context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Windows.Forms;
using System.Collections;
using System.Drawing;
using System.IO;
using PrimerProLocalization;
using GenLib;
using StandardFormatLib;
namespace PrimerProObjects
{
/// <summary>
///
/// </summary>
public class TextData
{
private Settings m_Settings;
private string m_FileName;
private ArrayList m_Paragraphs;
private const string kSeparator = Constants.Tab;
//private const string kLoad = "Loading Text Data";
//private const string kBuild = "Building Text Data";
//private const string kBuildWL = "Building Word List from Text Data";
//private const string kBuildSFM = "Building SFM Word List";
public const string kMergeTextData = "<Merged>";
public const string kPara = "Para";
public const string kSent = "Sent";
public const string kWord = "Word";
public TextData(Settings s)
{
m_Settings = s;
m_FileName = "";
m_Paragraphs = null;
}
public string FileName
{
get {return m_FileName;}
set {m_FileName = value;}
}
public ArrayList Paragraphs
{
get {return m_Paragraphs;}
set {m_Paragraphs = value;}
}
public void AddParagraph(Paragraph para)
{
m_Paragraphs.Add(para);
}
public void DelParagraph(int n)
{
m_Paragraphs.RemoveAt(n);
}
public Paragraph GetParagraph(int n)
{
if ( n < this.ParagraphCount() )
return (Paragraph) m_Paragraphs[n];
else return null;
}
public int ParagraphCount()
{
if (m_Paragraphs == null )
return 0;
else return m_Paragraphs.Count;
}
public int SentenceCount()
{
int nCount = 0;
Paragraph para = null;
for (int i = 0; i < this.ParagraphCount(); i++)
{
para = this.GetParagraph(i);
nCount = nCount + para.SentenceCount();
}
return nCount;
}
public int WordCount()
{
int nCount = 0;
Paragraph para = null;
for (int i = 0; i < this.ParagraphCount(); i++)
{
para = this.GetParagraph(i);
nCount = nCount + para.WordCount();
}
return nCount;
}
public int SyllableCount()
{
int nCount = 0;
Paragraph para = null;
for (int i = 0; i < this.ParagraphCount(); i++)
{
para = this.GetParagraph(i);
nCount = nCount + para.SyllableCount();
}
return nCount;
}
public int MaxNumberOfWordsInSentences()
{
int nMax = 0;
int nCount = 0;
Paragraph para = null;
for (int i = 0; i < this.ParagraphCount(); i++)
{
para = this.GetParagraph(i);
nCount = para.MaxNumberOfWordsInSentences();
if (nCount > nMax)
nMax = nCount;
}
return nMax;
}
public int MaxNumberOfSyllablesInWords()
{
int nMax = 0;
int nCount = 0;
Paragraph para = null;
for (int i = 0; i < this.ParagraphCount(); i++)
{
para = this.GetParagraph(i);
nCount = para.MaxNumberOfSyllablesinWords();
if (nCount > nMax)
nMax = nCount;
}
return nMax;
}
public int AvgNumberOfWordsInSentences()
{
int nAvg = 0;
int nTotal = 0;
Paragraph para = null;
for (int i = 0; i < this.ParagraphCount(); i++)
{
para = this.GetParagraph(i);
nTotal = nTotal + para.AvgNumberOfWordInSentences();
}
if (this.ParagraphCount() > 0)
nAvg = nTotal / this.ParagraphCount();
return nAvg;
}
public int AvgNumberOfSyllablesInWords()
{
int nAvg = 0;
int numberWords = 0;
int numberSyllables = 0;
Sentence sent = null;
Word word = null;
Paragraph para = null;
for (int i = 0; i < this.ParagraphCount(); i++)
{
para = this.GetParagraph(i);
if (para != null)
{
for (int j = 0; j < this.SentenceCount(); j++)
{
sent = para.GetSentence(j);
if (sent != null)
{
for (int k = 0; k < sent.WordCount(); k++)
{
word = sent.GetWord(k);
if (word != null)
numberSyllables = numberSyllables + word.SyllableCount();
}
numberWords = numberWords + sent.WordCount();
}
}
}
}
if (numberWords > 0)
nAvg = numberSyllables / numberWords;
return nAvg;
}
public string BuildTextDataAsString()
{
string strData = "";
string strMsg = "";
//FormProgressBar form = new FormProgressBar(TextData.kBuild);
strMsg = m_Settings.LocalizationTable.GetMessage("TextData12");
if (strMsg == "")
strMsg = "Building Text Data";
FormProgressBar form = new FormProgressBar(strMsg);
form.PB_Init(0, this.ParagraphCount());
if (this.m_FileName != "")
{
for (int i = 0; i < this.ParagraphCount(); i++)
{
form.PB_Update(i);
strData += GetParagraph(i).AsString() + Environment.NewLine;
//strData += Environment.NewLine;
}
}
//else MessageBox.Show("Need to import text data");
else
{
strMsg = m_Settings.LocalizationTable.GetMessage("TextData1");
if (strMsg == "")
strMsg = "Need to import text data first";
MessageBox.Show(strMsg);
}
form.Close();
return strData;
}
public ArrayList BuildTextDataAsArray()
{
ArrayList alData = new ArrayList();
string strPara = "";
string strMsg = "";
//FormProgressBar form = new FormProgressBar(TextData.kBuild);
strMsg = m_Settings.LocalizationTable.GetMessage("TextData12");
if (strMsg == "")
strMsg = "Building Text Data";
FormProgressBar form = new FormProgressBar(strMsg);
form.PB_Init(0, this.ParagraphCount());
if (this.m_FileName != "")
{
for (int i = 0; i < this.ParagraphCount(); i++)
{
form.PB_Update(i);
strPara = GetParagraph(i).AsString();
alData.Add(strPara);
}
}
//else MessageBox.Show("Need to import text data");
else
{
strMsg = m_Settings.LocalizationTable.GetMessage("TextData1");
if (strMsg == "")
strMsg = "Need to import text data first";
MessageBox.Show(strMsg);
}
form.Close();
return alData;
}
public TextData Load(string strFolder)
{
TextData td = null;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "txt files (*.txt)|*.txt|All Files (*.*)|*.*";
ofd.FileName = "";
ofd.DefaultExt = "*.txt";
ofd.InitialDirectory = strFolder;
ofd.CheckFileExists = true;
ofd.CheckPathExists = true;
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
td = new TextData(m_Settings);
if (td.LoadFile(ofd.FileName))
td.FileName = ofd.FileName;
else td.FileName = "";
}
return td;
}
public bool LoadFile(string strFileName)
{
bool fReturn = false;
Paragraph para = null;
this.FileName = strFileName;
string strMsg = "";
if (File.Exists(strFileName))
{
try
{
string[] strLines = File.ReadAllLines(strFileName);
int nCount = strLines.GetLength(0);
//FormProgressBar form = new FormProgressBar(TextData.kLoad));
strMsg = m_Settings.LocalizationTable.GetMessage("TextData11");
if (strMsg == "")
strMsg = "Loading Text Data";
FormProgressBar form = new FormProgressBar(strMsg);
form.PB_Init(0, nCount);
if (this.Paragraphs == null)
this.Paragraphs = new ArrayList();
int n = 0;
foreach (string strPara in strLines)
{
n++;
form.PB_Update(n);
if (strPara != "")
{
para = new Paragraph(strPara, m_Settings);
this.AddParagraph(para);
}
}
form.Close();
fReturn = true;
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
fReturn = false;
}
}
//else MessageBox.Show(strFileName + " does not exist");
else
{
strMsg = m_Settings.LocalizationTable.GetMessage("TextData2");
if (strMsg == "")
strMsg = "does not exist";
MessageBox.Show(strFileName + Constants.Space + strMsg);
}
return fReturn;
}
public TextData Merge(string strFolder)
{
TextData td = this;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "txt files (*.txt)|*.txt|All Files (*.*)|*.*";
ofd.FileName = "";
ofd.DefaultExt = "*.txt";
ofd.InitialDirectory = strFolder;
ofd.CheckFileExists = true;
ofd.CheckPathExists = true;
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
if (td.LoadFile(ofd.FileName))
td.FileName = TextData.kMergeTextData;
else td.FileName = "";
}
return td;
}
public bool Save(string strFolder)
{
bool fReturn = false;
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "txt files (*.txt)|*.txt|All Files (*.*)|*.*";
if (this.FileName == TextData.kMergeTextData)
sfd.FileName = "";
else sfd.FileName = this.FileName;
sfd.DefaultExt = "*.txt";
sfd.InitialDirectory = strFolder;
sfd.CheckPathExists = true;
if (sfd.ShowDialog()== DialogResult.OK)
{
this.SaveFile(sfd.FileName);
this.FileName = sfd.FileName;
fReturn = true;
}
return fReturn;
}
public void SaveFile(string strFileName)
{
string strText = this.BuildTextDataAsString();
StreamWriter sw = File.CreateText(strFileName);
sw.Write(strText);
sw.Close();
}
public WordList BuildWordList()
{
WordList wl = new WordList(m_Settings);
Paragraph para = null;
Sentence sent = null;
Word word = null;
//string strmsg = "Loading Text Data";
string strMsg = m_Settings.LocalizationTable.GetMessage("TextData13");
if (strMsg == "")
strMsg = "Loading Text Data";
FormProgressBar form = new FormProgressBar(strMsg);
form.PB_Init(0, this.ParagraphCount());
for (int i = 0; i < this.ParagraphCount(); i++)
{
form.PB_Update(i);
para = this.GetParagraph(i);
for (int j = 0; j < para.SentenceCount(); j++)
{
sent = para.GetSentence(j);
for (int k = 0; k < sent.WordCount(); k++)
{
word = sent.GetWord(k);
if (word != null)
wl.AddWord(word);
}
}
}
form.Close();
return wl;
}
public WordList BuildWordListWithNoDuplicates()
{
WordList wl = new WordList(m_Settings);
SortedList sl = new SortedList();
Paragraph para = null;
Sentence sent = null;
Word word = null;
//string strmsg ="Loading Text Data";
string strMsg = m_Settings.LocalizationTable.GetMessage("TextData13");
if (strMsg == "")
strMsg = "Loading Text Data";
FormProgressBar form = new FormProgressBar(strMsg);
form.PB_Init(0, this.ParagraphCount());
for (int i = 0; i < this.ParagraphCount(); i++)
{
form.PB_Update(i);
para = this.GetParagraph(i);
for (int j = 0; j < para.SentenceCount(); j++)
{
sent = para.GetSentence(j);
for (int k = 0; k < sent.WordCount(); k++)
{
word = sent.GetWord(k);
if (word != null)
{
if (!sl.ContainsKey(word.DisplayWord))
{
wl.AddWord(word);
sl.Add(word.DisplayWord, word);
}
}
}
}
}
form.Close();
return wl;
}
public GraphemeInventory BuildSyllabaryInventory()
{
GraphemeInventory gi = new GraphemeInventory(m_Settings);
Paragraph para = null;
Sentence sent = null;
Word word = null;
Syllograph syllograph = null;
string strGrapheme = "";
//string strMsg = "Building syllograph inventory";
string strMsg = m_Settings.LocalizationTable.GetMessage("TextData10");
if (strMsg == "")
strMsg = "Building syllograph inventory";
FormProgressBar form = new FormProgressBar(strMsg);
form.PB_Init(0, this.ParagraphCount());
for (int i = 0; i < this.ParagraphCount(); i++)
{
form.PB_Update(i);
para = this.GetParagraph(i);
for (int j = 0; j < para.SentenceCount(); j++)
{
sent = para.GetSentence(j);
for (int k = 0; k < sent.WordCount(); k++)
{
word = sent.GetWord(k);
for (int l = 0; l < word.GraphemeCount(); l++)
{
strGrapheme = word.GetGrapheme(l).Symbol;
if (strGrapheme != "")
{
if (!gi.IsInInventory(strGrapheme))
{
syllograph = new Syllograph(strGrapheme);
syllograph.UpperCase = strGrapheme;
gi.AddSyllograph(syllograph);
}
}
}
}
}
}
form.Close();
return gi;
}
public SortedList BuildSortedListOfWords(bool fIgnore)
{
SortedList sl = new SortedList(StringComparer.OrdinalIgnoreCase);
Paragraph para = null;
Sentence sent = null;
Word word = null;
string strWord = "";
for (int i = 0; i < this.ParagraphCount(); i++)
{
para = this.GetParagraph(i);
for (int j = 0; j < para.SentenceCount(); j++)
{
sent = para.GetSentence(j);
for (int k = 0; k < sent.WordCount(); k++)
{
word = sent.GetWord(k);
if (fIgnore)
strWord = word.GetWordWithoutTone();
else strWord = word.DisplayWord;
if (strWord != "")
if ( sl.IndexOfKey(strWord) < 0 )
sl.Add(strWord, strWord);
}
}
}
return sl;
}
public StandardFormatFile BuildStandardFormatFile()
{
OptionList ol = m_Settings.OptionSettings;
StandardFormatRecord sfr = null;
StandardFormatField field = null;
WordList wl = m_Settings.WordList;
Paragraph para = null;
Sentence sent = null;
Word word = null;
string strDisplayWord = "";
string strDisplayWordUSV = ""; //Unicode values for display word
SortedList sl = new SortedList(); //Use to build records in alphabetical order and without duplicates
//FormProgressBar form = new FormProgressBar(TextData.kBuildSFM);
string strMsg = m_Settings.LocalizationTable.GetMessage("TextData14");
if (strMsg == "")
strMsg = "Building SFM Word List";
FormProgressBar form = new FormProgressBar(strMsg);
form.PB_Init(0, this.ParagraphCount() - 1);
for (int i = 0; i < this.ParagraphCount(); i++)
{
para = this.GetParagraph(i);
for (int j = 0; j < para.SentenceCount(); j++)
{
sent = para.GetSentence(j);
for (int k = 0; k < sent.WordCount(); k++)
{
word = sent.GetWord(k);
if (word != null)
{
strDisplayWord = word.GetWordInLowerCase().Trim();
strDisplayWordUSV = Funct.GetUnicodeString(strDisplayWord);
if (strDisplayWord != "") //if real word
{
if (!sl.ContainsKey(strDisplayWordUSV)) //if not in sff
{
sfr = new StandardFormatRecord();
if (wl.IsWordInList(strDisplayWord))
{
word = wl.GetWord2(strDisplayWord);
//Add fields to record
field = new StandardFormatField(ol.FMLexicon, word.DisplayWord);
sfr.AddField(field);
field = new StandardFormatField(ol.FMPS, word.PartOfSpeech);
sfr.AddField(field);
field = new StandardFormatField(ol.FMGlossEnglish, word.GlossEnglish);
sfr.AddField(field);
if (word.GlossNational != "")
{
field = new StandardFormatField(ol.FMGlossNational, word.GlossNational);
sfr.AddField(field);
}
if (word.GlossRegional != "")
{
field = new StandardFormatField(ol.FMGlossRegional, word.GlossRegional);
sfr.AddField(field);
}
if (word.Plural != "")
{
field = new StandardFormatField(ol.FMPlural, word.Plural);
sfr.AddField(field);
}
if (word.Root != null)
{
if (word.Root.DisplayRoot != "")
{
field = new StandardFormatField(ol.
FMRoot, word.Root.DisplayRoot);
sfr.AddField(field);
}
}
}
else
{
//Add fields to record
field = new StandardFormatField(ol.FMLexicon, strDisplayWord);
sfr.AddField(field);
field = new StandardFormatField(ol.FMPS, "");
sfr.AddField(field);
field = new StandardFormatField(ol.FMGlossEnglish, "");
sfr.AddField(field);
}
// Add record (word) to file
sl.Add(strDisplayWordUSV, sfr);
}
//else
//{
// MessageBox.Show("Already in SortedList: " + strDisplayWord);
//}
}
}
}
}
form.PB_Update(i);
}
form.Close();
StandardFormatFile sff = new StandardFormatFile();
for (int i =0; i < sl.Count; i++)
{
sfr = (StandardFormatRecord) sl.GetByIndex(i);
sff.AddRecord(sfr);
}
return sff;
}
public GraphemeInventory UpdateGraphemeCounts(GraphemeInventory gi, bool fIgnoreSightWords, bool fIgnoreTone)
{
Consonant cns = null;
Vowel vwl = null;
Tone tone = null;
Syllograph syllograph = null;
Paragraph para = null;
Sentence snt = null;
Word wrd = null;
Grapheme grf = null;
string strSym;
// Initialize Counts
for (int k = 0; k < gi.ConsonantCount(); k++)
{
cns = gi.GetConsonant(k);
cns.InitCountInTextData();
gi.UpdConsonant(k, cns);
}
for (int k = 0; k < gi.VowelCount(); k++)
{
vwl = gi.GetVowel(k);
vwl.InitCountInTextData();
gi.UpdVowel(k, vwl);
}
for (int k = 0; k < gi.ToneCount(); k++)
{
tone = gi.GetTone(k);
tone.InitCountInTextData();
gi.UpdTone(k, tone);
}
for (int k = 0; k < gi.SyllographCount(); k++)
{
syllograph = gi.GetSyllograph(k);
syllograph.InitCountInTextData();
gi.UpdSyllograph(k, syllograph);
}
int nPara = this.ParagraphCount();
for (int i = 0; i < nPara; i++)
{
para = this.GetParagraph(i); //next paragraph
int nSent = para.SentenceCount();
for (int j = 0; j < nSent; j++)
{
snt = para.GetSentence(j); //next sentence
int nWord = snt.WordCount();
for ( int k = 0; k <nWord; k++)
{
wrd = snt.GetWord(k); //next word
int ndx = 0; //index in inventory for grapheme
if ( !fIgnoreSightWords || !wrd.IsSightWord() )
{
for (int n = 0; n < wrd.GraphemeCount(); n++)
{
strSym = wrd.GetGrapheme(n).Symbol;
if (gi.IsInInventory(strSym))
{
ndx = gi.FindConsonantIndex(strSym);
if (ndx >= 0)
{
cns = gi.GetConsonant(ndx);
cns.IncrCountInTextData();
gi.UpdConsonant(ndx, cns);
}
ndx = gi.FindVowelIndex(strSym);
if (ndx >= 0)
{
vwl = gi.GetVowel(ndx);
vwl.IncrCountInTextData();
gi.UpdVowel(ndx, vwl);
}
ndx = gi.FindToneIndex(strSym);
if (ndx >= 0)
{
if (fIgnoreTone)
{
grf = gi.GetTone(ndx).ToneBearingUnit;
if ((grf != null) && (grf.IsVowel))
{
ndx = gi.FindVowelIndex(grf.Symbol);
if (ndx >= 0)
{
vwl = gi.GetVowel(ndx);
vwl.IncrCountInTextData();
gi.UpdVowel(ndx, vwl);
}
}
if ((grf != null) && (grf.IsConsonant))
{
ndx = gi.FindConsonantIndex(grf.Symbol);
if (ndx >= 0)
{
cns = gi.GetConsonant(ndx);
cns.IncrCountInTextData();
gi.UpdConsonant(ndx, cns);
}
}
}
else
{
tone = gi.GetTone(ndx);
tone.IncrCountInTextData();
gi.UpdTone(ndx, tone);
}
}
ndx = gi.FindSyllographIndex(strSym);
if (ndx >= 0)
{
syllograph = gi.GetSyllograph(ndx);
syllograph.IncrCountInTextData();
gi.UpdSyllograph(ndx, syllograph);
}
}
}
}
}
}
}
return gi;
}
public string GetMissingGraphemes()
{
string strText = "";
ArrayList alMissingSegs = new ArrayList();
Paragraph para = null;
Sentence snt = null;
Word wrd = null;
string strSymbol = "";
int nWidth = this.m_Settings.OptionSettings.MaxSizeGrapheme + 2;
char chSpace = Constants.Space;
TextData td = m_Settings.TextData;
//For each paragraph in text data
int nPara = td.ParagraphCount();
for (int i = 0; i < nPara; i++)
{
para = td.GetParagraph(i);
//For each sentence in paragraph
int nSent = para.SentenceCount();
for (int j = 0; j < nSent; j++)
{
snt = para.GetSentence(j);
//For each word in sentence
int nWord = snt.WordCount();
for (int k = 0; k < nWord; k++)
{
wrd = snt.GetWord(k);
for (int n = 0; n < wrd.GraphemeCount(); n++)
{
//For Each grapheme in word
strSymbol = wrd.GetGrapheme(n).Symbol;
if ( strSymbol != chSpace.ToString() )
{
if ( !m_Settings.GraphemeInventory.IsInInventory(strSymbol) )
{
if ( !alMissingSegs.Contains(strSymbol) )
{
alMissingSegs.Add(strSymbol);
strText += strSymbol.PadRight(nWidth, chSpace);
}
}
}
}
}
}
}
return strText;
}
public string GetMissingWords()
{
string strText = "";
ArrayList alMissingWords = new ArrayList();
Paragraph para = null;
Sentence snt = null;
Word wrd = null;
string strWord = "";
TextData td = m_Settings.TextData;
//For each paragraph in text data
int nPara = td.ParagraphCount();
for (int i = 0; i < nPara; i++)
{
para = td.GetParagraph(i);
//For each sentence in paragraph
int nSent = para.SentenceCount();
for (int j = 0; j < nSent; j++)
{
snt = para.GetSentence(j);
//For each word in sentence
int nWord = snt.WordCount();
for (int k = 0; k < nWord; k++)
{
wrd = snt.GetWord(k);
strWord = wrd.DisplayWord;
if ( !m_Settings.WordList.IsWordInList(strWord) )
{
if ( !alMissingWords.Contains(strWord) )
{
alMissingWords.Add(strWord);
strText += strWord + Environment.NewLine;
}
}
}
}
}
return strText;
}
public SortedList GetWordCounts(char SortOrder, bool IgnoreTone)
// SortOder is alphaetic or numeric
{
SortedList sl = new SortedList(StringComparer.OrdinalIgnoreCase);
int nCount = 0;
Paragraph para = null;
Sentence snt = null;
Word wrd = null;
string strWord = "";
TextData td = m_Settings.TextData;
//For each paragraph in text data
int nPara = td.ParagraphCount();
for (int i = 0; i < nPara; i++)
{
para = td.GetParagraph(i);
//For each sentence in paragraph
int nSent = para.SentenceCount();
for (int j = 0; j < nSent; j++)
{
snt = para.GetSentence(j);
//For each word in sentence
int nWord = snt.WordCount();
for (int k = 0; k < nWord; k++)
{
wrd = snt.GetWord(k);
if (wrd != null)
{
if (IgnoreTone)
strWord = wrd.GetWordWithoutTone();
else strWord = wrd.DisplayWord;
if (strWord != "") //skip empty words
{
if (sl.ContainsKey(strWord))
{
nCount = (int)sl[strWord];
sl[strWord] = nCount + 1;
}
else
{
sl.Add(strWord, 1);
}
}
}
}
}
}
if (SortOrder == 'N')
{
SortedList slNumer = new SortedList(StringComparer.OrdinalIgnoreCase);
string strVal = "";
string strKey = "";
for (int i = 0; i < sl.Count; i++)
{
strVal = sl.GetKey(i).ToString();
strKey = sl.GetByIndex(i).ToString().PadLeft(5, Constants.Space) + strVal;
slNumer.Add(strKey, strVal);
}
sl = slNumer;
}
return sl;
}
public SortedList GetSyllableCounts(char SortOrder, bool IgnoreTone, bool UseGraphemesTaught, ArrayList alGTO)
{
SortedList sl = new SortedList(StringComparer.OrdinalIgnoreCase);
int nCount = 0;
Paragraph para = null;
Sentence snt = null;
Word wrd = null;
Syllable syll = null;
string strSyll = "";
TextData td = m_Settings.TextData;
//For each paragraph in text data
int nPara = td.ParagraphCount();
for (int i = 0; i < nPara; i++)
{
para = td.GetParagraph(i);
//For each sentence in paragraph
int nSent = para.SentenceCount();
for (int j = 0; j < nSent; j++)
{
snt = para.GetSentence(j);
//For each word in sentence
int nWord = snt.WordCount();
for (int k = 0; k < nWord; k++)
{
wrd = snt.GetWord(k);
if (wrd != null)
{
int nSyll = wrd.SyllableCount();
for (int l = 0; l < nSyll; l++)
{
syll = wrd.GetSyllable(l);
strSyll = "";
if (UseGraphemesTaught)
if (syll.IsBuildable(alGTO))
{
if (IgnoreTone)
strSyll = syll.GetSyllableWithoutTone();
else strSyll = syll.GetSyllableInLowerCase();
}
else strSyll = "";
else
{
if (IgnoreTone)
strSyll = syll.GetSyllableWithoutTone();
else strSyll = syll.GetSyllableInLowerCase();
}
if (strSyll != "") //skip empty syllables
{
if (sl.ContainsKey(strSyll))
{
nCount = (int)sl[strSyll];
sl[strSyll] = nCount + 1;
}
else
{
sl.Add(strSyll, 1);
}
}
}
}
}
}
}
if (SortOrder == 'N')
{
SortedList slNumer = new SortedList(StringComparer.OrdinalIgnoreCase);
string strVal = "";
string strKey = "";
for (int i = 0; i < sl.Count; i++)
{
strVal = sl.GetKey(i).ToString();
strKey = sl.GetByIndex(i).ToString().PadLeft(5, Constants.Space) + strVal;
slNumer.Add(strKey, strVal);
}
sl = slNumer;
}
return sl;
}
//public SortedList GetSyllableCounts(char SortOrder, bool IgnoreTone)
//{
// SortedList sl = new SortedList(StringComparer.OrdinalIgnoreCase);
// int nCount = 0;
// Paragraph para = null;
// Sentence snt = null;
// Word wrd = null;
// Syllable syll = null;
// string strSyll = "";
// TextData td = m_Settings.TextData;
// //For each paragraph in text data
// int nPara = td.ParagraphCount();
// for (int i = 0; i < nPara; i++)
// {
// para = td.GetParagraph(i);
// //For each sentence in paragraph
// int nSent = para.SentenceCount();
// for (int j = 0; j < nSent; j++)
// {
// snt = para.GetSentence(j);
// //For each word in sentence
// int nWord = snt.WordCount();
// for (int k = 0; k < nWord; k++)
// {
// wrd = snt.GetWord(k);
// if (wrd != null)
// {
// int nSyll = wrd.SyllableCount();
// for (int l = 0; l < nSyll; l++)
// {
// syll = wrd.GetSyllable(l);
// if (IgnoreTone)
// strSyll = syll.GetSyllableWithoutTone();
// else strSyll = syll.GetSyllableInLowerCase();
// if (strSyll != "") //skip empty words
// {
// if (sl.ContainsKey(strSyll))
// {
// nCount = (int)sl[strSyll];
// sl[strSyll] = nCount + 1;
// }
// else
// {
// sl.Add(strSyll, 1);
// }
// }
// }
// }
// }
// }
// }
// if (SortOrder == 'N')
// {
// SortedList slNumer = new SortedList(StringComparer.OrdinalIgnoreCase);
// string strVal = "";
// string strKey = "";
// for (int i = 0; i < sl.Count; i++)
// {
// strVal = sl.GetKey(i).ToString();
// strKey = sl.GetByIndex(i).ToString().PadLeft(5, Constants.Space) + strVal;
// slNumer.Add(strKey, strVal);
// }
// sl = slNumer;
// }
// return sl;
//}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace DotSpatial.Symbology.Forms
{
/// <summary>
/// HueSlider.
/// </summary>
[DefaultEvent("PositionChanging")]
public class HueSlider : Control
{
#region Fields
private int _dx;
private int _hueShift;
private bool _inverted;
private int _max;
private int _min;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="HueSlider"/> class.
/// </summary>
public HueSlider()
{
_min = 0;
_max = 360;
LeftHandle = new HueHandle(this)
{
Position = 72,
Left = true
};
RightHandle = new HueHandle(this)
{
Position = 288
};
}
#endregion
#region Events
/// <summary>
/// Occurs after the user has finished adjusting the positions of either of the sliders and has released control
/// </summary>
public event EventHandler PositionChanged;
/// <summary>
/// Occurs as the user is adjusting the positions on either of the sliders
/// </summary>
public event EventHandler PositionChanging;
#endregion
#region Properties
/// <summary>
/// Gets or sets an integer value indicating how much to adjust the hue to change where wrapping occurs.
/// </summary>
[Description("Gets or sets an integer value indicating how much to adjust the hue to change where wrapping occurs.")]
public int HueShift
{
get
{
return _hueShift;
}
set
{
_hueShift = value;
Invalidate();
}
}
/// <summary>
/// Gets or sets a value indicating whether the hue pattern should be flipped.
/// </summary>
public bool Inverted
{
get
{
return _inverted;
}
set
{
_inverted = value;
Invalidate();
}
}
/// <summary>
/// Gets or sets the floating point position of the left slider. This must range
/// between 0 and 1, and to the left of the right slider, (therefore with a value lower than the right slider.)
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[TypeConverter(typeof(ExpandableObjectConverter))]
public HueHandle LeftHandle { get; set; }
/// <summary>
/// Gets or sets the value represented by the left handle, taking into account
/// whether or not the slider has been reversed.
/// </summary>
public float LeftValue
{
get
{
if (_inverted)
{
return _max - LeftHandle.Position;
}
return LeftHandle.Position;
}
set
{
if (_inverted)
{
LeftHandle.Position = _max - value;
return;
}
LeftHandle.Position = value;
}
}
/// <summary>
/// Gets or sets the maximum allowed value for the slider.
/// </summary>
[Description("Gets or sets the maximum allowed value for the slider.")]
public int Maximum
{
get
{
return _max;
}
set
{
_max = value;
if (_max < RightHandle.Position) RightHandle.Position = _max;
if (_max < LeftHandle.Position) LeftHandle.Position = _max;
}
}
/// <summary>
/// Gets or sets the minimum allowed value for the slider.
/// </summary>
[Description("Gets or sets the minimum allowed value for the slider.")]
public int Minimum
{
get
{
return _min;
}
set
{
_min = value;
if (LeftHandle.Position < _min) LeftHandle.Position = _min;
if (RightHandle.Position < _min) RightHandle.Position = _min;
}
}
/// <summary>
/// Gets or sets the floating point position of the right slider. This must range
/// between 0 and 1, and to the right of the left slider.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[TypeConverter(typeof(ExpandableObjectConverter))]
public HueHandle RightHandle { get; set; }
/// <summary>
/// Gets or sets the value represented by the right handle, taking into account
/// whether or not the slider has been reversed.
/// </summary>
public float RightValue
{
get
{
if (_inverted)
{
return _max - RightHandle.Position;
}
return RightHandle.Position;
}
set
{
if (_inverted)
{
RightHandle.Position = _max - value;
return;
}
RightHandle.Position = value;
}
}
#endregion
#region Methods
/// <summary>
/// Uses the hue values from the specified start and end color to set the handle positions.
/// </summary>
/// <param name="startColor">The start color that represents the left hue.</param>
/// <param name="endColor">The start color that represents the right hue.</param>
public void SetRange(Color startColor, Color endColor)
{
int hStart = (int)startColor.GetHue();
int hEnd = (int)endColor.GetHue();
_inverted = hStart > hEnd;
LeftValue = hStart;
RightValue = hEnd;
}
/// <summary>
/// Controls the actual drawing for this gradient slider control.
/// </summary>
/// <param name="g">The graphics object used for drawing.</param>
/// <param name="clipRectangle">The clip rectangle.</param>
protected virtual void OnDraw(Graphics g, Rectangle clipRectangle)
{
using (GraphicsPath gp = new GraphicsPath())
{
Rectangle innerRect = new Rectangle(LeftHandle.Width, 3, Width - 1 - RightHandle.Width - LeftHandle.Width, Height - 1 - 6);
gp.AddRoundedRectangle(innerRect, 2);
if (Width == 0 || Height == 0) return;
// Create a rounded gradient effect as the backdrop that other colors will be drawn to
LinearGradientBrush silver = new LinearGradientBrush(ClientRectangle, BackColor.Lighter(.2F), BackColor.Darker(.6F), LinearGradientMode.Vertical);
g.FillPath(silver, gp);
silver.Dispose();
using (LinearGradientBrush lgb = new LinearGradientBrush(innerRect, Color.White, Color.White, LinearGradientMode.Horizontal))
{
Color[] colors = new Color[37];
float[] positions = new float[37];
for (int i = 0; i <= 36; i++)
{
int j = _inverted ? 36 - i : i;
colors[j] = SymbologyGlobal.ColorFromHsl(((i * 10) + _hueShift) % 360, 1, .7).ToTransparent(.7f);
positions[i] = i / 36f;
}
ColorBlend cb = new ColorBlend
{
Colors = colors,
Positions = positions
};
lgb.InterpolationColors = cb;
g.FillPath(lgb, gp);
}
g.DrawPath(Pens.Gray, gp);
}
if (Enabled)
{
LeftHandle.Draw(g);
RightHandle.Draw(g);
}
}
/// <summary>
/// Initiates slider dragging.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && Enabled)
{
Rectangle l = LeftHandle.GetBounds();
if (l.Contains(e.Location) && LeftHandle.Visible)
{
_dx = LeftHandle.GetBounds().Right - e.X;
LeftHandle.IsDragging = true;
}
Rectangle r = RightHandle.GetBounds();
if (r.Contains(e.Location) && RightHandle.Visible)
{
_dx = e.X - RightHandle.GetBounds().Left;
RightHandle.IsDragging = true;
}
}
base.OnMouseDown(e);
}
/// <summary>
/// Handles slider dragging.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseMove(MouseEventArgs e)
{
float w = Width - LeftHandle.Width;
if (RightHandle.IsDragging)
{
float x = e.X - _dx;
int min = 0;
if (LeftHandle.Visible) min = LeftHandle.Width;
if (x > w) x = w;
if (x < min) x = min;
RightHandle.Position = _min + ((x / w) * (_max - _min));
if (LeftHandle.Visible)
{
if (LeftHandle.Position > RightHandle.Position)
{
LeftHandle.Position = RightHandle.Position;
}
}
OnPositionChanging();
}
if (LeftHandle.IsDragging)
{
float x = e.X + _dx;
int max = Width;
if (RightHandle.Visible) max = Width - RightHandle.Width;
if (x > max) x = max;
if (x < 0) x = 0;
LeftHandle.Position = _min + ((x / w) * (_max - _min));
if (RightHandle.Visible)
{
if (RightHandle.Position < LeftHandle.Position)
{
RightHandle.Position = LeftHandle.Position;
}
}
OnPositionChanging();
}
Invalidate();
base.OnMouseMove(e);
}
/// <summary>
/// Handles the mouse up situation.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseUp(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (RightHandle.IsDragging) RightHandle.IsDragging = false;
if (LeftHandle.IsDragging) LeftHandle.IsDragging = false;
OnPositionChanged();
}
base.OnMouseUp(e);
}
/// <summary>
/// Draw the clipped portion.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnPaint(PaintEventArgs e)
{
Rectangle clip = e.ClipRectangle;
if (clip.IsEmpty) clip = ClientRectangle;
Bitmap bmp = new Bitmap(clip.Width, clip.Height);
Graphics g = Graphics.FromImage(bmp);
g.TranslateTransform(-clip.X, -clip.Y);
g.Clip = new Region(clip);
g.Clear(BackColor);
g.SmoothingMode = SmoothingMode.AntiAlias;
OnDraw(g, clip);
g.Dispose();
e.Graphics.DrawImage(bmp, clip, new Rectangle(0, 0, clip.Width, clip.Height), GraphicsUnit.Pixel);
}
/// <summary>
/// Prevent flicker.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnPaintBackground(PaintEventArgs e)
{
}
/// <summary>
/// Fires the Position Changed event after sliders are released.
/// </summary>
protected virtual void OnPositionChanged()
{
PositionChanged?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Fires the Position Changing event while either slider is being dragged.
/// </summary>
protected virtual void OnPositionChanging()
{
PositionChanging?.Invoke(this, EventArgs.Empty);
}
#endregion
}
}
| |
#if UNITY_EDITOR
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
namespace Zios {
public enum GUIStyleField {
name,
textColor,
background,
border,
margin,
padding,
overflow,
font,
fontSize,
fontStyle,
alignment,
wordWrap,
richText,
clipping,
imagePosition,
contentOffset,
fixedWidth,
fixedHeight,
stretchWidth,
stretchHeight,
}
public static class GUIStyleExtension {
public static GUIStyle Rotate90(this GUIStyle current) {
float width = current.fixedWidth;
float height = current.fixedHeight;
current.fixedWidth = height;
current.fixedHeight = width;
current.margin = RectOffsetExtension.Rotate90(current.margin);
current.padding = RectOffsetExtension.Rotate90(current.padding);
return current;
}
public static GUIStyle Border(this GUIStyle current, int value, bool asCopy = true) {
return current.Border(value, value, value, value, asCopy);
}
public static GUIStyle Border(this GUIStyle current, int left, int right, int top, int bottom, bool asCopy = true) {
return current.Border(new RectOffset(left, right, top, bottom), asCopy);
}
public static GUIStyle Border(this GUIStyle current, RectOffset offset, bool asCopy = true) {
if (asCopy) { current = new GUIStyle(current); }
current.border = offset;
return current;
}
public static GUIStyle ContentOffset(this GUIStyle current, float x, float y, bool asCopy = true) {
return current.ContentOffset(new Vector2(x, y), asCopy);
}
public static GUIStyle ContentOffset(this GUIStyle current, Vector2 offset, bool asCopy = true) {
if (asCopy) { current = new GUIStyle(current); }
current.contentOffset = offset;
return current;
}
public static GUIStyle Clipping(this GUIStyle current, TextClipping clipping, bool asCopy = true) {
if (asCopy) { current = new GUIStyle(current); }
current.clipping = clipping;
return current;
}
public static GUIStyle Clipping(this GUIStyle current, string value, bool asCopy = true) {
var clipValue = value.ToLower() == "overflow" ? TextClipping.Overflow : TextClipping.Clip;
return current.Clipping(clipValue, asCopy);
}
public static GUIStyle FixedWidth(this GUIStyle current, float value, bool asCopy = true) {
if (asCopy) { current = new GUIStyle(current); }
current.fixedWidth = value;
return current;
}
public static GUIStyle FixedHeight(this GUIStyle current, float value, bool asCopy = true) {
if (asCopy) { current = new GUIStyle(current); }
current.fixedHeight = value;
return current;
}
public static GUIStyle Margin(this GUIStyle current, int value, bool asCopy = true) {
return current.Margin(value, value, value, value, asCopy);
}
public static GUIStyle Margin(this GUIStyle current, int left, int right, int top, int bottom, bool asCopy = true) {
return current.Margin(new RectOffset(left, right, top, bottom), asCopy);
}
public static GUIStyle Margin(this GUIStyle current, RectOffset offset, bool asCopy = true) {
if (asCopy) { current = new GUIStyle(current); }
current.margin = offset;
return current;
}
public static GUIStyle Padding(this GUIStyle current, int value, bool asCopy = true) {
return current.Padding(value, value, value, value, asCopy);
}
public static GUIStyle Padding(this GUIStyle current, int left, int right, int top, int bottom, bool asCopy = true) {
return current.Padding(new RectOffset(left, right, top, bottom), asCopy);
}
public static GUIStyle Padding(this GUIStyle current, RectOffset offset, bool asCopy = true) {
if (asCopy) { current = new GUIStyle(current); }
current.padding = offset;
return current;
}
public static GUIStyle Overflow(this GUIStyle current, int value, bool asCopy = true) {
return current.Overflow(value, value, value, value, asCopy);
}
public static GUIStyle Overflow(this GUIStyle current, int left, int right, int top, int bottom, bool asCopy = true) {
return current.Overflow(new RectOffset(left, right, top, bottom), asCopy);
}
public static GUIStyle Overflow(this GUIStyle current, RectOffset offset, bool asCopy = true) {
if (asCopy) { current = new GUIStyle(current); }
current.overflow = offset;
return current;
}
public static GUIStyle RichText(this GUIStyle current, bool value, bool asCopy = true) {
if (asCopy) { current = new GUIStyle(current); }
current.richText = value;
return current;
}
public static GUIStyle StretchHeight(this GUIStyle current, bool value, bool asCopy = true) {
if (asCopy) { current = new GUIStyle(current); }
current.stretchHeight = value;
return current;
}
public static GUIStyle StretchWidth(this GUIStyle current, bool value, bool asCopy = true) {
if (asCopy) { current = new GUIStyle(current); }
current.stretchWidth = value;
return current;
}
public static GUIStyle Alignment(this GUIStyle current, TextAnchor anchor, bool asCopy = true) {
if (asCopy) { current = new GUIStyle(current); }
current.alignment = anchor;
return current;
}
public static GUIStyle Alignment(this GUIStyle current, string value, bool asCopy = true) {
value = value.ToLower();
TextAnchor anchor = current.alignment;
if (value == "upperleft") { anchor = TextAnchor.UpperLeft; }
if (value == "uppercenter") { anchor = TextAnchor.UpperCenter; }
if (value == "upperright") { anchor = TextAnchor.UpperRight; }
if (value == "middleleft") { anchor = TextAnchor.MiddleLeft; }
if (value == "middlecenter") { anchor = TextAnchor.MiddleCenter; }
if (value == "middleright") { anchor = TextAnchor.MiddleRight; }
if (value == "lowerleft") { anchor = TextAnchor.LowerLeft; }
if (value == "lowercenter") { anchor = TextAnchor.LowerCenter; }
if (value == "lowerright") { anchor = TextAnchor.LowerRight; }
return current.Alignment(anchor, asCopy);
}
public static GUIStyle Font(this GUIStyle current, Font font, bool asCopy = true) {
if (asCopy) { current = new GUIStyle(current); }
current.font = font;
return current;
}
public static GUIStyle Font(this GUIStyle current, string value, bool asCopy = true) {
Font font = FileManager.GetAsset<Font>(value);
if (font != null) { return current.Font(font, asCopy); }
return current;
}
public static GUIStyle FontSize(this GUIStyle current, int value, bool asCopy = true) {
if (asCopy) { current = new GUIStyle(current); }
current.fontSize = value;
return current;
}
public static GUIStyle FontStyle(this GUIStyle current, FontStyle fontStyle, bool asCopy = true) {
if (asCopy) { current = new GUIStyle(current); }
current.fontStyle = fontStyle;
return current;
}
public static GUIStyle FontStyle(this GUIStyle current, string value, bool asCopy = true) {
value = value.ToLower();
var fontStyle = current.fontStyle;
if (value == "normal") { fontStyle = UnityEngine.FontStyle.Normal; }
if (value == "bold") { fontStyle = UnityEngine.FontStyle.Bold; }
if (value == "italic") { fontStyle = UnityEngine.FontStyle.Italic; }
if (value == "boldanditalic") { fontStyle = UnityEngine.FontStyle.BoldAndItalic; }
return current.FontStyle(fontStyle, asCopy);
}
public static GUIStyle ImagePosition(this GUIStyle current, ImagePosition imagePosition, bool asCopy = true) {
if (asCopy) { current = new GUIStyle(current); }
current.imagePosition = imagePosition;
return current;
}
public static GUIStyle Background(this GUIStyle current, Texture2D background, bool asCopy = true) {
if (asCopy) { current = new GUIStyle(current); }
current.normal.background = background;
return current;
}
public static GUIStyle Background(this GUIStyle current, string value, bool asCopy = true) {
if (value.IsEmpty()) { return current.Background(new Texture2D(0, 0), asCopy); }
Texture2D texture = FileManager.GetAsset<Texture2D>(value);
if (texture != null) { return current.Background(texture, asCopy); }
return current;
}
public static GUIStyle TextColor(this GUIStyle current, Color textColor, bool asCopy = true) {
if (asCopy) { current = new GUIStyle(current); }
current.normal.textColor = textColor;
return current;
}
public static GUIStyle TextColor(this GUIStyle current, string value, bool asCopy = true) {
return current.TextColor(Colors.FromHex(value), asCopy);
}
public static GUIStyle ImagePosition(this GUIStyle current, string value, bool asCopy = true) {
value = value.ToLower();
ImagePosition imagePosition = current.imagePosition;
if (value.ContainsAny("imageleft", "left")) { imagePosition = UnityEngine.ImagePosition.ImageLeft; }
if (value.ContainsAny("imageabove", "above")) { imagePosition = UnityEngine.ImagePosition.ImageAbove; }
if (value.ContainsAny("imageonly")) { imagePosition = UnityEngine.ImagePosition.ImageOnly; }
if (value.ContainsAny("textOnly")) { imagePosition = UnityEngine.ImagePosition.TextOnly; }
return current.ImagePosition(imagePosition, asCopy);
}
public static GUIStyle WordWrap(this GUIStyle current, bool value, bool asCopy = true) {
if (asCopy) { current = new GUIStyle(current); }
current.wordWrap = value;
return current;
}
public static Dictionary<string, GUIStyleState> GetNamedStates(this GUIStyle current, bool offStates = true, bool onStates = true) {
var states = new Dictionary<string, GUIStyleState>();
if (offStates) {
states["normal"] = current.normal;
states["hover"] = current.hover;
states["active"] = current.active;
states["focused"] = current.focused;
}
if (onStates) {
states["onNormal"] = current.onNormal;
states["onHover"] = current.onHover;
states["onActive"] = current.onActive;
states["onFocused"] = current.onFocused;
}
return states;
}
public static GUIStyleState[] GetStates(this GUIStyle current, bool offStates = true, bool onStates = true) {
return current.GetNamedStates(offStates, onStates).Values.ToArray();
}
public static GUIStyle Rename(this GUIStyle current, string name) {
current.name = name;
return current;
}
public static GUIStyle UseState(this GUIStyle current, string find, string replace = "normal", bool asCopy = true) {
if (asCopy) { current = new GUIStyle(current); }
var states = current.GetNamedStates();
if (states.ContainsKey(replace)) {
states[replace].textColor = states[find].textColor;
states[replace].background = states[find].background;
}
if (replace.ContainsAny("*", "all")) {
foreach (var item in states) {
states[item.Key].textColor = states[find].textColor;
states[item.Key].background = states[find].background;
}
}
return current;
}
public static GUIStyle Use(this GUIStyle current, GUIStyle other) {
if (current.IsNull() || other.IsNull()) { return current; }
current.normal = other.normal;
current.hover = other.hover;
current.focused = other.focused;
current.active = other.active;
current.onNormal = other.onNormal;
current.onHover = other.onHover;
current.onFocused = other.onFocused;
current.onActive = other.onActive;
current.border = other.border;
current.margin = other.margin;
current.padding = other.padding;
current.overflow = other.overflow;
current.font = other.font;
current.fontSize = other.fontSize;
current.fontStyle = other.fontStyle;
current.alignment = other.alignment;
current.wordWrap = other.wordWrap;
current.richText = other.richText;
current.clipping = other.clipping;
current.imagePosition = other.imagePosition;
current.contentOffset = other.contentOffset;
current.fixedWidth = other.fixedWidth;
current.fixedHeight = other.fixedHeight;
current.stretchWidth = other.stretchWidth;
current.stretchHeight = other.stretchHeight;
return current;
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using Funq;
using NServiceKit.Common.Utils;
using NServiceKit.Common.Web;
using NServiceKit.ServiceHost;
using NServiceKit.Text;
namespace NServiceKit.WebHost.Endpoints.Extensions
{
/// <summary>A HTTP listener request wrapper.</summary>
public partial class HttpListenerRequestWrapper
: IHttpRequest
{
private static readonly string physicalFilePath;
private readonly HttpListenerRequest request;
/// <summary>Gets or sets the container.</summary>
///
/// <value>The container.</value>
public Container Container { get; set; }
static HttpListenerRequestWrapper()
{
physicalFilePath = "~".MapAbsolutePath();
}
/// <summary>Gets the request.</summary>
///
/// <value>The request.</value>
public HttpListenerRequest Request
{
get { return request; }
}
/// <summary>The underlying ASP.NET or HttpListener HttpRequest.</summary>
///
/// <value>The original request.</value>
public object OriginalRequest
{
get { return request; }
}
/// <summary>Initializes a new instance of the NServiceKit.WebHost.Endpoints.Extensions.HttpListenerRequestWrapper class.</summary>
///
/// <param name="request">The request.</param>
public HttpListenerRequestWrapper(HttpListenerRequest request)
: this(null, request) { }
/// <summary>Initializes a new instance of the NServiceKit.WebHost.Endpoints.Extensions.HttpListenerRequestWrapper class.</summary>
///
/// <param name="operationName">The name of the operation.</param>
/// <param name="request"> The request.</param>
public HttpListenerRequestWrapper(
string operationName, HttpListenerRequest request)
{
this.OperationName = operationName;
this.request = request;
}
/// <summary>Try resolve.</summary>
///
/// <typeparam name="T">Generic type parameter.</typeparam>
///
/// <returns>A T.</returns>
public T TryResolve<T>()
{
return Container == null
? EndpointHost.AppHost.TryResolve<T>()
: Container.TryResolve<T>();
}
/// <summary>The name of the service being called (e.g. Request DTO Name)</summary>
///
/// <value>The name of the operation.</value>
public string OperationName { get; set; }
/// <summary>The entire string contents of Request.InputStream.</summary>
///
/// <returns>The raw body.</returns>
public string GetRawBody()
{
if (bufferedStream != null)
{
return bufferedStream.ToArray().FromUtf8Bytes();
}
using (var reader = new StreamReader(InputStream))
{
return reader.ReadToEnd();
}
}
/// <summary>Gets URL of the raw.</summary>
///
/// <value>The raw URL.</value>
public string RawUrl
{
get { return request.RawUrl; }
}
/// <summary>Gets URI of the absolute.</summary>
///
/// <value>The absolute URI.</value>
public string AbsoluteUri
{
get { return request.Url.AbsoluteUri.TrimEnd('/'); }
}
/// <summary>The Remote Ip as reported by Request.UserHostAddress.</summary>
///
/// <value>The user host address.</value>
public string UserHostAddress
{
get { return request.UserHostAddress; }
}
/// <summary>The value of the X-Forwarded-For header, null if null or empty.</summary>
///
/// <value>The x coordinate forwarded for.</value>
public string XForwardedFor
{
get
{
return String.IsNullOrEmpty(request.Headers[HttpHeaders.XForwardedFor]) ? null : request.Headers[HttpHeaders.XForwardedFor];
}
}
/// <summary>The value of the X-Real-IP header, null if null or empty.</summary>
///
/// <value>The x coordinate real IP.</value>
public string XRealIp
{
get
{
return String.IsNullOrEmpty(request.Headers[HttpHeaders.XRealIp]) ? null : request.Headers[HttpHeaders.XRealIp];
}
}
private string remoteIp;
/// <summary>The Remote Ip as reported by X-Forwarded-For, X-Real-IP or Request.UserHostAddress.</summary>
///
/// <value>The remote IP.</value>
public string RemoteIp
{
get
{
return remoteIp ??
(remoteIp = XForwardedFor ??
(XRealIp ??
((request.RemoteEndPoint != null) ? request.RemoteEndPoint.Address.ToString() : null)));
}
}
/// <summary>e.g. is https or not.</summary>
///
/// <value>true if this object is secure connection, false if not.</value>
public bool IsSecureConnection
{
get { return request.IsSecureConnection; }
}
/// <summary>Gets a list of types of the accepts.</summary>
///
/// <value>A list of types of the accepts.</value>
public string[] AcceptTypes
{
get { return request.AcceptTypes; }
}
private Dictionary<string, object> items;
/// <summary>Attach any data to this request that all filters and services can access.</summary>
///
/// <value>The items.</value>
public Dictionary<string, object> Items
{
get { return items ?? (items = new Dictionary<string, object>()); }
}
private string responseContentType;
/// <summary>The expected Response ContentType for this request.</summary>
///
/// <value>The type of the response content.</value>
public string ResponseContentType
{
get { return responseContentType ?? (responseContentType = this.GetResponseContentType()); }
set { this.responseContentType = value; }
}
private string pathInfo;
/// <summary>Gets information describing the path.</summary>
///
/// <value>Information describing the path.</value>
public string PathInfo
{
get
{
if (this.pathInfo == null)
{
var mode = EndpointHost.Config.NServiceKitHandlerFactoryPath;
var pos = request.RawUrl.IndexOf("?");
if (pos != -1)
{
var path = request.RawUrl.Substring(0, pos);
this.pathInfo = HttpRequestExtensions.GetPathInfo(
path,
mode,
mode ?? "");
}
else
{
this.pathInfo = request.RawUrl;
}
this.pathInfo = this.pathInfo.UrlDecode();
this.pathInfo = NormalizePathInfo(pathInfo, mode);
}
return this.pathInfo;
}
}
private Dictionary<string, Cookie> cookies;
/// <summary>Gets the cookies.</summary>
///
/// <value>The cookies.</value>
public IDictionary<string, Cookie> Cookies
{
get
{
if (cookies == null)
{
cookies = new Dictionary<string, Cookie>();
for (var i = 0; i < this.request.Cookies.Count; i++)
{
var httpCookie = this.request.Cookies[i];
cookies[httpCookie.Name] = httpCookie;
}
}
return cookies;
}
}
/// <summary>Gets the user agent.</summary>
///
/// <value>The user agent.</value>
public string UserAgent
{
get { return request.UserAgent; }
}
/// <summary>Gets the headers.</summary>
///
/// <value>The headers.</value>
public NameValueCollection Headers
{
get { return request.Headers; }
}
private NameValueCollection queryString;
/// <summary>Gets the query string.</summary>
///
/// <value>The query string.</value>
public NameValueCollection QueryString
{
get { return queryString ?? (queryString = HttpUtility.ParseQueryString(request.Url.Query)); }
}
/// <summary>Gets information describing the form.</summary>
///
/// <value>Information describing the form.</value>
public NameValueCollection FormData
{
get { return this.Form; }
}
/// <summary>Gets a value indicating whether this object is local.</summary>
///
/// <value>true if this object is local, false if not.</value>
public bool IsLocal
{
get { return request.IsLocal; }
}
private string httpMethod;
/// <summary>Gets the HTTP method.</summary>
///
/// <value>The HTTP method.</value>
public string HttpMethod
{
get
{
return httpMethod
?? (httpMethod = Param(HttpHeaders.XHttpMethodOverride)
?? request.HttpMethod);
}
}
/// <summary>Parameters.</summary>
///
/// <param name="name">The name.</param>
///
/// <returns>A string.</returns>
public string Param(string name)
{
return Headers[name]
?? QueryString[name]
?? FormData[name];
}
/// <summary>The request ContentType.</summary>
///
/// <value>The type of the content.</value>
public string ContentType
{
get { return request.ContentType; }
}
/// <summary>Gets the content encoding.</summary>
///
/// <value>The content encoding.</value>
public Encoding ContentEncoding
{
get { return request.ContentEncoding; }
}
/// <summary>The value of the Referrer, null if not available.</summary>
///
/// <value>The URL referrer.</value>
public Uri UrlReferrer
{
get { return request.UrlReferrer; }
}
/// <summary>Gets an encoding.</summary>
///
/// <param name="contentTypeHeader">The content type header.</param>
///
/// <returns>The encoding.</returns>
public static Encoding GetEncoding(string contentTypeHeader)
{
var param = GetParameter(contentTypeHeader, "charset=");
if (param == null) return null;
try
{
return Encoding.GetEncoding(param);
}
catch (ArgumentException)
{
return null;
}
}
/// <summary>Buffer the Request InputStream so it can be re-read.</summary>
///
/// <value>true if use buffered stream, false if not.</value>
public bool UseBufferedStream
{
get { return bufferedStream != null; }
set
{
bufferedStream = value
? bufferedStream ?? new MemoryStream(request.InputStream.ReadFully())
: null;
}
}
private MemoryStream bufferedStream;
/// <summary>Gets the input stream.</summary>
///
/// <value>The input stream.</value>
public Stream InputStream
{
get { return bufferedStream ?? request.InputStream; }
}
/// <summary>Gets the length of the content.</summary>
///
/// <value>The length of the content.</value>
public long ContentLength
{
get { return request.ContentLength64; }
}
/// <summary>Gets the full pathname of the application file.</summary>
///
/// <value>The full pathname of the application file.</value>
public string ApplicationFilePath
{
get { return physicalFilePath; }
}
private IFile[] _files;
/// <summary>Access to the multi-part/formdata files posted on this request.</summary>
///
/// <value>The files.</value>
public IFile[] Files
{
get
{
if (_files == null)
{
if (files == null)
return _files = new IFile[0];
_files = new IFile[files.Count];
for (var i = 0; i < files.Count; i++)
{
var reqFile = files[i];
_files[i] = new HttpFile
{
ContentType = reqFile.ContentType,
ContentLength = reqFile.ContentLength,
FileName = reqFile.FileName,
InputStream = reqFile.InputStream,
};
}
}
return _files;
}
}
static Stream GetSubStream(Stream stream)
{
if (stream is MemoryStream)
{
var other = (MemoryStream)stream;
try
{
return new MemoryStream(other.GetBuffer(), 0, (int)other.Length, false, true);
}
catch (UnauthorizedAccessException)
{
return new MemoryStream(other.ToArray(), 0, (int)other.Length, false, true);
}
}
return stream;
}
static void EndSubStream(Stream stream)
{
}
/// <summary>Gets handler path if any.</summary>
///
/// <param name="listenerUrl">URL of the listener.</param>
///
/// <returns>The handler path if any.</returns>
public static string GetHandlerPathIfAny(string listenerUrl)
{
if (listenerUrl == null) return null;
var pos = listenerUrl.IndexOf("://", StringComparison.InvariantCultureIgnoreCase);
if (pos == -1) return null;
var startHostUrl = listenerUrl.Substring(pos + "://".Length);
var endPos = startHostUrl.IndexOf('/');
if (endPos == -1) return null;
var endHostUrl = startHostUrl.Substring(endPos + 1);
return String.IsNullOrEmpty(endHostUrl) ? null : endHostUrl.TrimEnd('/');
}
/// <summary>Normalize path information.</summary>
///
/// <param name="pathInfo"> Information describing the path.</param>
/// <param name="handlerPath">Full pathname of the handler file.</param>
///
/// <returns>A string.</returns>
public static string NormalizePathInfo(string pathInfo, string handlerPath)
{
if (handlerPath != null && pathInfo.TrimStart('/').StartsWith(
handlerPath, StringComparison.InvariantCultureIgnoreCase))
{
return pathInfo.TrimStart('/').Substring(handlerPath.Length);
}
return pathInfo;
}
}
}
| |
// 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.DirectoryServices.DirectorySearcher.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.DirectoryServices
{
public partial class DirectorySearcher : System.ComponentModel.Component
{
#region Methods and constructors
public DirectorySearcher(DirectoryEntry searchRoot, string filter, string[] propertiesToLoad, SearchScope scope)
{
}
public DirectorySearcher()
{
}
public DirectorySearcher(DirectoryEntry searchRoot, string filter, string[] propertiesToLoad)
{
}
public DirectorySearcher(string filter)
{
}
public DirectorySearcher(DirectoryEntry searchRoot)
{
}
public DirectorySearcher(DirectoryEntry searchRoot, string filter)
{
}
public DirectorySearcher(string filter, string[] propertiesToLoad, SearchScope scope)
{
}
public DirectorySearcher(string filter, string[] propertiesToLoad)
{
}
protected override void Dispose(bool disposing)
{
}
public SearchResultCollection FindAll()
{
Contract.Ensures(Contract.Result<SearchResultCollection>() != null);
return default(SearchResultCollection);
}
public SearchResult FindOne()
{
Contract.Ensures(Contract.Result<SearchResult>() != null);
return default(SearchResult);
}
#endregion
#region Properties and indexers
public bool Asynchronous
{
get
{
return default(bool);
}
set
{
}
}
public string AttributeScopeQuery
{
get
{
return default(string);
}
set
{
}
}
public bool CacheResults
{
get
{
return default(bool);
}
set
{
}
}
public TimeSpan ClientTimeout
{
get
{
return default(TimeSpan);
}
set
{
}
}
public DereferenceAlias DerefAlias
{
get
{
return default(DereferenceAlias);
}
set
{
}
}
public DirectorySynchronization DirectorySynchronization
{
get
{
return default(DirectorySynchronization);
}
set
{
}
}
public ExtendedDN ExtendedDN
{
get
{
return default(ExtendedDN);
}
set
{
}
}
public string Filter
{
get
{
return default(string);
}
set
{
}
}
public int PageSize
{
get
{
return default(int);
}
set
{
}
}
public System.Collections.Specialized.StringCollection PropertiesToLoad
{
get
{
return default(System.Collections.Specialized.StringCollection);
}
}
public bool PropertyNamesOnly
{
get
{
return default(bool);
}
set
{
}
}
public ReferralChasingOption ReferralChasing
{
get
{
return default(ReferralChasingOption);
}
set
{
}
}
public DirectoryEntry SearchRoot
{
get
{
return default(DirectoryEntry);
}
set
{
}
}
public SearchScope SearchScope
{
get
{
return default(SearchScope);
}
set
{
}
}
public SecurityMasks SecurityMasks
{
get
{
return default(SecurityMasks);
}
set
{
}
}
public TimeSpan ServerPageTimeLimit
{
get
{
return default(TimeSpan);
}
set
{
}
}
public TimeSpan ServerTimeLimit
{
get
{
return default(TimeSpan);
}
set
{
}
}
public int SizeLimit
{
get
{
return default(int);
}
set
{
}
}
public SortOption Sort
{
get
{
return default(SortOption);
}
set
{
}
}
public bool Tombstone
{
get
{
return default(bool);
}
set
{
}
}
public DirectoryVirtualListView VirtualListView
{
get
{
return default(DirectoryVirtualListView);
}
set
{
}
}
#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.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata.Ecma335;
namespace System.Reflection.Metadata
{
/// <summary>
/// Represents generic type parameters of a method or type.
/// </summary>
public struct GenericParameterHandleCollection : IReadOnlyList<GenericParameterHandle>
{
private readonly int _firstRowId;
private readonly ushort _count;
internal GenericParameterHandleCollection(int firstRowId, ushort count)
{
_firstRowId = firstRowId;
_count = count;
}
public int Count
{
get
{
return _count;
}
}
public GenericParameterHandle this[int index]
{
get
{
if (index < 0 || index >= _count)
{
Throw.IndexOutOfRange();
}
return GenericParameterHandle.FromRowId(_firstRowId + index);
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_firstRowId, _firstRowId + _count - 1);
}
IEnumerator<GenericParameterHandle> IEnumerable<GenericParameterHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<GenericParameterHandle>, IEnumerator
{
private readonly int _lastRowId; // inclusive
// first parameter rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int firstRowId, int lastRowId)
{
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public GenericParameterHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
return GenericParameterHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents constraints of a generic type parameter.
/// </summary>
public struct GenericParameterConstraintHandleCollection : IReadOnlyList<GenericParameterConstraintHandle>
{
private readonly int _firstRowId;
private readonly ushort _count;
internal GenericParameterConstraintHandleCollection(int firstRowId, ushort count)
{
_firstRowId = firstRowId;
_count = count;
}
public int Count
{
get
{
return _count;
}
}
public GenericParameterConstraintHandle this[int index]
{
get
{
if (index < 0 || index >= _count)
{
Throw.IndexOutOfRange();
}
return GenericParameterConstraintHandle.FromRowId(_firstRowId + index);
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_firstRowId, _firstRowId + _count - 1);
}
IEnumerator<GenericParameterConstraintHandle> IEnumerable<GenericParameterConstraintHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<GenericParameterConstraintHandle>, IEnumerator
{
private readonly int _lastRowId; // inclusive
// first parameter rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int firstRowId, int lastRowId)
{
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public GenericParameterConstraintHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
return GenericParameterConstraintHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct CustomAttributeHandleCollection : IReadOnlyCollection<CustomAttributeHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal CustomAttributeHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = reader.CustomAttributeTable.NumberOfRows;
}
internal CustomAttributeHandleCollection(MetadataReader reader, EntityHandle handle)
{
Debug.Assert(reader != null);
_reader = reader;
reader.CustomAttributeTable.GetAttributeRange(handle, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<CustomAttributeHandle> IEnumerable<CustomAttributeHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<CustomAttributeHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first custom attribute rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public CustomAttributeHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
if (_reader.CustomAttributeTable.PtrTable != null)
{
return GetCurrentCustomAttributeIndirect();
}
else
{
return CustomAttributeHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
private CustomAttributeHandle GetCurrentCustomAttributeIndirect()
{
return CustomAttributeHandle.FromRowId(
_reader.CustomAttributeTable.PtrTable[(_currentRowId & (int)TokenTypeIds.RIDMask) - 1]);
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct DeclarativeSecurityAttributeHandleCollection : IReadOnlyCollection<DeclarativeSecurityAttributeHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal DeclarativeSecurityAttributeHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = reader.DeclSecurityTable.NumberOfRows;
}
internal DeclarativeSecurityAttributeHandleCollection(MetadataReader reader, EntityHandle handle)
{
Debug.Assert(reader != null);
Debug.Assert(!handle.IsNil);
_reader = reader;
reader.DeclSecurityTable.GetAttributeRange(handle, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<DeclarativeSecurityAttributeHandle> IEnumerable<DeclarativeSecurityAttributeHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<DeclarativeSecurityAttributeHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first custom attribute rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public DeclarativeSecurityAttributeHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
return DeclarativeSecurityAttributeHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct MethodDefinitionHandleCollection : IReadOnlyCollection<MethodDefinitionHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal MethodDefinitionHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = reader.MethodDefTable.NumberOfRows;
}
internal MethodDefinitionHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType)
{
Debug.Assert(reader != null);
Debug.Assert(!containingType.IsNil);
_reader = reader;
reader.GetMethodRange(containingType, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<MethodDefinitionHandle> IEnumerable<MethodDefinitionHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<MethodDefinitionHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first method rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public MethodDefinitionHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
if (_reader.UseMethodPtrTable)
{
return GetCurrentMethodIndirect();
}
else
{
return MethodDefinitionHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
private MethodDefinitionHandle GetCurrentMethodIndirect()
{
return _reader.MethodPtrTable.GetMethodFor(_currentRowId & (int)TokenTypeIds.RIDMask);
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct FieldDefinitionHandleCollection : IReadOnlyCollection<FieldDefinitionHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal FieldDefinitionHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = reader.FieldTable.NumberOfRows;
}
internal FieldDefinitionHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType)
{
Debug.Assert(reader != null);
Debug.Assert(!containingType.IsNil);
_reader = reader;
reader.GetFieldRange(containingType, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<FieldDefinitionHandle> IEnumerable<FieldDefinitionHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<FieldDefinitionHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first field rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public FieldDefinitionHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
if (_reader.UseFieldPtrTable)
{
return GetCurrentFieldIndirect();
}
else
{
return FieldDefinitionHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
private FieldDefinitionHandle GetCurrentFieldIndirect()
{
return _reader.FieldPtrTable.GetFieldFor(_currentRowId & (int)TokenTypeIds.RIDMask);
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct PropertyDefinitionHandleCollection : IReadOnlyCollection<PropertyDefinitionHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal PropertyDefinitionHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = reader.PropertyTable.NumberOfRows;
}
internal PropertyDefinitionHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType)
{
Debug.Assert(reader != null);
Debug.Assert(!containingType.IsNil);
_reader = reader;
reader.GetPropertyRange(containingType, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<PropertyDefinitionHandle> IEnumerable<PropertyDefinitionHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<PropertyDefinitionHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first Property rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public PropertyDefinitionHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
if (_reader.UsePropertyPtrTable)
{
return GetCurrentPropertyIndirect();
}
else
{
return PropertyDefinitionHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
private PropertyDefinitionHandle GetCurrentPropertyIndirect()
{
return _reader.PropertyPtrTable.GetPropertyFor(_currentRowId & (int)TokenTypeIds.RIDMask);
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct EventDefinitionHandleCollection : IReadOnlyCollection<EventDefinitionHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal EventDefinitionHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = reader.EventTable.NumberOfRows;
}
internal EventDefinitionHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType)
{
Debug.Assert(reader != null);
Debug.Assert(!containingType.IsNil);
_reader = reader;
reader.GetEventRange(containingType, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<EventDefinitionHandle> IEnumerable<EventDefinitionHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<EventDefinitionHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId;
// first rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public EventDefinitionHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
if (_reader.UseEventPtrTable)
{
return GetCurrentEventIndirect();
}
else
{
return EventDefinitionHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
private EventDefinitionHandle GetCurrentEventIndirect()
{
return _reader.EventPtrTable.GetEventFor(_currentRowId & (int)TokenTypeIds.RIDMask);
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct MethodImplementationHandleCollection : IReadOnlyCollection<MethodImplementationHandle>
{
private readonly int _firstRowId;
private readonly int _lastRowId;
internal MethodImplementationHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType)
{
Debug.Assert(reader != null);
if (containingType.IsNil)
{
_firstRowId = 1;
_lastRowId = reader.MethodImplTable.NumberOfRows;
}
else
{
reader.MethodImplTable.GetMethodImplRange(containingType, out _firstRowId, out _lastRowId);
}
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_firstRowId, _lastRowId);
}
IEnumerator<MethodImplementationHandle> IEnumerable<MethodImplementationHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<MethodImplementationHandle>, IEnumerator
{
private readonly int _lastRowId; // inclusive
// first impl rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int firstRowId, int lastRowId)
{
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public MethodImplementationHandle Current
{
get
{
return MethodImplementationHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Collection of parameters of a specified method.
/// </summary>
public struct ParameterHandleCollection : IReadOnlyCollection<ParameterHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal ParameterHandleCollection(MetadataReader reader, MethodDefinitionHandle containingMethod)
{
Debug.Assert(reader != null);
Debug.Assert(!containingMethod.IsNil);
_reader = reader;
reader.GetParameterRange(containingMethod, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<ParameterHandle> IEnumerable<ParameterHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<ParameterHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first Parameter rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_lastRowId = lastRowId;
_currentRowId = firstRowId - 1;
}
public ParameterHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
if (_reader.UseParamPtrTable)
{
return GetCurrentParameterIndirect();
}
else
{
return ParameterHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
private ParameterHandle GetCurrentParameterIndirect()
{
return _reader.ParamPtrTable.GetParamFor(_currentRowId & (int)TokenTypeIds.RIDMask);
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct InterfaceImplementationHandleCollection : IReadOnlyCollection<InterfaceImplementationHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal InterfaceImplementationHandleCollection(MetadataReader reader, TypeDefinitionHandle implementingType)
{
Debug.Assert(reader != null);
Debug.Assert(!implementingType.IsNil);
_reader = reader;
reader.InterfaceImplTable.GetInterfaceImplRange(implementingType, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<InterfaceImplementationHandle> IEnumerable<InterfaceImplementationHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<InterfaceImplementationHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public InterfaceImplementationHandle Current
{
get
{
return InterfaceImplementationHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents a collection of <see cref="TypeDefinitionHandle"/>.
/// </summary>
public struct TypeDefinitionHandleCollection : IReadOnlyCollection<TypeDefinitionHandle>
{
private readonly int _lastRowId;
// Creates collection that represents the entire TypeDef table.
internal TypeDefinitionHandleCollection(int lastRowId)
{
_lastRowId = lastRowId;
}
public int Count
{
get { return _lastRowId; }
}
public Enumerator GetEnumerator()
{
return new Enumerator(_lastRowId);
}
IEnumerator<TypeDefinitionHandle> IEnumerable<TypeDefinitionHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<TypeDefinitionHandle>, IEnumerator
{
private readonly int _lastRowId;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int lastRowId)
{
_lastRowId = lastRowId;
_currentRowId = 0;
}
public TypeDefinitionHandle Current
{
get
{
return TypeDefinitionHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this method small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents a collection of <see cref="TypeReferenceHandle"/>.
/// </summary>
public struct TypeReferenceHandleCollection : IReadOnlyCollection<TypeReferenceHandle>
{
private readonly int _lastRowId;
// Creates collection that represents the entire TypeRef table.
internal TypeReferenceHandleCollection(int lastRowId)
{
_lastRowId = lastRowId;
}
public int Count
{
get { return _lastRowId; }
}
public Enumerator GetEnumerator()
{
return new Enumerator(_lastRowId);
}
IEnumerator<TypeReferenceHandle> IEnumerable<TypeReferenceHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<TypeReferenceHandle>, IEnumerator
{
private readonly int _lastRowId;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int lastRowId)
{
_lastRowId = lastRowId;
_currentRowId = 0;
}
public TypeReferenceHandle Current
{
get
{
return TypeReferenceHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this method small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents a collection of <see cref="TypeReferenceHandle"/>.
/// </summary>
public struct ExportedTypeHandleCollection : IReadOnlyCollection<ExportedTypeHandle>
{
private readonly int _lastRowId;
// Creates collection that represents the entire TypeRef table.
internal ExportedTypeHandleCollection(int lastRowId)
{
_lastRowId = lastRowId;
}
public int Count
{
get { return _lastRowId; }
}
public Enumerator GetEnumerator()
{
return new Enumerator(_lastRowId);
}
IEnumerator<ExportedTypeHandle> IEnumerable<ExportedTypeHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<ExportedTypeHandle>, IEnumerator
{
private readonly int _lastRowId;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int lastRowId)
{
_lastRowId = lastRowId;
_currentRowId = 0;
}
public ExportedTypeHandle Current
{
get
{
return ExportedTypeHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this method small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents a collection of <see cref="MemberReferenceHandle"/>.
/// </summary>
public struct MemberReferenceHandleCollection : IReadOnlyCollection<MemberReferenceHandle>
{
private readonly int _lastRowId;
// Creates collection that represents the entire TypeRef table.
internal MemberReferenceHandleCollection(int lastRowId)
{
_lastRowId = lastRowId;
}
public int Count
{
get { return _lastRowId; }
}
public Enumerator GetEnumerator()
{
return new Enumerator(_lastRowId);
}
IEnumerator<MemberReferenceHandle> IEnumerable<MemberReferenceHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<MemberReferenceHandle>, IEnumerator
{
private readonly int _lastRowId;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int lastRowId)
{
_lastRowId = lastRowId;
_currentRowId = 0;
}
public MemberReferenceHandle Current
{
get
{
return MemberReferenceHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this method small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct PropertyAccessors
{
// Workaround: JIT doesn't generate good code for nested structures, so use uints.
private readonly int _getterRowId;
private readonly int _setterRowId;
private readonly ImmutableArray<MethodDefinitionHandle> _others;
public MethodDefinitionHandle Getter { get { return MethodDefinitionHandle.FromRowId(_getterRowId); } }
public MethodDefinitionHandle Setter { get { return MethodDefinitionHandle.FromRowId(_setterRowId); } }
public ImmutableArray<MethodDefinitionHandle> Others { get { return _others; } }
internal PropertyAccessors(int getterRowId, int setterRowId, ImmutableArray<MethodDefinitionHandle> others)
{
_getterRowId = getterRowId;
_setterRowId = setterRowId;
_others = others;
}
}
public struct EventAccessors
{
// Workaround: JIT doesn't generate good code for nested structures, so use uints.
private readonly int _adderRowId;
private readonly int _removerRowId;
private readonly int _raiserRowId;
private readonly ImmutableArray<MethodDefinitionHandle> _others;
public MethodDefinitionHandle Adder { get { return MethodDefinitionHandle.FromRowId(_adderRowId); } }
public MethodDefinitionHandle Remover { get { return MethodDefinitionHandle.FromRowId(_removerRowId); } }
public MethodDefinitionHandle Raiser { get { return MethodDefinitionHandle.FromRowId(_raiserRowId); } }
public ImmutableArray<MethodDefinitionHandle> Others { get { return _others; } }
internal EventAccessors(int adderRowId, int removerRowId, int raiserRowId, ImmutableArray<MethodDefinitionHandle> others)
{
_adderRowId = adderRowId;
_removerRowId = removerRowId;
_raiserRowId = raiserRowId;
_others = others;
}
}
/// <summary>
/// Collection of assembly references.
/// </summary>
public struct AssemblyReferenceHandleCollection : IReadOnlyCollection<AssemblyReferenceHandle>
{
private readonly MetadataReader _reader;
internal AssemblyReferenceHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
}
public int Count
{
get
{
return _reader.AssemblyRefTable.NumberOfNonVirtualRows + _reader.AssemblyRefTable.NumberOfVirtualRows;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader);
}
IEnumerator<AssemblyReferenceHandle> IEnumerable<AssemblyReferenceHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<AssemblyReferenceHandle>, IEnumerator
{
private readonly MetadataReader _reader;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
private int _virtualRowId;
internal Enumerator(MetadataReader reader)
{
_reader = reader;
_currentRowId = 0;
_virtualRowId = -1;
}
public AssemblyReferenceHandle Current
{
get
{
if (_virtualRowId >= 0)
{
if (_virtualRowId == EnumEnded)
{
return default(AssemblyReferenceHandle);
}
return AssemblyReferenceHandle.FromVirtualIndex((AssemblyReferenceHandle.VirtualIndex)((uint)_virtualRowId));
}
else
{
return AssemblyReferenceHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
public bool MoveNext()
{
if (_currentRowId < _reader.AssemblyRefTable.NumberOfNonVirtualRows)
{
_currentRowId++;
return true;
}
if (_virtualRowId < _reader.AssemblyRefTable.NumberOfVirtualRows - 1)
{
_virtualRowId++;
return true;
}
_currentRowId = EnumEnded;
_virtualRowId = EnumEnded;
return false;
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents a collection of <see cref="ManifestResourceHandle"/>.
/// </summary>
public struct ManifestResourceHandleCollection : IReadOnlyCollection<ManifestResourceHandle>
{
private readonly int _lastRowId;
// Creates collection that represents the entire ManifestResource table.
internal ManifestResourceHandleCollection(int lastRowId)
{
_lastRowId = lastRowId;
}
public int Count
{
get { return _lastRowId; }
}
public Enumerator GetEnumerator()
{
return new Enumerator(_lastRowId);
}
IEnumerator<ManifestResourceHandle> IEnumerable<ManifestResourceHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<ManifestResourceHandle>, IEnumerator
{
private readonly int _lastRowId;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int lastRowId)
{
_lastRowId = lastRowId;
_currentRowId = 0;
}
public ManifestResourceHandle Current
{
get
{
return ManifestResourceHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this method small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents a collection of <see cref="AssemblyFileHandle"/>.
/// </summary>
public struct AssemblyFileHandleCollection : IReadOnlyCollection<AssemblyFileHandle>
{
private readonly int _lastRowId;
// Creates collection that represents the entire AssemblyFile table.
internal AssemblyFileHandleCollection(int lastRowId)
{
_lastRowId = lastRowId;
}
public int Count
{
get { return _lastRowId; }
}
public Enumerator GetEnumerator()
{
return new Enumerator(_lastRowId);
}
IEnumerator<AssemblyFileHandle> IEnumerable<AssemblyFileHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<AssemblyFileHandle>, IEnumerator
{
private readonly int _lastRowId;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int lastRowId)
{
_lastRowId = lastRowId;
_currentRowId = 0;
}
public AssemblyFileHandle Current
{
get
{
return AssemblyFileHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this method small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility001.accessibility001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility001.accessibility001;
public class Test
{
public void Method()
{
}
protected void Method(int x, object o)
{
s_status = 1;
}
internal protected void Method(long x, object o)
{
s_status = 2;
}
internal void Method(short x, object o)
{
s_status = 3;
}
private static int s_status = -1;
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Test b = new Test();
dynamic x = 1;
dynamic y = null;
b.Method(x, y);
return s_status == 1 ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility002.accessibility002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility002.accessibility002;
public class Test
{
public void Method()
{
}
protected void Method(int x, object o)
{
s_status = 1;
}
internal protected void Method(long x, object o)
{
s_status = 2;
}
internal void Method(short x, object o)
{
s_status = 3;
}
private static int s_status = -1;
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
var b = new Test();
b.Method();
dynamic x = short.MinValue;
dynamic y = null;
b.Method(x, y);
return s_status == 3 ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.errorverifier.errorverifier
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.errorverifier.errorverifier;
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility003.accessibility003;
using System;
using System.Collections;
using System.IO;
using System.Globalization;
using System.Reflection;
using System.Resources;
using Microsoft.CSharp.RuntimeBinder;
public enum ErrorElementId
{
None,
SK_METHOD, // method
SK_CLASS, // type
SK_NAMESPACE, // namespace
SK_FIELD, // field
SK_PROPERTY, // property
SK_UNKNOWN, // element
SK_VARIABLE, // variable
SK_EVENT, // event
SK_TYVAR, // type parameter
SK_ALIAS, // using alias
ERRORSYM, // <error>
NULL, // <null>
GlobalNamespace, // <global namespace>
MethodGroup, // method group
AnonMethod, // anonymous method
Lambda, // lambda expression
AnonymousType, // anonymous type
}
public enum ErrorMessageId
{
None,
BadBinaryOps, // Operator '{0}' cannot be applied to operands of type '{1}' and '{2}'
IntDivByZero, // Division by constant zero
BadIndexLHS, // Cannot apply indexing with [] to an expression of type '{0}'
BadIndexCount, // Wrong number of indices inside []; expected '{0}'
BadUnaryOp, // Operator '{0}' cannot be applied to operand of type '{1}'
NoImplicitConv, // Cannot implicitly convert type '{0}' to '{1}'
NoExplicitConv, // Cannot convert type '{0}' to '{1}'
ConstOutOfRange, // Constant value '{0}' cannot be converted to a '{1}'
AmbigBinaryOps, // Operator '{0}' is ambiguous on operands of type '{1}' and '{2}'
AmbigUnaryOp, // Operator '{0}' is ambiguous on an operand of type '{1}'
ValueCantBeNull, // Cannot convert null to '{0}' because it is a non-nullable value type
WrongNestedThis, // Cannot access a non-static member of outer type '{0}' via nested type '{1}'
NoSuchMember, // '{0}' does not contain a definition for '{1}'
ObjectRequired, // An object reference is required for the non-static field, method, or property '{0}'
AmbigCall, // The call is ambiguous between the following methods or properties: '{0}' and '{1}'
BadAccess, // '{0}' is inaccessible due to its protection level
MethDelegateMismatch, // No overload for '{0}' matches delegate '{1}'
AssgLvalueExpected, // The left-hand side of an assignment must be a variable, property or indexer
NoConstructors, // The type '{0}' has no constructors defined
BadDelegateConstructor, // The delegate '{0}' does not have a valid constructor
PropertyLacksGet, // The property or indexer '{0}' cannot be used in this context because it lacks the get accessor
ObjectProhibited, // Member '{0}' cannot be accessed with an instance reference; qualify it with a type name instead
AssgReadonly, // A readonly field cannot be assigned to (except in a constructor or a variable initializer)
RefReadonly, // A readonly field cannot be passed ref or out (except in a constructor)
AssgReadonlyStatic, // A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)
RefReadonlyStatic, // A static readonly field cannot be passed ref or out (except in a static constructor)
AssgReadonlyProp, // Property or indexer '{0}' cannot be assigned to -- it is read only
AbstractBaseCall, // Cannot call an abstract base member: '{0}'
RefProperty, // A property or indexer may not be passed as an out or ref parameter
ManagedAddr, // Cannot take the address of, get the size of, or declare a pointer to a managed type ('{0}')
FixedNotNeeded, // You cannot use the fixed statement to take the address of an already fixed expression
UnsafeNeeded, // Dynamic calls cannot be used in conjunction with pointers
BadBoolOp, // In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') must have the same return type as the type of its 2 parameters
MustHaveOpTF, // The type ('{0}') must contain declarations of operator true and operator false
CheckedOverflow, // The operation overflows at compile time in checked mode
ConstOutOfRangeChecked, // Constant value '{0}' cannot be converted to a '{1}' (use 'unchecked' syntax to override)
AmbigMember, // Ambiguity between '{0}' and '{1}'
SizeofUnsafe, // '{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
FieldInitRefNonstatic, // A field initializer cannot reference the non-static field, method, or property '{0}'
CallingFinalizeDepracated, // Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available.
CallingBaseFinalizeDeprecated, // Do not directly call your base class Finalize method. It is called automatically from your destructor.
BadCastInFixed, // The right hand side of a fixed statement assignment may not be a cast expression
NoImplicitConvCast, // Cannot implicitly convert type '{0}' to '{1}'. An explicit conversion exists (are you missing a cast?)
InaccessibleGetter, // The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible
InaccessibleSetter, // The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible
BadArity, // Using the generic {1} '{0}' requires '{2}' type arguments
BadTypeArgument, // The type '{0}' may not be used as a type argument
TypeArgsNotAllowed, // The {1} '{0}' cannot be used with type arguments
HasNoTypeVars, // The non-generic {1} '{0}' cannot be used with type arguments
NewConstraintNotSatisfied, // '{2}' must be a non-abstract type with a public parameterless constructor in order to use it as parameter '{1}' in the generic type or method '{0}'
GenericConstraintNotSatisfiedRefType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no implicit reference conversion from '{3}' to '{1}'.
GenericConstraintNotSatisfiedNullableEnum, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'.
GenericConstraintNotSatisfiedNullableInterface, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. Nullable types can not satisfy any interface constraints.
GenericConstraintNotSatisfiedTyVar, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion or type parameter conversion from '{3}' to '{1}'.
GenericConstraintNotSatisfiedValType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion from '{3}' to '{1}'.
TypeVarCantBeNull, // Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.
BadRetType, // '{1} {0}' has the wrong return type
CantInferMethTypeArgs, // The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.
MethGrpToNonDel, // Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?
RefConstraintNotSatisfied, // The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'
ValConstraintNotSatisfied, // The type '{2}' must be a non-nullable value type in order to use it as parameter '{1}' in the generic type or method '{0}'
CircularConstraint, // Circular constraint dependency involving '{0}' and '{1}'
BaseConstraintConflict, // Type parameter '{0}' inherits conflicting constraints '{1}' and '{2}'
ConWithValCon, // Type parameter '{1}' has the 'struct' constraint so '{1}' cannot be used as a constraint for '{0}'
AmbigUDConv, // Ambiguous user defined conversions '{0}' and '{1}' when converting from '{2}' to '{3}'
PredefinedTypeNotFound, // Predefined type '{0}' is not defined or imported
PredefinedTypeBadType, // Predefined type '{0}' is declared incorrectly
BindToBogus, // '{0}' is not supported by the language
CantCallSpecialMethod, // '{0}': cannot explicitly call operator or accessor
BogusType, // '{0}' is a type not supported by the language
MissingPredefinedMember, // Missing compiler required member '{0}.{1}'
LiteralDoubleCast, // Literal of type double cannot be implicitly converted to type '{1}'; use an '{0}' suffix to create a literal of this type
UnifyingInterfaceInstantiations, // '{0}' cannot implement both '{1}' and '{2}' because they may unify for some type parameter substitutions
ConvertToStaticClass, // Cannot convert to static type '{0}'
GenericArgIsStaticClass, // '{0}': static types cannot be used as type arguments
PartialMethodToDelegate, // Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration
IncrementLvalueExpected, // The operand of an increment or decrement operator must be a variable, property or indexer
NoSuchMemberOrExtension, // '{0}' does not contain a definition for '{1}' and no extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?)
ValueTypeExtDelegate, // Extension methods '{0}' defined on value type '{1}' cannot be used to create delegates
BadArgCount, // No overload for method '{0}' takes '{1}' arguments
BadArgTypes, // The best overloaded method match for '{0}' has some invalid arguments
BadArgType, // Argument '{0}': cannot convert from '{1}' to '{2}'
RefLvalueExpected, // A ref or out argument must be an assignable variable
BadProtectedAccess, // Cannot access protected member '{0}' via a qualifier of type '{1}'; the qualifier must be of type '{2}' (or derived from it)
BindToBogusProp2, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor methods '{1}' or '{2}'
BindToBogusProp1, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor method '{1}'
BadDelArgCount, // Delegate '{0}' does not take '{1}' arguments
BadDelArgTypes, // Delegate '{0}' has some invalid arguments
AssgReadonlyLocal, // Cannot assign to '{0}' because it is read-only
RefReadonlyLocal, // Cannot pass '{0}' as a ref or out argument because it is read-only
ReturnNotLValue, // Cannot modify the return value of '{0}' because it is not a variable
BadArgExtraRef, // Argument '{0}' should not be passed with the '{1}' keyword
// DelegateOnConditional, // Cannot create delegate with '{0}' because it has a Conditional attribute (REMOVED)
BadArgRef, // Argument '{0}' must be passed with the '{1}' keyword
AssgReadonly2, // Members of readonly field '{0}' cannot be modified (except in a constructor or a variable initializer)
RefReadonly2, // Members of readonly field '{0}' cannot be passed ref or out (except in a constructor)
AssgReadonlyStatic2, // Fields of static readonly field '{0}' cannot be assigned to (except in a static constructor or a variable initializer)
RefReadonlyStatic2, // Fields of static readonly field '{0}' cannot be passed ref or out (except in a static constructor)
AssgReadonlyLocalCause, // Cannot assign to '{0}' because it is a '{1}'
RefReadonlyLocalCause, // Cannot pass '{0}' as a ref or out argument because it is a '{1}'
ThisStructNotInAnonMeth, // Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead.
DelegateOnNullable, // Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<T>'
BadCtorArgCount, // '{0}' does not contain a constructor that takes '{1}' arguments
BadExtensionArgTypes, // '{0}' does not contain a definition for '{1}' and the best extension method overload '{2}' has some invalid arguments
BadInstanceArgType, // Instance argument: cannot convert from '{0}' to '{1}'
BadArgTypesForCollectionAdd, // The best overloaded Add method '{0}' for the collection initializer has some invalid arguments
InitializerAddHasParamModifiers, // The best overloaded method match '{0}' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters.
NonInvocableMemberCalled, // Non-invocable member '{0}' cannot be used like a method.
NamedArgumentSpecificationBeforeFixedArgument, // Named argument specifications must appear after all fixed arguments have been specified
BadNamedArgument, // The best overload for '{0}' does not have a parameter named '{1}'
BadNamedArgumentForDelegateInvoke, // The delegate '{0}' does not have a parameter named '{1}'
DuplicateNamedArgument, // Named argument '{0}' cannot be specified multiple times
NamedArgumentUsedInPositional, // Named argument '{0}' specifies a parameter for which a positional argument has already been given
}
public enum RuntimeErrorId
{
None,
// RuntimeBinderInternalCompilerException
InternalCompilerError, // An unexpected exception occurred while binding a dynamic operation
// ArgumentException
BindRequireArguments, // Cannot bind call with no calling object
// RuntimeBinderException
BindCallFailedOverloadResolution, // Overload resolution failed
// ArgumentException
BindBinaryOperatorRequireTwoArguments, // Binary operators must be invoked with two arguments
// ArgumentException
BindUnaryOperatorRequireOneArgument, // Unary operators must be invoked with one argument
// RuntimeBinderException
BindPropertyFailedMethodGroup, // The name '{0}' is bound to a method and cannot be used like a property
// RuntimeBinderException
BindPropertyFailedEvent, // The event '{0}' can only appear on the left hand side of += or -=
// RuntimeBinderException
BindInvokeFailedNonDelegate, // Cannot invoke a non-delegate type
// ArgumentException
BindImplicitConversionRequireOneArgument, // Implicit conversion takes exactly one argument
// ArgumentException
BindExplicitConversionRequireOneArgument, // Explicit conversion takes exactly one argument
// ArgumentException
BindBinaryAssignmentRequireTwoArguments, // Binary operators cannot be invoked with one argument
// RuntimeBinderException
BindBinaryAssignmentFailedNullReference, // Cannot perform member assignment on a null reference
// RuntimeBinderException
NullReferenceOnMemberException, // Cannot perform runtime binding on a null reference
// RuntimeBinderException
BindCallToConditionalMethod, // Cannot dynamically invoke method '{0}' because it has a Conditional attribute
// RuntimeBinderException
BindToVoidMethodButExpectResult, // Cannot implicitly convert type 'void' to 'object'
// EE?
EmptyDynamicView, // No further information on this object could be discovered
// MissingMemberException
GetValueonWriteOnlyProperty, // Write Only properties are not supported
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility003.accessibility003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.errorverifier.errorverifier;
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility003.accessibility003;
public class Test
{
private delegate void Del(long x, int y);
public void Method(long x, int y)
{
}
private void Method(int x, int y)
{
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic b = new Test();
try
{
Del ddd = new Del(b.Method);
dynamic d1 = 1;
dynamic d2 = 2;
ddd(d1, d2);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
return 0;
}
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility004.accessibility004
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility004.accessibility004;
// <Title>Accessibility</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public struct Test
{
public void Method()
{
}
private void Method(int x, object o)
{
s_status = 1;
}
internal void Method(long x, object o)
{
s_status = 2;
}
internal void Method(short x, object o)
{
s_status = 3;
}
private static int s_status = -1;
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Test b = new Test();
dynamic x = -1;
dynamic y = null;
b.Method(x, y);
return s_status == 1 ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility005.accessibility005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility005.accessibility005;
public class Test
{
private class Base
{
public void Method(int x)
{
}
}
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Base b = new Base();
dynamic x = int.MaxValue;
b.Method(x);
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility006.accessibility006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility006.accessibility006;
public class Test
{
protected class Base
{
public void Method()
{
}
protected void Method(int x, object o)
{
}
internal protected void Method(long x, object o)
{
}
internal void Method(short x, object o)
{
}
public void Method(byte x, object o)
{
}
}
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Base b = new Base();
dynamic x = byte.MaxValue;
dynamic y = new object();
b.Method(x, y);
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility007.accessibility007
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility007.accessibility007;
public class Test
{
public void Method(int x, int y)
{
s_status = 1;
}
private void Method(long x, int y)
{
s_status = 2;
}
internal void Method1(short x, int y)
{
s_status = 3;
}
protected void Method1(long x, int y)
{
s_status = 4;
}
private static int s_status = -1;
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic b = new Test();
dynamic d1 = 1;
dynamic d2 = 2;
b.Method(d1, d2);
bool ret = s_status == 1;
b.Method1(d1, d2);
ret &= (s_status == 4);
return ret ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility011.accessibility011
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility011.accessibility011;
public class Test
{
public class Higher
{
private class Base
{
public void Method(int x)
{
}
}
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Base b = new Base();
dynamic x = int.MaxValue;
b.Method(x);
return 0;
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility012.accessibility012
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility012.accessibility012;
public class Test
{
internal class Base
{
public void Method(int x)
{
Test.Status = 1;
}
}
public static int Status;
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Base b = new Base();
dynamic x = int.MaxValue;
b.Method(x);
if (Test.Status == 1)
return 0;
return 1;
}
}
// </Code>
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using CpsDbHelper.Extensions;
namespace CpsDbHelper
{
public class DataReaderHelper : DbHelper<DataReaderHelper>
{
private const string DefaultKey = "__default";
private readonly IDictionary<string, object> _results = new Dictionary<string, object>();
private readonly IDictionary<string, Func<IDataReader, DataReaderHelper, object>> _processDelegates = new Dictionary<string, Func<IDataReader, DataReaderHelper, object>>();
private readonly IDictionary<string, Action<IDataReader>> _preActions = new Dictionary<string, Action<IDataReader>>();
public DataReaderHelper(string text, string connectionString)
: base(text, connectionString)
{
}
public DataReaderHelper(string text, SqlConnection connection, SqlTransaction transaction)
: base(text, connection, transaction)
{
}
protected override void BeginExecute(SqlCommand cmd)
{
using (var reader = cmd.ExecuteReader())
{
ProcessReader(reader);
}
}
protected override async Task BeginExecuteAsync(SqlCommand cmd)
{
using (var reader = await cmd.ExecuteReaderAsync())
{
ProcessReader(reader);
}
}
/// <summary>
/// Define an action that executes right after the sqlCommand.execute() and before looping through the DataReader
/// </summary>
/// <param name="action">the action to apply to the DataReader</param>
/// <param name="resultKey">The result set key which matches the define/map result method. the action will be applied before the key specified result set</param>
/// <returns></returns>
public virtual DataReaderHelper PreProcessResult(Action<IDataReader> action, string resultKey = DefaultKey)
{
_preActions.Add(resultKey, action);
return this;
}
/// <summary>
/// Define a result, use the reader to process result and return it to helper, later use the result key to get the result
/// </summary>
/// <param name="fun">the function that applied to the DataReader to process the result. the return value is the final result</param>
/// <param name="resultKey">the identifier to find the reuslt later</param>
/// <returns></returns>
public DataReaderHelper DefineResult(Func<IDataReader, DataReaderHelper, object> fun, string resultKey = DefaultKey)
{
_processDelegates.Add(resultKey, fun);
return this;
}
/// <summary>
/// Define a result, use the reader to process result and return it to helper, later use the result key to get the result
/// </summary>
/// <param name="fun">the function that applied to the DataReader to process the result. the return value is the final result</param>
/// <param name="resultKey">the identifier to find the reuslt later</param>
/// <returns></returns>
public DataReaderHelper DefineResult(Func<IDataReader, object> fun, string resultKey = DefaultKey)
{
_processDelegates.Add(resultKey, (reader, helper) => fun(reader));
return this;
}
/// <summary>
/// Define a result, use the reader to process result and return it to helper, later use the result key to get the result
/// </summary>
/// <param name="fun">the function that applied to the DataReader to process the result. the return value is the item of a list, the final result is the list of the item</param>
/// <param name="resultKey">the identifier to find the reuslt later</param>
/// <returns></returns>
public DataReaderHelper DefineListResult<T>(Func<IDataReader, DataReaderHelper, T> fun, string resultKey = DefaultKey)
{
_processDelegates.Add(resultKey, (reader, helper) => ProcessListResult(reader, fun));
return this;
}
/// <summary>
/// Define a result, use the reader to process result and return it to helper, later use the result key to get the result
/// </summary>
/// <param name="fun">the function that applied to the DataReader to process the result. the return value is the item of a list, the final result is the list of the item</param>
/// <param name="resultKey">the identifier to find the reuslt later</param>
/// <returns></returns>
public DataReaderHelper DefineListResult<T>(Func<IDataReader, T> fun, string resultKey)
{
_processDelegates.Add(resultKey, (reader, helper) => ProcessListResult(reader, (rea, hel) => fun(rea)));
return this;
}
/// <summary>
/// Start mapping TValue with the result set, the row will be aligned with TValue in later operations
/// </summary>
/// <typeparam name="TValue">The type of the result which will be produced after proceesing this set of reader result</typeparam>
/// <param name="resultKey">the identifier to find the reuslt with helper.GetResult()</param>
/// <returns></returns>
public DataReaderMapper<TValue> BeginMapResult<TValue>(string resultKey = DefaultKey)
{
return new DataReaderMapper<TValue>(this, resultKey);
}
/// <summary>
/// Auto map property names with column names to TValue from the result set
/// </summary>
/// <typeparam name="TValue">The type of the result which will be produced after proceesing this set of reader result</typeparam>
/// <param name="resultKey">the identifier to find the reuslt with helper.GetResult()</param>
/// <returns></returns>
public DataReaderHelper AutoMapResult<TValue>(string resultKey = DefaultKey)
{
return new DataReaderMapper<TValue>(this, resultKey).AutoMap().FinishMap();
}
/// <summary>
/// Use this method to map the only one column from the reuslt set to a simple type
/// </summary>
/// <typeparam name="TValue">a C# simple type which the column's value will be converted to</typeparam>
/// <param name="columnName">the column name of the reuslt set</param>
/// <param name="resultKey">the identifier to find the reuslt with helper.GetResult()</param>
/// <returns></returns>
public DataReaderHelper DefineBasicTypeListResult<TValue>(string columnName, string resultKey = DefaultKey)
{
_processDelegates.Add(resultKey, (reader, helper) =>
{
var ordinal = reader.GetOrdinal(columnName);
var ret = new List<TValue>();
while (reader.Read())
{
ret.Add(reader.Get<TValue>(ordinal));
}
return ret;
});
return this;
}
/// <summary>
/// Get the result after Execute() is called.
/// previous DefineResult will return the return value of the function passed in
/// DefineListResult<TValue>/MapResult<TValue>/AutoMapResult<TValue> will need to use IList<TValue> to retrieve the result
/// </summary>
/// <typeparam name="T">the type of the result to cast to</typeparam>
/// <param name="key">The key used to define result</param>
/// <returns></returns>
public DataReaderHelper GetResult<T>(out T result, string key = DefaultKey)
{
result = (T)_results[key];
return this;
}
/// <summary>
/// Get the result after Execute() is called.
/// previous DefineResult will return the return value of the function passed in
/// DefineListResult<TValue>/MapResult<TValue>/AutoMapResult<TValue> will need to use IList<TValue> to retrieve the result
/// </summary>
/// <typeparam name="T">the type of the result to cast to</typeparam>
/// <param name="key">The key used to define result</param>
/// <returns></returns>
public T GetResult<T>(string key = DefaultKey)
{
return (T)_results[key];
}
/// <summary>
/// Get the result after Execute() is called.
/// returns List<T> previous defined by DefineListResult<T>/MapResult<T>/AutoMapResult<T>
/// </summary>
/// <typeparam name="T">the type of the result to cast to</typeparam>
/// <param name="key">The key used to define result</param>
/// <returns></returns>
public DataReaderHelper GetResultCollection<T>(out IList<T> result, string key = DefaultKey)
{
result = (IList<T>)_results[key];
return this;
}
/// <summary>
/// Get the result after Execute() is called.
/// </summary>
/// <typeparam name="T">the type of the result to cast to</typeparam>
/// <param name="key">The key used to define result</param>
/// <returns>List<T> previous defined by DefineListResult<T>/MapResult<T>/AutoMapResult<T></returns>
public IList<T> GetResultCollection<T>(string key = DefaultKey)
{
return (IList<T>)_results[key];
}
private object ProcessListResult<T>(IDataReader reader, Func<IDataReader, DataReaderHelper, T> fun)
{
var ret = new List<T>();
while (reader.Read())
{
ret.Add(fun(reader, this));
}
return ret;
}
private void ProcessReader(SqlDataReader reader)
{
var first = true;
foreach (var del in _processDelegates)
{
if (!first)
{
if (!reader.NextResult())
{
return;
}
}
if (_preActions.ContainsKey(del.Key))
{
_preActions[del.Key](reader);
}
var res = del.Value(reader, this);
_results.Add(del.Key, res);
first = false;
}
}
/// <summary>
/// Utility class used to map columns with type's properties to fill a list of result
/// </summary>
/// <typeparam name="TValue"></typeparam>
public class DataReaderMapper<TValue>
{
private readonly DataReaderHelper _helper;
private readonly string _resultKey;
private readonly IDictionary<string, Action<object, object>> _mapper = new Dictionary<string, Action<object, object>>();
private readonly IList<Action<TValue, IDataReader>> _customMapper = new List<Action<TValue, IDataReader>>();
public DataReaderMapper(DataReaderHelper helper, string resultKey)
{
_helper = helper;
_resultKey = resultKey;
}
/// <summary>
/// Put the value from specified column into the item's property value with func
/// </summary>
/// <typeparam name="TField">The type of the property</typeparam>
/// <param name="columnName">The column's name from the reader result set</param>
/// <param name="func">the function to set value using the column's value</param>
/// <returns></returns>
public DataReaderMapper<TValue> MapField<TField>(string columnName, Action<TValue, TField, DataReaderHelper> func)
{
_mapper.Add(columnName.ToLower(), (value, field) => func((TValue)value, (TField)field, _helper));
return this;
}
/// <summary>
/// Put the value from specified column into the item's property value with func
/// </summary>
/// <typeparam name="TField">The type of the property</typeparam>
/// <param name="columnName">The column's name from the reader result set</param>
/// <param name="func">the function to set value using the column's value</param>
/// <returns></returns>
public DataReaderMapper<TValue> MapField<TField>(string columnName, Action<TValue, TField> func)
{
_mapper.Add(columnName.ToLower(), (value, field) => func((TValue)value, (TField)field));
return this;
}
/// <summary>
/// Manually operate the DataReader and set the property value with func
/// </summary>
/// <param name="func">the function to operate on the current row's corresponding TValue item with DataReader</param>
/// <returns></returns>
public DataReaderMapper<TValue> MapField(Action<TValue, IDataReader> func)
{
_customMapper.Add(func);
return this;
}
public DataReaderMapper<TValue> MapField(Action<TValue> func)
{
_customMapper.Add((value, reader) => func(value));
return this;
}
/// <summary>
/// Auto map the property names of TValue with columns names
/// </summary>
/// <param name="skips">property name's to skip</param>
/// <returns></returns>
public DataReaderMapper<TValue> AutoMap(params string[] skips)
{
var properties = typeof(TValue).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty).Where(p => p.CanWrite && !skips.Contains(p.Name));
foreach (var p in properties)
{
var u = Nullable.GetUnderlyingType(p.PropertyType);
if ((u != null) && u.IsEnum)
{
_mapper.Add(p.Name.ToLower(), (item, value) =>
{
if (value is int)
{
p.SetValue(item, Enum.ToObject(u, (int)value));
}
else if (value is short)
{
p.SetValue(item, Enum.ToObject(u, (short)value));
}
else if (value is long)
{
p.SetValue(item, Enum.ToObject(u, (long)value));
}
else if (value is byte)
{
p.SetValue(item, Enum.ToObject(u, (byte)value));
}
});
}
else
{
_mapper.Add(p.Name.ToLower(), p.SetValue);
}
}
return this;
}
/// <summary>
/// Finsh the mapping and return the context to the dbhelper
/// </summary>
/// <returns></returns>
public DataReaderHelper FinishMap()
{
return _helper.DefineResult(MapperDelegate, _resultKey);
}
private object MapperDelegate(IDataReader reader, DataReaderHelper helper)
{
var ordinals = new Dictionary<int, Action<object, object>>();
for (var i = 0; i < reader.FieldCount; i++)
{
var name = reader.GetName(i).ToLower();
if (_mapper.ContainsKey(name))
{
var ordinal = reader.GetOrdinal(name);
if (!ordinals.ContainsKey(ordinal))
{
ordinals.Add(ordinal, _mapper[name]);
}
}
}
var ret = new List<TValue>();
while (reader.Read())
{
var item = Activator.CreateInstance<TValue>();
foreach (var ordinal in ordinals)
{
ordinal.Value(item, reader.IsDBNull(ordinal.Key) ? null : reader.GetValue(ordinal.Key));
}
foreach (var action in _customMapper)
{
action(item, reader);
}
ret.Add(item);
}
return ret;
}
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Axiom.Core;
using Axiom.ParticleSystems;
using Axiom.MathLib;
namespace Multiverse.Tools.WorldEditor
{
public class DisplayParticleSystem : IDisposable
{
protected string name;
protected SceneManager scene;
protected string particleSystemName;
protected Vector3 scale;
protected Vector3 rotation;
protected Quaternion orientation;
protected Vector3 position;
protected float velocityScale;
protected float particleScale;
protected float baseWidth;
protected float baseHeight;
protected bool attached;
protected Axiom.Animating.TagPoint tagPoint;
protected DisplayObject displayObject;
protected string attachmentPointName;
// Axiom structures for representing the object in the scene
protected ParticleSystem particleSystem;
private SceneNode node = null;
public DisplayParticleSystem(String name, SceneManager scene, string particleSystemName, Vector3 position, Vector3 scale, Vector3 rotation, float velocityScale, float particleScale)
{
this.name = name;
this.scene = scene;
this.particleSystemName = particleSystemName;
this.position = position;
this.scale = scale;
this.rotation = rotation;
this.particleScale = particleScale;
this.velocityScale = velocityScale;
attached = false;
AddToScene();
}
public DisplayParticleSystem(String name, SceneManager scene, string particleSystemName, float velocityScale, float particleScale, DisplayObject displayObject, string attachmentPointName)
{
this.name = name;
this.scene = scene;
this.particleSystemName = particleSystemName;
this.particleScale = particleScale;
this.velocityScale = velocityScale;
this.displayObject = displayObject;
this.attachmentPointName = attachmentPointName;
attached = true;
AddToScene();
}
public float VelocityScale
{
get
{
return velocityScale;
}
set
{
// undo previous scale
particleSystem.ScaleVelocity(1 / velocityScale);
// set the scale
velocityScale = value;
particleSystem.ScaleVelocity(velocityScale);
}
}
public float ParticleScale
{
get
{
return particleScale;
}
set
{
particleScale = value;
particleSystem.DefaultHeight = baseHeight * particleScale;
particleSystem.DefaultWidth = baseHeight * particleScale;
}
}
private void AddToScene()
{
string sceneName = WorldEditor.GetUniqueName(name, "Particle System");
particleSystem = ParticleSystemManager.Instance.CreateSystem(sceneName, particleSystemName);
particleSystem.ScaleVelocity(velocityScale);
baseHeight = particleSystem.DefaultHeight;
baseWidth = particleSystem.DefaultWidth;
ParticleScale = particleScale;
if (attached)
{
Axiom.Animating.AttachmentPoint attachmentPoint = displayObject.GetAttachmentPoint(attachmentPointName);
if (attachmentPoint == null)
{
attachmentPoint = new Axiom.Animating.AttachmentPoint(attachmentPointName, null, Quaternion.Identity, Vector3.Zero);
}
if (attachmentPoint.ParentBone != null)
{
tagPoint = displayObject.Entity.AttachObjectToBone(attachmentPoint.ParentBone, particleSystem, attachmentPoint.Orientation, attachmentPoint.Position);
node = null;
}
else
{
node = scene.CreateSceneNode();
node.Position = attachmentPoint.Position;
node.Orientation = attachmentPoint.Orientation;
displayObject.SceneNode.AddChild(node);
node.AttachObject(particleSystem);
}
}
else
{
node = scene.RootSceneNode.CreateChildSceneNode();
node.AttachObject(particleSystem);
node.Position = position;
node.ScaleFactor = scale;
node.Orientation = Quaternion.FromAngleAxis(rotation.y * MathUtil.RADIANS_PER_DEGREE, Vector3.UnitY);
}
}
private void RemoveFromScene()
{
if (tagPoint != null)
{
displayObject.Entity.DetachObjectFromBone(tagPoint.Parent.Name, tagPoint);
}
else
{
// remove the scene node from the scene's list of all nodes, and from its parent in the tree
node.Creator.DestroySceneNode(node.Name);
node = null;
// XXX - remove the entity from the scene
}
particleSystem = null;
}
/// <summary>
/// Highlight the object. Use the axiom bounding box display as a cheap highlight.
/// </summary>
public bool Highlight
{
get
{
return node.ShowBoundingBox;
}
set
{
node.ShowBoundingBox = value;
}
}
public Vector3 Position
{
get
{
//Debug.Assert(!attached);
return node.Position;
}
set
{
//Debug.Assert(!attached);
node.Position = value;
}
}
public void AdjustRotation(Vector3 v)
{
//Debug.Assert(!attached);
rotation += v;
orientation = (Quaternion.FromAngleAxis(rotation.y * MathUtil.RADIANS_PER_DEGREE, Vector3.UnitY));
return;
}
public Quaternion Orientation
{
get
{
//Debug.Assert(!attached);
return orientation;
}
set
{
//Debug.Assert(!attached);
orientation = value;
if (node != null)
{
node.Orientation = orientation;
}
}
}
public void Dispose()
{
RemoveFromScene();
}
}
}
| |
// Copyright (c) 2015 semdiffdotnet. Distributed under the MIT License.
// See LICENSE file or opensource.org/licenses/MIT.
using Microsoft.CodeAnalysis;
using System;
using System.Collections.Immutable;
namespace SemDiff.Core
{
/// <summary>
/// This class provides our interface for reporting diagnostics using Roslyn
/// </summary>
public class Diagnostics
{
//Shared Values
private const string Category = nameof(SemDiff); //Not sure where this shows up yet
#region SD0001
public const string Sd0001Id = nameof(SD0001);
private const string Sd0001Description =
"SemDiff detected a moved method within the local repository that " +
"was also changed in a pull request. This could create a " +
"False-Positive merge conflict when merging both into the master " +
"branch. False-Positives occur when text-based tools detect a " +
"conflict but there are no semantic differences between the " +
"conflicting changes.";
private const string Sd0001MessageFormat =
"Method '{0}' was moved, but was also changed in a pull request - '{1}' (#{2})";
private const string Sd0001Title = "Local Method Moved, Remote Method Changed";
///<summary>Local Method Moved, Remote Method Changed</summary>
private static readonly DiagnosticDescriptor SD0001 =
new DiagnosticDescriptor(Sd0001Id, Sd0001Title, Sd0001MessageFormat, Category,
DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Sd0001Description);
#endregion SD0001
#region SD0002
public const string Sd0002Id = nameof(SD0002);
private const string Sd0002Description =
"SemDiff detected a changed method within the local repository " +
"that was also moved in a pull request. This could create a " +
"False-Positive merge conflict when merging both into the master " +
"branch. False-Positives occur when text-based tools detect a " +
"conflict but there are no semantic differences between the " +
"conflicting changes.";
private const string Sd0002MessageFormat =
"Method '{0}' was changed, but was also moved in a pull request - '{1}' (#{2})";
private const string Sd0002Title = "Local Method Changed, Remote Method Moved";
///<summary>Local Method Changed, Remote Method Moved</summary>
private static readonly DiagnosticDescriptor SD0002 =
new DiagnosticDescriptor(Sd0002Id, Sd0002Title, Sd0002MessageFormat, Category,
DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Sd0002Description);
#endregion SD0002
#region SD0003
public const string Sd0003Id = nameof(SD0003);
private const string Sd0003Description =
"SemDiff detected that the base class of a class changed within " +
"the local repository was also modified in a pull request. A " +
"False-Negative merge conflict could be created when both are " +
"merged into the master branch. False-Negatives occur when " +
"text-based tools fail to detect a conflict that affects the " +
"semantics of the application. In other words, when merging " +
"changes the runtime behavior of the application.";
private const string Sd0003MessageFormat =
"The base class of '{0}' ('{1}') was changed in a pull request - '{2}' (#{3})";
private const string Sd0003Title = "Base Class of Locally Modified Class Changed Remotely";
///<summary>Base Class of Locally Modified Class Changed Remotely</summary>
private static readonly DiagnosticDescriptor SD0003 =
new DiagnosticDescriptor(Sd0003Id, Sd0003Title, Sd0003MessageFormat, Category,
DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Sd0003Description);
#endregion SD0003
#region SD0004
public const string Sd0004Id = nameof(SD0004);
private const string Sd0004Description =
"SemDiff detected that changes in the local file and GitHub " +
"indicated that the file has been either changed or renamed in a " +
"pull request. No further analysis is done on changed or renamed " +
"files, but a file that has been changed or renamed in another " +
"pull request could indicate a possible conflict. A changed file " +
"could have had its permission changed or was part of a truncated " +
"diff (GitHub will not process all of the files in a large pull " +
"request).";
private const string Sd0004MessageFormat =
"File has been modified locally as well as changed or renamed in a pull request - '{0}' (#{1})";
private const string Sd0004Title = "Locally Changed File Changed or Renamed Remotely";
///<summary>Locally Changed File Changed or Renamed Remotely</summary>
private static readonly DiagnosticDescriptor SD0004 =
new DiagnosticDescriptor(Sd0004Id, Sd0004Title, Sd0004MessageFormat, Category,
DiagnosticSeverity.Info, isEnabledByDefault: true, description: Sd0004Description);
#endregion SD0004
#region SD1001
public const string Sd1001Id = nameof(SD1001);
private const string Sd1001MessageFormat =
"SemDiff Internal Error While {0} - {1}";
private const string Sd1001Title = "SemDiff Internal Error";
///<summary>SemDiff Internal Error</summary>
private static readonly DiagnosticDescriptor SD1001 =
new DiagnosticDescriptor(Sd1001Id, Sd1001Title, Sd1001MessageFormat, Category,
DiagnosticSeverity.Warning, isEnabledByDefault: true);
#endregion SD1001
#region SD2001
public const string Sd2001Id = nameof(SD2001);
private const string Sd2001Description =
"SemDiff uses the GitHub API to request information about pull " +
"requests. However, GitHub limits the number of requests to the " +
"API using a rate limit. The rate limit can be increased by using " +
"authentication. See the SemDiff wiki for more information.";
///<summary>This should be shown only when the rate limit is hit AND the user is unauthenticated
private const string RateLimitWikiTipText =
" (enable authentication to raise rate limit https://goo.gl/W19V7U)";
private const string Sd2001MessageFormat =
"SemDiff has exceeded the rate limit of {0} requests per hour imposed by GitHub.{1}";
private const string Sd2001Title = "GitHub Rate Limit Exceeded";
///<summary>GitHub Rate Limit Exceeded</summary>
private static readonly DiagnosticDescriptor SD2001 =
new DiagnosticDescriptor(Sd2001Id, Sd2001Title, Sd2001MessageFormat, Category,
DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Sd2001Description);
#endregion SD2001
#region SD2002
public const string Sd2002Id = nameof(SD2002);
private const string Sd2002Description =
"The .git/config file found does not contain a GitHub remote. " +
"The repo is likely not a GitHub repo.";
private const string Sd2002MessageFormat =
"Git repo found, but has no GitHub remote - {0}";
private const string Sd2002Title = "GitHub Remote not Found";
///<summary>GitHub Remote not Found</summary>
private static readonly DiagnosticDescriptor SD2002 =
new DiagnosticDescriptor(Sd2002Id, Sd2002Title, Sd2002MessageFormat, Category,
DiagnosticSeverity.Info, isEnabledByDefault: true, description: Sd2002Description);
#endregion SD2002
#region SD2003
public const string Sd2003Id = nameof(SD2003);
private const string Sd2003MessageFormat =
"GitHub Authentication - {0}";
private const string Sd2003Title = "GitHub Authentication Problem";
///<summary>GitHub Authentication Problem</summary>
private static readonly DiagnosticDescriptor SD2003 =
new DiagnosticDescriptor(Sd2003Id, Sd2003Title, Sd2003MessageFormat, Category,
DiagnosticSeverity.Warning, isEnabledByDefault: true);
#endregion SD2003
/// <summary>
/// The Diagnostics we support, provided for the SupportedDiagnostics property of DiagnosticAnalyzer
/// </summary>
public static ImmutableArray<DiagnosticDescriptor> Supported { get; } =
ImmutableArray.Create(SD0001, SD0002, SD0003, SD0004, SD1001, SD2001, SD2002, SD2003);
/// <summary>
/// Converts `DetectedFalsePositive`s to Diagnostics (the class provided by Roslyn) and
/// sends them to the function provided
/// </summary>
/// <param name="fps">the object that contains the information to populate the error message</param>
public static Diagnostic Convert(DetectedFalsePositive fps)
{
if (fps.ConflictType == DetectedFalsePositive.ConflictTypes.LocalMethodRemoved)
{
return Diagnostic.Create(SD0001, fps.Location, fps.MethodName, fps.RemoteChange.Title, fps.RemoteChange.Number);
}
else if (fps.ConflictType == DetectedFalsePositive.ConflictTypes.LocalMethodChanged)
{
return Diagnostic.Create(SD0002, fps.Location, fps.MethodName, fps.RemoteChange.Title, fps.RemoteChange.Number);
}
throw new NotImplementedException(fps.ConflictType.ToString());
}
/// <summary>
/// Converts `DetectedFalseNegative`s to Diagnostics (the class provided by Roslyn) and
/// sends them to the function provided
/// </summary>
/// <param name="fns">the object that contains the information to populate the error message</param>
public static Diagnostic Convert(DetectedFalseNegative fns)
{
return Diagnostic.Create(SD0003, fns.Location, fns.DerivedTypeName, fns.BaseTypeName, fns.RemoteChange.Title, fns.RemoteChange.Number);
}
/// <summary>
/// Returns a diagnostic that represents a message that a repo was found but could a GitHub
/// url was not found.
/// </summary>
/// <param name="path">The exception message that should contain the path</param>
public static Diagnostic NotGitHubRepo(string path)
{
return Diagnostic.Create(SD2002, Location.None, path);
}
/// <summary>
/// Returns a diagnostic that represents a friendly message that the rate limit has been
/// exceeded and a link to our documentation.
/// </summary>
/// <param name="rateLimit">Maximum rate limit value</param>
/// <param name="authenticated">true if user is authenticated</param>
public static Diagnostic RateLimit(int rateLimit, bool authenticated)
{
return Diagnostic.Create(SD2001, Location.None, rateLimit, authenticated ? "" : RateLimitWikiTipText);
}
/// <summary>
/// Returns a Diagnostic that represents authentication failure
/// </summary>
/// <param name="githubMessage">Message returned by the github api</param>
public static Diagnostic AuthenticationFailure(string githubMessage)
{
return Diagnostic.Create(SD2003, Location.None, githubMessage);
}
/// <summary>
/// Should create a diagnostic that represents something like this: Unexpected Error
/// Occurred while ((verbNounPhrase))
/// </summary>
/// <param name="verbNounPhrase">
/// Something like: Washing the Car, Mowing the Lawn, or Burning out a Fuse up here Alone
/// </param>
/// <param name="message">
/// Exception message
/// </param>
public static Diagnostic UnexpectedError(string verbNounPhrase, string message)
{
return Diagnostic.Create(SD1001, Location.None, verbNounPhrase, message);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
namespace Internal.Cryptography.Pal
{
internal static class CrlCache
{
public static void AddCrlForCertificate(
X509Certificate2 cert,
SafeX509StoreHandle store,
X509RevocationMode revocationMode,
DateTime verificationTime,
ref TimeSpan remainingDownloadTime)
{
// In Offline mode, accept any cached CRL we have.
// "CRL is Expired" is a better match for Offline than "Could not find CRL"
if (revocationMode != X509RevocationMode.Online)
{
verificationTime = DateTime.MinValue;
}
if (AddCachedCrl(cert, store, verificationTime))
{
return;
}
// Don't do any work if we're over limit or prohibited from fetching new CRLs
if (remainingDownloadTime <= TimeSpan.Zero ||
revocationMode != X509RevocationMode.Online)
{
return;
}
DownloadAndAddCrl(cert, store, ref remainingDownloadTime);
}
private static bool AddCachedCrl(X509Certificate2 cert, SafeX509StoreHandle store, DateTime verificationTime)
{
string crlFile = GetCachedCrlPath(cert);
using (SafeBioHandle bio = Interop.Crypto.BioNewFile(crlFile, "rb"))
{
if (bio.IsInvalid)
{
return false;
}
// X509_STORE_add_crl will increase the refcount on the CRL object, so we should still
// dispose our copy.
using (SafeX509CrlHandle crl = Interop.Crypto.PemReadBioX509Crl(bio))
{
if (crl.IsInvalid)
{
return false;
}
// If crl.LastUpdate is in the past, downloading a new version isn't really going
// to help, since we can't rewind the Internet. So this is just going to fail, but
// at least it can fail without using the network.
//
// If crl.NextUpdate is in the past, try downloading a newer version.
DateTime nextUpdate = OpenSslX509CertificateReader.ExtractValidityDateTime(
Interop.Crypto.GetX509CrlNextUpdate(crl));
// OpenSSL is going to convert our input time to universal, so we should be in Local or
// Unspecified (local-assumed).
Debug.Assert(
verificationTime.Kind != DateTimeKind.Utc,
"UTC verificationTime should have been normalized to Local");
// In the event that we're to-the-second accurate on the match, OpenSSL will consider this
// to be already expired.
if (nextUpdate <= verificationTime)
{
return false;
}
// TODO (#3063): Check the return value of X509_STORE_add_crl, and throw on any error other
// than X509_R_CERT_ALREADY_IN_HASH_TABLE
Interop.Crypto.X509StoreAddCrl(store, crl);
return true;
}
}
}
private static void DownloadAndAddCrl(
X509Certificate2 cert,
SafeX509StoreHandle store,
ref TimeSpan remainingDownloadTime)
{
string url = GetCdpUrl(cert);
if (url == null)
{
return;
}
// X509_STORE_add_crl will increase the refcount on the CRL object, so we should still
// dispose our copy.
using (SafeX509CrlHandle crl = CertificateAssetDownloader.DownloadCrl(url, ref remainingDownloadTime))
{
// null is a valid return (e.g. no remainingDownloadTime)
if (crl != null && !crl.IsInvalid)
{
// TODO (#3063): Check the return value of X509_STORE_add_crl, and throw on any error other
// than X509_R_CERT_ALREADY_IN_HASH_TABLE
Interop.Crypto.X509StoreAddCrl(store, crl);
// Saving the CRL to the disk is just a performance optimization for later requests to not
// need to use the network again, so failure to save shouldn't throw an exception or mark
// the chain as invalid.
try
{
string crlFile = GetCachedCrlPath(cert, mkDir: true);
using (SafeBioHandle bio = Interop.Crypto.BioNewFile(crlFile, "wb"))
{
if (!bio.IsInvalid)
{
Interop.Crypto.PemWriteBioX509Crl(bio, crl);
}
}
}
catch (IOException)
{
}
}
}
}
private static string GetCachedCrlPath(X509Certificate2 cert, bool mkDir=false)
{
OpenSslX509CertificateReader pal = (OpenSslX509CertificateReader)cert.Pal;
string crlDir = PersistedFiles.GetUserFeatureDirectory(
X509Persistence.CryptographyFeatureName,
X509Persistence.CrlsSubFeatureName);
// X509_issuer_name_hash returns "unsigned long", which is marshalled as ulong.
// But it only sets 32 bits worth of data, so force it down to uint just... in case.
ulong persistentHashLong = Interop.Crypto.X509IssuerNameHash(pal.SafeHandle);
uint persistentHash = unchecked((uint)persistentHashLong);
// OpenSSL's hashed filename algorithm is the 8-character hex version of the 32-bit value
// of X509_issuer_name_hash (or X509_subject_name_hash, depending on the context).
string localFileName = persistentHash.ToString("x8") + ".crl";
if (mkDir)
{
Directory.CreateDirectory(crlDir);
}
return Path.Combine(crlDir, localFileName);
}
private static string GetCdpUrl(X509Certificate2 cert)
{
byte[] crlDistributionPoints = null;
foreach (X509Extension extension in cert.Extensions)
{
if (StringComparer.Ordinal.Equals(extension.Oid.Value, Oids.CrlDistributionPoints))
{
// If there's an Authority Information Access extension, it might be used for
// looking up additional certificates for the chain.
crlDistributionPoints = extension.RawData;
break;
}
}
if (crlDistributionPoints == null)
{
return null;
}
// CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
//
// DistributionPoint ::= SEQUENCE {
// distributionPoint [0] DistributionPointName OPTIONAL,
// reasons [1] ReasonFlags OPTIONAL,
// cRLIssuer [2] GeneralNames OPTIONAL }
//
// DistributionPointName ::= CHOICE {
// fullName [0] GeneralNames,
// nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
//
// GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
//
// GeneralName ::= CHOICE {
// otherName [0] OtherName,
// rfc822Name [1] IA5String,
// dNSName [2] IA5String,
// x400Address [3] ORAddress,
// directoryName [4] Name,
// ediPartyName [5] EDIPartyName,
// uniformResourceIdentifier [6] IA5String,
// iPAddress [7] OCTET STRING,
// registeredID [8] OBJECT IDENTIFIER }
DerSequenceReader cdpSequence = new DerSequenceReader(crlDistributionPoints);
while (cdpSequence.HasData)
{
const byte ContextSpecificFlag = 0x80;
const byte ContextSpecific0 = ContextSpecificFlag;
const byte ConstructedFlag = 0x20;
const byte ContextSpecificConstructed0 = ContextSpecific0 | ConstructedFlag;
const byte GeneralNameUri = ContextSpecificFlag | 0x06;
DerSequenceReader distributionPointReader = cdpSequence.ReadSequence();
byte tag = distributionPointReader.PeekTag();
// Only distributionPoint is supported
if (tag != ContextSpecificConstructed0)
{
continue;
}
// The DistributionPointName is a CHOICE, not a SEQUENCE, but the reader is the same.
DerSequenceReader dpNameReader = distributionPointReader.ReadSequence();
tag = dpNameReader.PeekTag();
// Only fullName is supported,
// nameRelativeToCRLIssuer is for LDAP-based lookup.
if (tag != ContextSpecificConstructed0)
{
continue;
}
DerSequenceReader fullNameReader = dpNameReader.ReadSequence();
while (fullNameReader.HasData)
{
tag = fullNameReader.PeekTag();
if (tag != GeneralNameUri)
{
fullNameReader.SkipValue();
continue;
}
string uri = fullNameReader.ReadIA5String();
Uri parsedUri = new Uri(uri);
if (!StringComparer.Ordinal.Equals(parsedUri.Scheme, "http"))
{
continue;
}
return uri;
}
}
return null;
}
}
}
| |
// ===========================================================
// Copyright (C) 2014-2015 Kendar.org
//
// 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 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 System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Web.UI.WebControls;
using ClassWrapper;
using Node.Cs.Lib.Attributes;
using Node.Cs.Lib.Attributes.Validation;
using Node.Cs.Lib.Utils;
using RazorEngine.Templating;
using RazorEngine.Text;
namespace Node.Cs.Razor.Helpers
{
public partial class HtmlHelper<T>
{
private ItemData GetItemData<TK>(Expression<Func<TK>> expression, bool pValue = false, bool mValue = false)
{
var result = new ItemData
{
MainType = Lambda.GetObjectType(expression),
PropertyName = Lambda.GetPropertyName(expression)
};
if (_classWrapper != null && _classWrapper.Instance.GetType() == result.MainType)
{
result.PropertyAttributes = _wrapperDescriptor.GetProperty(result.PropertyName).Attributes.ToArray();
if (pValue)
{
result.PropertyValue = _classWrapper.GetObject(result.PropertyName);
}
}
else
{
result.PropertyAttributes = Lambda.GetCustomAttribues(expression).Select(a => (Attribute)a);
if (pValue)
{
result.PropertyValue = Lambda.GetPropertyValue(expression);
}
}
if (mValue)
{
result.MainValue = Lambda.GetObject(expression);
}
return result;
}
public RawString LabelFor<TK>(Expression<Func<TK>> propertyLambda, string label = null)
{
if (label != null) return new RawString(label);
var itemData = GetItemData(propertyLambda);
foreach (var attr in itemData.PropertyAttributes)
{
var disp = attr as DisplayAttribute;
if (disp != null)
{
return new RawString(disp.Name);
}
}
return new RawString(itemData.PropertyName);
}
private RawString InputTypeFor<TK>(string inputType, Expression<Func<TK>> propertyLambda, string value = null)
{
var itemData = GetItemData(propertyLambda, true);
if (value == null)
{
value = "";
if (itemData.PropertyValue != null) value = itemData.PropertyValue.ToString();
}
var stringLengthAttribute =
(StringLengthAttribute)itemData.PropertyAttributes.FirstOrDefault(a => a.GetType() == typeof(StringLengthAttribute));
if (stringLengthAttribute == null)
return InputTypeFor(inputType, itemData.PropertyName, value);
return InputTypeFor(inputType, itemData.PropertyName, value, stringLengthAttribute);
}
public RawString CheckBoxFor<TK>(Expression<Func<TK>> propertyLambda)
{
var itemData = GetItemData(propertyLambda, true);
bool value = false;
if (itemData.PropertyValue != null)
{
value = (bool)itemData.PropertyValue;
}
var hiddenText = HiddenFor(itemData.PropertyName, "false");
var checkBox = InputTypeFor("checkbox", propertyLambda, value ? "true" : "");
return new RawString(hiddenText.ToString() + checkBox.ToString());
}
public RawString DisplayFor<TK>(Expression<Func<TK>> propertyLambda)
{
var itemData = GetItemData(propertyLambda, true);
var value = itemData.PropertyValue ?? string.Empty;
return new RawString(value.ToString());
}
public RawString CheckBoxFor(string id)
{
var hiddenText = HiddenFor(id, "false");
var checkBox = InputTypeFor("checkbox", id);
return new RawString(hiddenText.ToString() + checkBox.ToString());
}
private RawString InputTypeFor(string inputType, string name, string value = "", StringLengthAttribute attr = null)
{
var partial = new Dictionary<string, object>
{
{"type", inputType},
{"id", name},
{"name", name},
{"value", value}
};
if (attr != null && attr.MaximumLength > 0)
{
partial.Add("maxlength", attr.MaximumLength);
}
var result = TagBuilder.StartTag("input", partial, true);
return new RawString(result);
}
public RawString LabelFor(string label)
{
return new RawString(label);
}
public RawString TextBoxFor<TK>(Expression<Func<TK>> propertyLambda)
{
return InputTypeFor("text", propertyLambda);
}
public RawString TextBoxFor(string id, string value = "")
{
return InputTypeFor("text", id, value);
}
public RawString HiddenFor<TK>(Expression<Func<TK>> propertyLambda)
{
return InputTypeFor("hidden", propertyLambda);
}
public RawString HiddenFor(string id, string value = "")
{
return InputTypeFor("hidden", id, value);
}
public RawString PasswordFor<TK>(Expression<Func<TK>> propertyLambda)
{
return InputTypeFor("password", propertyLambda);
}
public RawString PasswordFor(string id, string value = "")
{
return InputTypeFor("password", id, value);
}
public RawString FileFor<TK>(Expression<Func<TK>> propertyLambda)
{
return InputTypeFor("file", propertyLambda);
}
public RawString FileFor(string id)
{
return InputTypeFor("file", id);
}
public RawString ValidationSummary(bool whoKnows, string message = null)
{
if (ViewContext.ModelState.IsValid) return new RawString("");
var errors = ViewContext.ModelState.GetErrors("");
var result = message ?? string.Empty;
if (errors.Count > 0)
{
result += "<ul>";
foreach (var error in errors)
{
result += "<li>" + error + "</li>";
}
result += "</ul>";
}
return new RawString(result);
}
public RawString ValidationMessageFor<TK>(Expression<Func<TK>> propertyLambda)
{
if (ViewContext.ModelState.IsValid) return new RawString("");
var name = Lambda.GetPropertyName(propertyLambda);
var errors = ViewContext.ModelState.GetErrors(name);
if (errors.Count == 0) return new RawString("");
var result = "";
if (errors.Count > 1)
{
result += "<ul>";
foreach (var error in errors)
{
result += "<li>" + error + "</li>";
}
result += "</ul>";
}
else
{
result = errors[0];
}
return new RawString(result);
}
public RawString EditorFor<TK>(Expression<Func<TK>> propertyLambda)
{
var itemData = GetItemData(propertyLambda, true);
IEnumerable<Attribute> attributes = null;
attributes = itemData.PropertyAttributes;
var dataType = DataType.Text;
foreach (var attr in attributes)
{
var disp = attr as DataTypeAttribute;
if (disp != null)
{
dataType = disp.DataType;
}
else
{
var sca = attr as ScaffoldColumnAttribute;
if (sca != null)
{
if (!sca.Scaffold)
{
return HiddenFor(propertyLambda);
}
}
}
}
var label = LabelFor(propertyLambda);
switch (dataType)
{
case (DataType.Upload):
return Combine(label, FileFor(propertyLambda));
case (DataType.Password):
return Combine(label, PasswordFor(propertyLambda));
case (DataType.Html):
case (DataType.Url):
case (DataType.EmailAddress):
case (DataType.ImageUrl):
case (DataType.MultilineText):
throw new NotImplementedException("DataType");
default:
return Combine(label, TextBoxFor(propertyLambda));
}
}
private RawString EditorFor(PropertyWrapperDescriptor wrapperDescriptor)
{
string name = wrapperDescriptor.Name;
IEnumerable<Attribute> attributes = wrapperDescriptor.Attributes;
var value = _classWrapper.GetObject(name);
string stringValue = value == null ? string.Empty : value.ToString();
var dataType = DataType.Text;
foreach (var attr in attributes)
{
var disp = attr as DataTypeAttribute;
if (disp != null)
{
dataType = disp.DataType;
}
else
{
var sca = attr as ScaffoldColumnAttribute;
if (sca != null)
{
if (!sca.Scaffold)
{
return HiddenFor(name, stringValue);
}
}
}
}
var label = "<div class='editor-label'>" + LabelFor(name) + "</div>";
const string startField = "<div class='editor-field'>";
const string endField = "</div>";
switch (dataType)
{
case (DataType.Upload):
return Combine(label, startField + FileFor(name) + endField);
case (DataType.Password):
return Combine(label, startField + PasswordFor(name, stringValue) + endField);
case (DataType.Html):
case (DataType.Url):
case (DataType.ImageUrl):
case (DataType.MultilineText):
throw new NotImplementedException("DataType");
case (DataType.EmailAddress):
default:
return Combine(label, startField + TextBoxFor(name, stringValue) + endField);
}
}
private RawString Combine(string label, string rest)
{
return new RawString(label + rest);
}
private RawString Combine(params RawString[] raws)
{
var stringResult = string.Empty;
foreach (var raw in raws)
{
stringResult += "\r\n" + raw;
}
return new RawString(stringResult);
}
public RawString DropDownList(string id, object selectedValue = null)
{
var mem = Lambda.GetProperty(ViewBag, id);
var sl = mem as SelectList;
if (sl == null) throw new Exception("Missing SelectList for id " + id);
string selTostring = null;
if (selectedValue != null)
{
selTostring = selectedValue.ToString();
}
var start = TagBuilder.StartTag("select", new Dictionary<string, object> { { "id", id }, { "name", id } });
var options = string.Empty;
var end = TagBuilder.EndTag("select");
var starting = true;
MethodInfo pinfovalue = null;
MethodInfo pinfotext = null;
foreach (var item in sl.Items)
{
var selected = false;
if (starting)
{
pinfovalue = item.GetType().GetProperty(sl.DataValueField).GetGetMethod();
pinfotext = pinfovalue;
if (sl.DataTextField != sl.DataValueField)
{
pinfotext = item.GetType().GetProperty(sl.DataTextField).GetGetMethod();
}
starting = false;
}
var value = pinfovalue.Invoke(item, new object[] { }).ToString();
// ReSharper disable once RedundantToStringCall
var text = value.ToString();
if (sl.DataTextField != sl.DataValueField)
{
text = pinfotext.Invoke(item, new object[] { }).ToString();
}
if (selTostring != null && selTostring == value)
{
selected = true;
}
var dict = new Dictionary<string, object>();
if (selected)
{
dict.Add("selected", "selected");
}
dict.Add("value", value);
options += TagBuilder.TagWithValue("option", text, dict);
}
return new RawString(start + options + end);
}
public RawString Label(string labelText)
{
return new RawString(labelText);
}
public RawString TextBox(string id)
{
return TextBoxFor(id);
}
}
}
| |
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using FluentAssertions;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.RequiredRelationships
{
public sealed class DefaultBehaviorTests : IClassFixture<IntegrationTestContext<TestableStartup<DefaultBehaviorDbContext>, DefaultBehaviorDbContext>>
{
private readonly IntegrationTestContext<TestableStartup<DefaultBehaviorDbContext>, DefaultBehaviorDbContext> _testContext;
private readonly DefaultBehaviorFakers _fakers = new();
public DefaultBehaviorTests(IntegrationTestContext<TestableStartup<DefaultBehaviorDbContext>, DefaultBehaviorDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<OrdersController>();
testContext.UseController<ShipmentsController>();
testContext.UseController<CustomersController>();
var options = (JsonApiOptions)testContext.Factory.Services.GetRequiredService<IJsonApiOptions>();
options.UseRelativeLinks = true;
}
[Fact]
public async Task Cannot_create_dependent_side_of_required_ManyToOne_relationship_without_providing_principal_side()
{
// Arrange
Order order = _fakers.Orders.Generate();
var requestBody = new
{
data = new
{
type = "orders",
attributes = new
{
order = order.Amount
}
}
};
const string route = "/orders";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.InternalServerError);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.InternalServerError);
error.Title.Should().Be("An unhandled error occurred while processing this request.");
error.Detail.Should().Be("Failed to persist changes in the underlying data store.");
}
[Fact]
public async Task Cannot_create_dependent_side_of_required_OneToOne_relationship_without_providing_principal_side()
{
// Arrange
Shipment shipment = _fakers.Shipments.Generate();
var requestBody = new
{
data = new
{
type = "shipments",
attributes = new
{
trackAndTraceCode = shipment.TrackAndTraceCode
}
}
};
const string route = "/shipments";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.InternalServerError);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.InternalServerError);
error.Title.Should().Be("An unhandled error occurred while processing this request.");
error.Detail.Should().Be("Failed to persist changes in the underlying data store.");
}
[Fact]
public async Task Deleting_principal_side_of_required_OneToMany_relationship_triggers_cascading_delete()
{
// Arrange
Order existingOrder = _fakers.Orders.Generate();
existingOrder.Customer = _fakers.Customers.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Orders.Add(existingOrder);
await dbContext.SaveChangesAsync();
});
string route = $"/customers/{existingOrder.Customer.StringId}";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Customer existingCustomerInDatabase = await dbContext.Customers.FirstWithIdOrDefaultAsync(existingOrder.Customer.Id);
existingCustomerInDatabase.Should().BeNull();
Order existingOrderInDatabase = await dbContext.Orders.FirstWithIdOrDefaultAsync(existingOrder.Id);
existingOrderInDatabase.Should().BeNull();
});
}
[Fact]
public async Task Deleting_principal_side_of_required_OneToOne_relationship_triggers_cascading_delete()
{
// Arrange
Order existingOrder = _fakers.Orders.Generate();
existingOrder.Shipment = _fakers.Shipments.Generate();
existingOrder.Customer = _fakers.Customers.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Orders.Add(existingOrder);
await dbContext.SaveChangesAsync();
});
string route = $"/orders/{existingOrder.StringId}";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Order existingOrderInDatabase = await dbContext.Orders.FirstWithIdOrDefaultAsync(existingOrder.Id);
existingOrderInDatabase.Should().BeNull();
Shipment existingShipmentInDatabase = await dbContext.Shipments.FirstWithIdOrDefaultAsync(existingOrder.Shipment.Id);
existingShipmentInDatabase.Should().BeNull();
Customer existingCustomerInDatabase = await dbContext.Customers.FirstWithIdOrDefaultAsync(existingOrder.Customer.Id);
existingCustomerInDatabase.Should().NotBeNull();
});
}
[Fact]
public async Task Cannot_clear_required_ManyToOne_relationship_through_primary_endpoint()
{
// Arrange
Order existingOrder = _fakers.Orders.Generate();
existingOrder.Shipment = _fakers.Shipments.Generate();
existingOrder.Customer = _fakers.Customers.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Orders.Add(existingOrder);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
id = existingOrder.StringId,
type = "orders",
relationships = new
{
customer = new
{
data = (object)null
}
}
}
};
string route = $"/orders/{existingOrder.StringId}";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.BadRequest);
error.Title.Should().Be("Failed to clear a required relationship.");
error.Detail.Should().Be($"The relationship 'customer' of resource type 'orders' with ID '{existingOrder.StringId}' " +
"cannot be cleared because it is a required relationship.");
}
[Fact]
public async Task Cannot_clear_required_ManyToOne_relationship_through_relationship_endpoint()
{
// Arrange
Order existingOrder = _fakers.Orders.Generate();
existingOrder.Shipment = _fakers.Shipments.Generate();
existingOrder.Customer = _fakers.Customers.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Orders.Add(existingOrder);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = (object)null
};
string route = $"/orders/{existingOrder.StringId}/relationships/customer";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.BadRequest);
error.Title.Should().Be("Failed to clear a required relationship.");
error.Detail.Should().Be($"The relationship 'customer' of resource type 'orders' with ID '{existingOrder.StringId}' " +
"cannot be cleared because it is a required relationship.");
}
[Fact]
public async Task Cannot_clear_required_OneToMany_relationship_through_primary_endpoint()
{
// Arrange
Order existingOrder = _fakers.Orders.Generate();
existingOrder.Shipment = _fakers.Shipments.Generate();
existingOrder.Customer = _fakers.Customers.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Orders.Add(existingOrder);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
id = existingOrder.Customer.StringId,
type = "customers",
relationships = new
{
orders = new
{
data = Array.Empty<object>()
}
}
}
};
string route = $"/customers/{existingOrder.Customer.StringId}";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.BadRequest);
error.Title.Should().Be("Failed to clear a required relationship.");
error.Detail.Should().Be($"The relationship 'orders' of resource type 'customers' with ID '{existingOrder.StringId}' " +
"cannot be cleared because it is a required relationship.");
}
[Fact]
public async Task Cannot_clear_required_OneToMany_relationship_by_updating_through_relationship_endpoint()
{
// Arrange
Order existingOrder = _fakers.Orders.Generate();
existingOrder.Shipment = _fakers.Shipments.Generate();
existingOrder.Customer = _fakers.Customers.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Orders.Add(existingOrder);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = Array.Empty<object>()
};
string route = $"/customers/{existingOrder.Customer.StringId}/relationships/orders";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.BadRequest);
error.Title.Should().Be("Failed to clear a required relationship.");
error.Detail.Should().Be($"The relationship 'orders' of resource type 'customers' with ID '{existingOrder.StringId}' " +
"cannot be cleared because it is a required relationship.");
}
[Fact]
public async Task Cannot_clear_required_OneToMany_relationship_by_deleting_through_relationship_endpoint()
{
// Arrange
Order existingOrder = _fakers.Orders.Generate();
existingOrder.Shipment = _fakers.Shipments.Generate();
existingOrder.Customer = _fakers.Customers.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Orders.Add(existingOrder);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new object[]
{
new
{
type = "orders",
id = existingOrder.StringId
}
}
};
string route = $"/customers/{existingOrder.Customer.StringId}/relationships/orders";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.BadRequest);
error.Title.Should().Be("Failed to clear a required relationship.");
error.Detail.Should().Be($"The relationship 'orders' of resource type 'customers' with ID '{existingOrder.StringId}' " +
"cannot be cleared because it is a required relationship.");
}
[Fact]
public async Task Can_reassign_dependent_side_of_ZeroOrOneToOne_relationship_through_primary_endpoint()
{
// Arrange
Order orderWithShipment = _fakers.Orders.Generate();
orderWithShipment.Shipment = _fakers.Shipments.Generate();
orderWithShipment.Customer = _fakers.Customers.Generate();
Order orderWithoutShipment = _fakers.Orders.Generate();
orderWithoutShipment.Customer = _fakers.Customers.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Orders.AddRange(orderWithShipment, orderWithoutShipment);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
id = orderWithoutShipment.StringId,
type = "orders",
relationships = new
{
shipment = new
{
data = new
{
id = orderWithShipment.Shipment.StringId,
type = "shipments"
}
}
}
}
};
string route = $"/orders/{orderWithoutShipment.StringId}";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Shipment existingShipmentInDatabase =
await dbContext.Shipments.Include(shipment => shipment.Order).FirstWithIdOrDefaultAsync(orderWithShipment.Shipment.Id);
existingShipmentInDatabase.Order.Id.Should().Be(orderWithoutShipment.Id);
});
}
[Fact]
public async Task Can_reassign_dependent_side_of_ZeroOrOneToOne_relationship_through_relationship_endpoint()
{
// Arrange
Order orderWithShipment = _fakers.Orders.Generate();
orderWithShipment.Shipment = _fakers.Shipments.Generate();
orderWithShipment.Customer = _fakers.Customers.Generate();
Order orderWithoutShipment = _fakers.Orders.Generate();
orderWithoutShipment.Customer = _fakers.Customers.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Orders.AddRange(orderWithShipment, orderWithoutShipment);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
id = orderWithShipment.Shipment.StringId,
type = "shipments"
}
};
string route = $"/orders/{orderWithoutShipment.StringId}/relationships/shipment";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Shipment existingShipmentInDatabase =
await dbContext.Shipments.Include(shipment => shipment.Order).FirstWithIdOrDefaultAsync(orderWithShipment.Shipment.Id);
existingShipmentInDatabase.Order.Id.Should().Be(orderWithoutShipment.Id);
});
}
}
}
| |
#region Header
/*
* The authors disclaim copyright to this source code.
* For more details, see the COPYING file included with this distribution.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace LitJson {
internal enum Condition {
InArray,
InObject,
NotAProperty,
Property,
Value
}
internal class WriterContext {
public int Count, Padding;
public bool InArray, InObject;
public bool ExpectingValue;
}
/// <summary>
/// Stream-like facility to output JSON text.
/// </summary>
public class JsonWriter {
private static readonly NumberFormatInfo numberFormat;
private WriterContext context;
private Stack<WriterContext> ctxStack;
private bool hasReachedEnd;
private char[] hexSeq;
private int indentation, indentValue;
private StringBuilder stringBuilder;
public int IndentValue {
get { return indentValue; }
set {
indentation = (indentation / indentValue) * value;
indentValue = value;
}
}
public bool PrettyPrint { get; set; }
public bool Validate { get; set; }
public bool TypeHinting { get; set; }
public string HintTypeName { get; set; }
public string HintValueName { get; set; }
public TextWriter TextWriter { get; private set; }
static JsonWriter() {
numberFormat = NumberFormatInfo.InvariantInfo;
}
public JsonWriter() {
stringBuilder = new StringBuilder();
TextWriter = new StringWriter(stringBuilder);
Init();
}
public JsonWriter(StringBuilder sb) : this(new StringWriter(sb)) {
}
public JsonWriter(TextWriter writer) {
if (writer == null) {
throw new ArgumentNullException("writer");
}
this.TextWriter = writer;
Init();
}
private void DoValidation(Condition cond) {
if (!context.ExpectingValue) {
context.Count++;
}
if (!Validate) {
return;
}
if (hasReachedEnd) {
throw new JsonException("A complete JSON symbol has already been written");
}
switch (cond) {
case Condition.InArray:
if (!context.InArray) {
throw new JsonException("Can't close an array here");
}
break;
case Condition.InObject:
if (!context.InObject || context.ExpectingValue) {
throw new JsonException("Can't close an object here");
}
break;
case Condition.NotAProperty:
if (context.InObject && !context.ExpectingValue) {
throw new JsonException("Expected a property in obj? "+context.InObject+" expect val? "+context.ExpectingValue+" <"+stringBuilder.ToString()+">");
}
break;
case Condition.Property:
if (!context.InObject || context.ExpectingValue) {
throw new JsonException("Can't add a property here");
}
break;
case Condition.Value:
if (!context.InArray &&
(!context.InObject || !context.ExpectingValue)) {
throw new JsonException("Can't add a value here");
}
break;
}
}
private void Init() {
hasReachedEnd = false;
hexSeq = new char[4];
indentation = 0;
indentValue = 4;
PrettyPrint = false;
Validate = true;
TypeHinting = false;
HintTypeName = "__type__";
HintValueName = "__value__";
ctxStack = new Stack<WriterContext>();
context = new WriterContext();
ctxStack.Push(context);
}
private static void IntToHex(int n, char[] hex) {
int num;
for (int i = 0; i < 4; i++) {
num = n % 16;
if (num < 10) {
hex[3 - i] = (char) ('0' + num);
} else {
hex[3 - i] = (char) ('A' + (num - 10));
}
n >>= 4;
}
}
private void Indent() {
if (PrettyPrint) {
indentation += indentValue;
}
}
private void Put(string str) {
if (PrettyPrint && !context.ExpectingValue) {
for (int i = 0; i < indentation; i++) {
TextWriter.Write(' ');
}
}
TextWriter.Write(str);
}
private void PutNewline(bool addComma = true) {
if (addComma && !context.ExpectingValue && context.Count > 1) {
TextWriter.Write(',');
}
if (PrettyPrint && !context.ExpectingValue) {
TextWriter.Write(Environment.NewLine);
}
}
private void PutString(string str) {
Put(string.Empty);
TextWriter.Write('"');
int n = str.Length;
for (int i = 0; i < n; i++) {
switch (str[i]) {
case '\n':
TextWriter.Write("\\n");
continue;
case '\r':
TextWriter.Write("\\r");
continue;
case '\t':
TextWriter.Write("\\t");
continue;
case '"':
case '\\':
TextWriter.Write('\\');
TextWriter.Write(str[i]);
continue;
case '\f':
TextWriter.Write("\\f");
continue;
case '\b':
TextWriter.Write("\\b");
continue;
}
if ((int)str[i] >= 32 && (int)str[i] <= 126) {
TextWriter.Write(str[i]);
continue;
}
// Default, turn into a \uXXXX sequence
IntToHex ((int)str[i], hexSeq);
TextWriter.Write("\\u");
TextWriter.Write(hexSeq);
}
TextWriter.Write('"');
}
private void Unindent() {
if (PrettyPrint) {
indentation -= indentValue;
}
}
public override string ToString() {
if (stringBuilder == null) {
return string.Empty;
}
return stringBuilder.ToString();
}
public void Reset() {
hasReachedEnd = false;
ctxStack.Clear();
context = new WriterContext();
ctxStack.Push(context);
if (stringBuilder != null) {
stringBuilder.Remove(0, stringBuilder.Length);
}
}
public void Write(bool boolean) {
DoValidation(Condition.Value);
PutNewline();
Put(boolean ? "true" : "false");
context.ExpectingValue = false;
}
public void Write(double number) {
DoValidation(Condition.Value);
PutNewline();
string str = number.ToString("R", numberFormat);
Put(str);
if (str.IndexOf('.') == -1 && str.IndexOf('E') == -1) {
TextWriter.Write(".0");
}
context.ExpectingValue = false;
}
public void Write(decimal number) {
DoValidation(Condition.Value);
PutNewline();
Put(Convert.ToString(number, numberFormat));
context.ExpectingValue = false;
}
public void Write(long number) {
DoValidation(Condition.Value);
PutNewline();
Put(Convert.ToString(number, numberFormat));
context.ExpectingValue = false;
}
public void Write(ulong number) {
DoValidation(Condition.Value);
PutNewline();
Put(Convert.ToString(number, numberFormat));
context.ExpectingValue = false;
}
public void Write(string str) {
DoValidation(Condition.Value);
PutNewline();
if (str == null) {
Put("null");
} else {
PutString(str);
}
context.ExpectingValue = false;
}
public void WriteArrayEnd() {
DoValidation(Condition.InArray);
PutNewline(false);
ctxStack.Pop();
if (ctxStack.Count == 1) {
hasReachedEnd = true;
} else {
context = ctxStack.Peek();
context.ExpectingValue = false;
}
Unindent();
Put("]");
}
public void WriteArrayStart() {
DoValidation(Condition.NotAProperty);
PutNewline();
Put("[");
context = new WriterContext ();
context.InArray = true;
ctxStack.Push (context);
Indent();
}
public void WriteObjectEnd() {
DoValidation(Condition.InObject);
PutNewline(false);
ctxStack.Pop();
if (ctxStack.Count == 1) {
hasReachedEnd = true;
} else {
context = ctxStack.Peek();
context.ExpectingValue = false;
}
Unindent();
Put("}");
}
public void WriteObjectStart() {
DoValidation(Condition.NotAProperty);
PutNewline();
Put("{");
context = new WriterContext();
context.InObject = true;
ctxStack.Push(context);
Indent();
}
public void WritePropertyName(string name) {
DoValidation(Condition.Property);
PutNewline();
PutString(name);
if (PrettyPrint) {
if (name.Length > context.Padding) {
context.Padding = name.Length;
}
for (int i = context.Padding - name.Length; i >= 0; i--) {
TextWriter.Write(' ');
}
TextWriter.Write(": ");
} else {
TextWriter.Write(':');
}
context.ExpectingValue = true;
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.IO;
using System.Reflection;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Management.Automation;
using System.Management.Automation.Provider;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.WSMan.Management
{
/// <summary>
/// Executes action on a target object specified by RESOURCE_URI, where
/// parameters are specified by key value pairs.
/// eg., Call StartService method on the spooler service
/// Invoke-WSManAction -Action StartService -ResourceURI wmicimv2/Win32_Service
/// -SelectorSet {Name=Spooler}
/// </summary>
[Cmdlet(VerbsLifecycle.Invoke, "WSManAction", DefaultParameterSetName = "URI", HelpUri = "http://go.microsoft.com/fwlink/?LinkId=141446")]
public class InvokeWSManActionCommand : AuthenticatingWSManCommand, IDisposable
{
/// <summary>
/// The following is the definition of the input parameter "Action".
/// Indicates the method which needs to be executed on the management object
/// specified by the ResourceURI and selectors
/// </summary>
[Parameter(Mandatory = true,
Position = 1)]
[ValidateNotNullOrEmpty]
public String Action
{
get { return action; }
set { action = value; }
}
private String action;
/// <summary>
/// The following is the definition of the input parameter "ApplicationName".
/// ApplicationName identifies the remote endpoint.
/// </summary>
[Parameter(ParameterSetName = "ComputerName")]
[ValidateNotNullOrEmpty]
public String ApplicationName
{
get { return applicationname; }
set { applicationname = value; }
}
private String applicationname = null;
/// <summary>
/// The following is the definition of the input parameter "ComputerName".
/// Executes the management operation on the specified computer(s). The default
/// is the local computer. Type the fully qualified domain name, NETBIOS name or
/// IP address to indicate the remote host(s)
/// </summary>
[Parameter(ParameterSetName = "ComputerName")]
[Alias("cn")]
public String ComputerName
{
get { return computername; }
set
{
computername = value;
if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.CurrentCultureIgnoreCase)))
{
computername = "localhost";
}
}
}
private String computername = null;
/// <summary>
/// The following is the definition of the input parameter "ConnectionURI".
/// Specifies the transport, server, port, and ApplicationName of the new
/// runspace. The format of this string is:
/// transport://server:port/ApplicationName.
/// </summary>
[Parameter(ParameterSetName = "URI")]
[ValidateNotNullOrEmpty]
[Alias("CURI", "CU")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")]
public Uri ConnectionURI
{
get { return connectionuri; }
set { connectionuri = value; }
}
private Uri connectionuri;
/// <summary>
/// The following is the definition of the input parameter "FilePath".
/// Updates the management resource specified by the ResourceURI and SelectorSet
/// via this input file
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public String FilePath
{
get { return filepath; }
set { filepath = value; }
}
private String filepath;
/// <summary>
/// The following is the definition of the input parameter "OptionSet".
/// OptionSet is a hashtable and is used to pass a set of switches to the
/// service to modify or refine the nature of the request.
/// </summary>
[Parameter(ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
[Alias("os")]
public Hashtable OptionSet
{
get { return optionset; }
set { optionset = value; }
}
private Hashtable optionset;
/// <summary>
/// The following is the definition of the input parameter "Port".
/// Specifies the port to be used when connecting to the ws management service.
/// </summary>
[Parameter(ParameterSetName = "ComputerName")]
[ValidateNotNullOrEmpty]
[ValidateRange(1, Int32.MaxValue)]
public Int32 Port
{
get { return port; }
set { port = value; }
}
private Int32 port = 0;
/// <summary>
/// The following is the definition of the input parameter "SelectorSet".
/// SelectorSet is a hash table which helps in identify an instance of the
/// management resource if there are are more than 1 instance of the resource
/// class
/// </summary>
[Parameter(Position = 2,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public Hashtable SelectorSet
{
get { return selectorset; }
set { selectorset = value; }
}
private Hashtable selectorset;
/// <summary>
/// The following is the definition of the input parameter "SessionOption".
/// Defines a set of extended options for the WSMan session. This hashtable can
/// be created using New-WSManSessionOption
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
[Alias("so")]
public SessionOption SessionOption
{
get { return sessionoption; }
set { sessionoption = value; }
}
private SessionOption sessionoption;
/// <summary>
/// The following is the definition of the input parameter "UseSSL".
/// Uses the Secure Sockets Layer (SSL) protocol to establish a connnection to
/// the remote computer. If SSL is not available on the port specified by the
/// Port parameter, the command fails.
/// </summary>
[Parameter(ParameterSetName = "ComputerName")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")]
public SwitchParameter UseSSL
{
get { return usessl; }
set { usessl = value; }
}
private SwitchParameter usessl;
/// <summary>
/// The following is the definition of the input parameter "ValueSet".
/// ValueSet is a hahs table which helps to modify resource represented by the
/// ResourceURI and SelectorSet.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public Hashtable ValueSet
{
get { return valueset; }
set { valueset = value; }
}
private Hashtable valueset;
/// <summary>
/// The following is the definition of the input parameter "ResourceURI".
/// URI of the resource class/instance representation
/// </summary>
[Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[Alias("ruri")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")]
public Uri ResourceURI
{
get { return resourceuri; }
set { resourceuri = value; }
}
private Uri resourceuri;
private WSManHelper helper;
IWSManEx m_wsmanObject = (IWSManEx)new WSManClass();
IWSManSession m_session = null;
string connectionStr = string.Empty;
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
helper = new WSManHelper(this);
helper.WSManOp = "invoke";
//create the connection string
connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname);
}
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
try
{
//create the resourcelocator object
IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, null, null, m_wsmanObject, resourceuri);
//create the session object
m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent);
string rootNode = helper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, action);
string input = helper.ProcessInput(m_wsmanObject, filepath, helper.WSManOp, rootNode, valueset, m_resource, m_session);
string resultXml = m_session.Invoke(action, m_resource, input, 0);
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(resultXml);
WriteObject(xmldoc.DocumentElement);
}
finally
{
if (!String.IsNullOrEmpty(m_wsmanObject.Error))
{
helper.AssertError(m_wsmanObject.Error, true, resourceuri);
}
if (!String.IsNullOrEmpty(m_session.Error))
{
helper.AssertError(m_session.Error, true, resourceuri);
}
if (m_session != null)
Dispose(m_session);
}
}//End ProcessRecord()
#region IDisposable Members
/// <summary>
/// public dispose method
/// </summary>
public
void
Dispose()
{
//CleanUp();
GC.SuppressFinalize(this);
}
/// <summary>
/// public dispose method
/// </summary>
public
void
Dispose(IWSManSession sessionObject)
{
sessionObject = null;
this.Dispose();
}
#endregion IDisposable Members
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void EndProcessing()
{
// WSManHelper helper = new WSManHelper();
helper.CleanUp();
}
}//End Class
}
| |
//#define Trace
// BZip2OutputStream.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2011 Dino Chiesa.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// Last Saved: <2011-August-02 16:44:11>
//
// ------------------------------------------------------------------
//
// This module defines the BZip2OutputStream class, which is a
// compressing stream that handles BZIP2. This code may have been
// derived in part from Apache commons source code. The license below
// applies to the original Apache code.
//
// ------------------------------------------------------------------
// flymake: csc.exe /t:module BZip2InputStream.cs BZip2Compressor.cs Rand.cs BCRC32.cs @@FILE@@
/*
* 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.
*/
// Design Notes:
//
// This class follows the classic Decorator pattern: it is a Stream that
// wraps itself around a Stream, and in doing so provides bzip2
// compression as callers Write into it.
//
// BZip2 is a straightforward data format: there are 4 magic bytes at
// the top of the file, followed by 1 or more compressed blocks. There
// is a small "magic byte" trailer after all compressed blocks. This
// class emits the magic bytes for the header and trailer, and relies on
// a BZip2Compressor to generate each of the compressed data blocks.
//
// BZip2 does byte-shredding - it uses partial fractions of bytes to
// represent independent pieces of information. This class relies on the
// BitWriter to adapt the bit-oriented BZip2 output to the byte-oriented
// model of the .NET Stream class.
//
// ----
//
// Regarding the Apache code base: Most of the code in this particular
// class is related to stream operations, and is my own code. It largely
// does not rely on any code obtained from Apache commons. If you
// compare this code with the Apache commons BZip2OutputStream, you will
// see very little code that is common, except for the
// nearly-boilerplate structure that is common to all subtypes of
// System.IO.Stream. There may be some small remnants of code in this
// module derived from the Apache stuff, which is why I left the license
// in here. Most of the Apache commons compressor magic has been ported
// into the BZip2Compressor class.
//
using System;
using System.IO;
namespace Ionic.BZip2
{
/// <summary>
/// A write-only decorator stream that compresses data as it is
/// written using the BZip2 algorithm.
/// </summary>
public class BZip2OutputStream : System.IO.Stream
{
int totalBytesWrittenIn;
bool leaveOpen;
BZip2Compressor compressor;
uint combinedCRC;
Stream output;
BitWriter bw;
int blockSize100k; // 0...9
private TraceBits desiredTrace = TraceBits.Crc | TraceBits.Write;
/// <summary>
/// Constructs a new <c>BZip2OutputStream</c>, that sends its
/// compressed output to the given output stream.
/// </summary>
///
/// <param name='output'>
/// The destination stream, to which compressed output will be sent.
/// </param>
///
/// <example>
///
/// This example reads a file, then compresses it with bzip2 file,
/// and writes the compressed data into a newly created file.
///
/// <code>
/// var fname = "logfile.log";
/// using (var fs = File.OpenRead(fname))
/// {
/// var outFname = fname + ".bz2";
/// using (var output = File.Create(outFname))
/// {
/// using (var compressor = new Ionic.BZip2.BZip2OutputStream(output))
/// {
/// byte[] buffer = new byte[2048];
/// int n;
/// while ((n = fs.Read(buffer, 0, buffer.Length)) > 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// </example>
public BZip2OutputStream(Stream output)
: this(output, BZip2.MaxBlockSize, false)
{
}
/// <summary>
/// Constructs a new <c>BZip2OutputStream</c> with specified blocksize.
/// </summary>
/// <param name = "output">the destination stream.</param>
/// <param name = "blockSize">
/// The blockSize in units of 100000 bytes.
/// The valid range is 1..9.
/// </param>
public BZip2OutputStream(Stream output, int blockSize)
: this(output, blockSize, false)
{
}
/// <summary>
/// Constructs a new <c>BZip2OutputStream</c>.
/// </summary>
/// <param name = "output">the destination stream.</param>
/// <param name = "leaveOpen">
/// whether to leave the captive stream open upon closing this stream.
/// </param>
public BZip2OutputStream(Stream output, bool leaveOpen)
: this(output, BZip2.MaxBlockSize, leaveOpen)
{
}
/// <summary>
/// Constructs a new <c>BZip2OutputStream</c> with specified blocksize,
/// and explicitly specifies whether to leave the wrapped stream open.
/// </summary>
///
/// <param name = "output">the destination stream.</param>
/// <param name = "blockSize">
/// The blockSize in units of 100000 bytes.
/// The valid range is 1..9.
/// </param>
/// <param name = "leaveOpen">
/// whether to leave the captive stream open upon closing this stream.
/// </param>
public BZip2OutputStream(Stream output, int blockSize, bool leaveOpen)
{
if (blockSize < BZip2.MinBlockSize ||
blockSize > BZip2.MaxBlockSize)
{
var msg = String.Format("blockSize={0} is out of range; must be between {1} and {2}",
blockSize,
BZip2.MinBlockSize, BZip2.MaxBlockSize);
throw new ArgumentException(msg, "blockSize");
}
this.output = output;
if (!this.output.CanWrite)
throw new ArgumentException("The stream is not writable.", "output");
this.bw = new BitWriter(this.output);
this.blockSize100k = blockSize;
this.compressor = new BZip2Compressor(this.bw, blockSize);
this.leaveOpen = leaveOpen;
this.combinedCRC = 0;
EmitHeader();
}
/// <summary>
/// Close the stream.
/// </summary>
/// <remarks>
/// <para>
/// This may or may not close the underlying stream. Check the
/// constructors that accept a bool value.
/// </para>
/// </remarks>
public override void Close()
{
if (output != null)
{
Stream o = this.output;
Finish();
if (!leaveOpen)
o.Close();
}
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
if (this.output != null)
{
this.bw.Flush();
this.output.Flush();
}
}
private void EmitHeader()
{
var magic = new byte[] {
(byte) 'B',
(byte) 'Z',
(byte) 'h',
(byte) ('0' + this.blockSize100k)
};
// not necessary to shred the initial magic bytes
this.output.Write(magic, 0, magic.Length);
}
private void EmitTrailer()
{
// A magic 48-bit number, 0x177245385090, to indicate the end
// of the last block. (sqrt(pi), if you want to know)
TraceOutput(TraceBits.Write, "total written out: {0} (0x{0:X})",
this.bw.TotalBytesWrittenOut);
// must shred
this.bw.WriteByte(0x17);
this.bw.WriteByte(0x72);
this.bw.WriteByte(0x45);
this.bw.WriteByte(0x38);
this.bw.WriteByte(0x50);
this.bw.WriteByte(0x90);
this.bw.WriteInt(this.combinedCRC);
this.bw.FinishAndPad();
TraceOutput(TraceBits.Write, "final total: {0} (0x{0:X})",
this.bw.TotalBytesWrittenOut);
}
void Finish()
{
// Console.WriteLine("BZip2:Finish");
try
{
var totalBefore = this.bw.TotalBytesWrittenOut;
this.compressor.CompressAndWrite();
TraceOutput(TraceBits.Write,"out block length (bytes): {0} (0x{0:X})",
this.bw.TotalBytesWrittenOut - totalBefore);
TraceOutput(TraceBits.Crc, " combined CRC (before): {0:X8}",
this.combinedCRC);
this.combinedCRC = (this.combinedCRC << 1) | (this.combinedCRC >> 31);
this.combinedCRC ^= (uint) compressor.Crc32;
TraceOutput(TraceBits.Crc, " block CRC : {0:X8}",
this.compressor.Crc32);
TraceOutput(TraceBits.Crc, " combined CRC (final) : {0:X8}",
this.combinedCRC);
EmitTrailer();
}
finally
{
this.output = null;
this.compressor = null;
this.bw = null;
}
}
/// <summary>
/// The blocksize parameter specified at construction time.
/// </summary>
public int BlockSize
{
get { return this.blockSize100k; }
}
/// <summary>
/// Write data to the stream.
/// </summary>
/// <remarks>
///
/// <para>
/// Use the <c>BZip2OutputStream</c> to compress data while writing:
/// create a <c>BZip2OutputStream</c> with a writable output stream.
/// Then call <c>Write()</c> on that <c>BZip2OutputStream</c>, providing
/// uncompressed data as input. The data sent to the output stream will
/// be the compressed form of the input data.
/// </para>
///
/// <para>
/// A <c>BZip2OutputStream</c> can be used only for <c>Write()</c> not for <c>Read()</c>.
/// </para>
///
/// </remarks>
///
/// <param name="buffer">The buffer holding data to write to the stream.</param>
/// <param name="offset">the offset within that data array to find the first byte to write.</param>
/// <param name="count">the number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (offset < 0)
throw new IndexOutOfRangeException(String.Format("offset ({0}) must be > 0", offset));
if (count < 0)
throw new IndexOutOfRangeException(String.Format("count ({0}) must be > 0", count));
if (offset + count > buffer.Length)
throw new IndexOutOfRangeException(String.Format("offset({0}) count({1}) bLength({2})",
offset, count, buffer.Length));
if (this.output == null)
throw new IOException("the stream is not open");
if (count == 0) return; // nothing to do
int bytesWritten = 0;
int bytesRemaining = count;
do
{
int n = compressor.Fill(buffer, offset, bytesRemaining);
if (n != bytesRemaining)
{
// The compressor data block is full. Compress and
// write out the compressed data, then reset the
// compressor and continue.
var totalBefore = this.bw.TotalBytesWrittenOut;
this.compressor.CompressAndWrite();
TraceOutput(TraceBits.Write,"out block length (bytes): {0} (0x{0:X})",
this.bw.TotalBytesWrittenOut - totalBefore);
// and now any remaining bits
TraceOutput(TraceBits.Write,
" remaining: {0} 0x{1:X}",
this.bw.NumRemainingBits,
this.bw.RemainingBits);
TraceOutput(TraceBits.Crc, " combined CRC (before): {0:X8}",
this.combinedCRC);
this.combinedCRC = (this.combinedCRC << 1) | (this.combinedCRC >> 31);
this.combinedCRC ^= (uint) compressor.Crc32;
TraceOutput(TraceBits.Crc, " block CRC : {0:X8}",
compressor.Crc32);
TraceOutput(TraceBits.Crc, " combined CRC (after) : {0:X8}",
this.combinedCRC);
offset += n;
}
bytesRemaining -= n;
bytesWritten += n;
} while (bytesRemaining > 0);
totalBytesWrittenIn += bytesWritten;
}
/// <summary>
/// Indicates whether the stream can be read.
/// </summary>
/// <remarks>
/// The return value is always false.
/// </remarks>
public override bool CanRead
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream supports Seek operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream can be written.
/// </summary>
/// <remarks>
/// The return value should always be true, unless and until the
/// object is disposed and closed.
/// </remarks>
public override bool CanWrite
{
get
{
if (this.output == null) throw new ObjectDisposedException("BZip2Stream");
return this.output.CanWrite;
}
}
/// <summary>
/// Reading this property always throws a <see cref="NotImplementedException"/>.
/// </summary>
public override long Length
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// The position of the stream pointer.
/// </summary>
///
/// <remarks>
/// Setting this property always throws a <see
/// cref="NotImplementedException"/>. Reading will return the
/// total number of uncompressed bytes written through.
/// </remarks>
public override long Position
{
get
{
return this.totalBytesWrittenIn;
}
set { throw new NotImplementedException(); }
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="offset">this is irrelevant, since it will always throw!</param>
/// <param name="origin">this is irrelevant, since it will always throw!</param>
/// <returns>irrelevant!</returns>
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotImplementedException();
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="value">this is irrelevant, since it will always throw!</param>
public override void SetLength(long value)
{
throw new NotImplementedException();
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name='buffer'>this parameter is never used</param>
/// <param name='offset'>this parameter is never used</param>
/// <param name='count'>this parameter is never used</param>
/// <returns>never returns anything; always throws</returns>
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
// used only when Trace is defined
[Flags]
enum TraceBits : uint
{
None = 0,
Crc = 1,
Write = 2,
All = 0xffffffff,
}
[System.Diagnostics.ConditionalAttribute("Trace")]
private void TraceOutput(TraceBits bits, string format, params object[] varParams)
{
if ((bits & this.desiredTrace) != 0)
{
//lock(outputLock)
{
int tid = System.Threading.Thread.CurrentThread.GetHashCode();
#if !SILVERLIGHT && !NETCF
Console.ForegroundColor = (ConsoleColor) (tid % 8 + 10);
#endif
Console.Write("{0:000} PBOS ", tid);
Console.WriteLine(format, varParams);
#if !SILVERLIGHT && !NETCF
Console.ResetColor();
#endif
}
}
}
}
}
| |
// -------------------------------------
// Domain : Avariceonline.com
// Author : Nicholas Ventimiglia
// Product : Unity3d Foundation
// Published : 2015
// -------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
#if UNITY_WSA && !UNITY_EDITOR
using System.Threading.Tasks;
#endif
namespace Foundation
{
/// <summary>
/// The Injector is a static application service for resolving dependencies by asking for a components type or interface
/// </summary>
public class Injector
{
#region container
/// <summary>
/// represents a injection subscriber
/// </summary>
protected class InjectSubscription
{
/// <summary>
/// ValueType of the export
/// </summary>
public readonly Type MemberType;
/// <summary>
/// Optional lookup key
/// </summary>
public string InjectKey { get; private set; }
/// <summary>
/// Is there an optional lookup key ?
/// </summary>
public bool HasKey
{
get
{
return !string.IsNullOrEmpty(InjectKey);
}
}
/// <summary>
/// Importing Member
/// </summary>
public readonly MemberInfo Member;
/// <summary>
/// Importing instance
/// </summary>
/// <remarks>
/// Handler target
/// </remarks>
public readonly object Instance;
public InjectSubscription(Type mtype, object instance, MemberInfo member)
{
MemberType = mtype;
Member = member;
Instance = instance;
}
public InjectSubscription(Type mtype, object instance, MemberInfo member, string key)
{
MemberType = mtype;
Member = member;
Instance = instance;
InjectKey = key;
}
}
/// <summary>
/// represents a injection export
/// </summary>
protected class InjectExport
{
/// <summary>
/// ValueType of the export
/// </summary>
public readonly Type MemberType;
/// <summary>
/// Importing instance
/// </summary>
/// <remarks>
/// Handler target
/// </remarks>
public readonly object Instance;
/// <summary>
/// Optional lookup key
/// </summary>
public string InjectKey { get; private set; }
/// <summary>
/// Is there an optional lookup key ?
/// </summary>
public bool HasKey
{
get
{
return !string.IsNullOrEmpty(InjectKey);
}
}
public InjectExport(Type mtype, object instance)
{
MemberType = mtype;
Instance = instance;
}
public InjectExport(Type mtype, object instance, string key)
{
MemberType = mtype;
Instance = instance;
InjectKey = key;
}
}
/// <summary>
/// delegates
/// </summary>
static readonly List<InjectSubscription> Subscriptions = new List<InjectSubscription>();
/// <summary>
/// delegates
/// </summary>
static readonly List<InjectExport> Exports = new List<InjectExport>();
/// <summary>
/// determines if the subscription should be invoked
/// </summary>
/// <returns></returns>
static IEnumerable<InjectExport> GetExports(Type memberType, string key)
{
if (!string.IsNullOrEmpty(key))
{
return Exports.Where(o => (o.HasKey && o.InjectKey == key));
}
return
Exports.Where(o =>
// is message type
memberType == o.MemberType
// or handler is an interface of message
#if UNITY_WSA && !UNITY_EDITOR
|| (memberType.GetTypeInfo().IsAssignableFrom(o.MemberType.GetTypeInfo())));
#else
|| (memberType.IsAssignableFrom(o.MemberType)));
#endif
}
/// <summary>
/// determines if the subscription should be invoked
/// </summary>
/// <returns></returns>
static IEnumerable<InjectSubscription> GetSubscriptionsFor(InjectExport export)
{
if (export.HasKey)
{
return Subscriptions.Where(o => (o.HasKey && o.InjectKey == export.InjectKey));
}
#if UNITY_WSA && !UNITY_EDITOR
return
Subscriptions.Where(o =>
// is message type
o.MemberType == export.MemberType
// or handler is an interface of message
|| (o.MemberType.GetTypeInfo().IsAssignableFrom(export.MemberType.GetTypeInfo()))
// support for GetAll
// ReSharper disable once PossibleNullReferenceException
|| (o.MemberType.IsArray && o.MemberType.GetElementType().GetTypeInfo().IsAssignableFrom(export.MemberType.GetTypeInfo()))
|| (o.MemberType.GetTypeInfo().IsGenericType && o.MemberType.GetTypeInfo().GenericTypeArguments.First().GetTypeInfo().IsAssignableFrom(export.MemberType.GetTypeInfo())));
#else
return
Subscriptions.Where(o =>
// is message type
o.MemberType == export.MemberType
// or handler is an interface of message
|| (o.MemberType.IsAssignableFrom(export.MemberType))
// support for GetAll
// ReSharper disable once PossibleNullReferenceException
|| (o.MemberType.IsArray && o.MemberType.GetElementType().IsAssignableFrom(export.MemberType))
|| (o.MemberType.IsGenericType && o.MemberType.GetGenericArguments().First().IsAssignableFrom(export.MemberType)));
#endif
}
#endregion
#region ctor
static Injector()
{
InjectorInitialized.LoadServices();
}
/// <summary>
/// Initializes the injector.
/// </summary>
public static void ConfirmInit()
{
}
#endregion
#region exporting
/// <summary>
/// Adds the instance to the export container.
/// Will publish to pending imports
/// </summary>
/// <param name="instance">The instance to add</param>
public static void AddExport(object instance)
{
// add as self
var type = instance.GetType();
#if UNITY_WSA && !UNITY_EDITOR
if (type.IsGenericParameter || type.IsArray)
#else
if (type.IsGenericType || type.IsArray)
#endif
{
Debug.LogError("Generics and Arrays are not valid exports. Export individually or a container.");
return;
}
if (Exports.Any(o => o.Instance == instance))
Debug.LogWarning("Export is being added multiple times ! " + instance.GetType());
var key = type.GetAttribute<ExportAttribute>();
// add to container
var e = new InjectExport(type, instance, key == null ? null : key.InjectKey);
Exports.Add(e);
// notify imports
foreach (var sub in GetSubscriptionsFor(e))
{
Import(sub.Instance, sub.Member, sub.InjectKey);
}
}
/// <summary>
/// Removes the instance to the container.
/// Will publish changes to imports
/// </summary>
/// <param name="instance">The instance to remove</param>
public static void RemoveExport(object instance)
{
// get exports
var es = Exports.Where(o => o.Instance == instance).ToArray();
//remove
Exports.RemoveAll(o => o.Instance == instance);
// clean up publish
for (int index = 0;index < es.Length;index++)
{
var export = es[index];
// notify imports
foreach (var sub in GetSubscriptionsFor(export))
{
Clear(sub.Instance, sub.Member);
}
}
}
#endregion
#region importing
/// <summary>
/// Will import to member fields/properties with Import Attribute
/// </summary>
/// <param name="instance"></param>
public static void Import(object instance)
{
#if UNITY_WSA && !UNITY_EDITOR
var fields = instance.GetType().GetTypeInfo().DeclaredFields.Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
var props = instance.GetType().GetTypeInfo().DeclaredProperties.Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
#else
var fields = instance.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public).Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
var props = instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
#endif
for (int i = 0;i < fields.Length;i++)
{
Import(instance, fields[i], fields[i].GetAttribute<ImportAttribute>().InjectKey);
}
for (int i = 0;i < props.Length;i++)
{
Import(instance, props[i], props[i].GetAttribute<ImportAttribute>().InjectKey);
}
}
/// <summary>
/// Will inject instance into member
/// </summary>
static void Import(object instance, MemberInfo member, string key)
{
// get member type
var memberType = member.GetMemberType();
if (memberType.IsArray)
{
// get array type
var type = memberType.GetElementType();
// ReSharper disable once AssignNullToNotNullAttribute
var arg = GetExports(type, key).Select(o => ConvertTo(o.Instance, type)).ToArray();
// ReSharper disable once AssignNullToNotNullAttribute
var a = Array.CreateInstance(type, arg.Length);
Array.Copy(arg, a, arg.Length);
member.SetMemberValue(instance, a);
}
#if UNITY_WSA && !UNITY_EDITOR
else if (memberType.GetTypeInfo().IsGenericType)
#else
else if (memberType.IsGenericType)
#endif
{
#if UNITY_WSA && !UNITY_EDITOR
var type = memberType.GetTypeInfo().GenericTypeArguments.First();
#else
var type = memberType.GetGenericArguments().First();
#endif
//get enumerable generic type
#if UNITY_WSA && !UNITY_EDITOR
if (memberType.GetTypeInfo().IsInterface)
#else
if (memberType.IsInterface)
#endif
{
var arg = GetExports(type, key).Select(o => ConvertTo(o.Instance, type)).ToArray();
var a = Array.CreateInstance(type, arg.Length);
Array.Copy(arg, a, arg.Length);
member.SetMemberValue(instance, a);
}
else
{
Debug.LogError("Injecting into non-Array / non-IEnumerable not supported.");
}
}
else
{
var arg = GetExports(memberType, key).FirstOrDefault();
if (arg != null)
member.SetMemberValue(instance, arg.Instance);
}
}
static object ConvertTo(object instance, Type type)
{
#if UNITY_WSA && !UNITY_EDITOR
if (type.GetTypeInfo().IsInterface)
#else
if (type.IsInterface)
#endif
{
return instance;
}
// ReSharper disable once AssignNullToNotNullAttribute
return Convert.ChangeType(instance, type);
}
/// <summary>
/// Will set value to null
/// </summary>
public static void Clear(object instance, MemberInfo member)
{
member.SetMemberValue(instance, null);
}
#endregion
#region Resolving
/// <summary>
/// Returns true if the container contains any T
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static bool HasExport<T>()
{
var t = typeof(T);
return HasExport(t);
}
/// <summary>
/// Returns true if the container contains any T
/// </summary>
/// <returns></returns>
public static bool HasExport(Type t)
{
#if UNITY_WSA && !UNITY_EDITOR
return Exports.Any(o => o.MemberType == t || (o.MemberType.GetTypeInfo().IsAssignableFrom(t.GetTypeInfo())));
#else
return Exports.Any(o => o.MemberType == t || (t.IsAssignableFrom(o.MemberType)));
#endif
}
/// <summary>
/// returns the first instance of T
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T GetFirst<T>()
{
return (T)GetFirst(typeof(T));
}
/// <summary>
/// returns the first instance of T
/// </summary>
/// <returns></returns>
public static object GetFirst(Type t)
{
var es = GetExports(t, null).ToArray();
if (es.Count() > 1)
{
Debug.LogWarning("Multiple exports of type : " + t);
}
if (!es.Any())
{
return null;
}
return es.First().Instance;
}
/// <summary>
/// Returns all instances of T
/// </summary>
/// <returns></returns>
public static IEnumerable<T> GetAll<T>()
{
return GetAll(typeof(T)).Cast<T>();
}
/// <summary>
/// Returns all instances of T
/// </summary>
/// <returns></returns>
public static IEnumerable<object> GetAll(Type t)
{
return GetExports(t, null).Select(o => o.Instance).ToArray();
}
/// <summary>
/// Returns true if the container contains any T
/// </summary>
/// <returns></returns>
public static bool HasExport(string key)
{
return Exports.Any(o => o.HasKey && o.InjectKey == key);
}
/// <summary>
/// returns the first instance of T
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T GetFirst<T>(string key)
{
return (T)GetFirst(key);
}
/// <summary>
/// returns the first instance of T
/// </summary>
/// <returns></returns>
public static object GetFirst(string key)
{
var es = Exports.Where(o => o.HasKey && o.InjectKey == key).ToArray();
if (es.Count() > 1)
{
Debug.LogWarning("Multiple exports of key : " + key);
}
if (!es.Any())
{
return null;
}
return es.First().Instance;
}
/// <summary>
/// Returns all instances of T
/// </summary>
/// <returns></returns>
public static IEnumerable<T> GetAll<T>(string key)
{
return GetAll(typeof(T)).Cast<T>();
}
/// <summary>
/// Returns all instances of T
/// </summary>
/// <returns></returns>
public static IEnumerable<object> GetAll(string key)
{
return Exports.Where(o => o.HasKey && o.InjectKey == key).Select(o => o.Instance).ToArray();
}
#endregion
#region subscribing
/// <summary>
/// Will subscribe members for late injection
/// </summary>
/// <param name="instance"></param>
public static void Subscribe(object instance)
{
#if UNITY_WSA && !UNITY_EDITOR
var fields = instance.GetType().GetRuntimeFields().Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
var props = instance.GetType().GetRuntimeProperties().Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
#else
var fields = instance.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public).Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
var props = instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
#endif
for (int i = 0;i < fields.Length;i++)
{
Subscribe(instance, fields[i]);
}
for (int i = 0;i < props.Length;i++)
{
Subscribe(instance, props[i]);
}
}
/// <summary>
/// Will subscribe instance into member
/// </summary>
public static void Subscribe(object instance, MemberInfo member)
{
//Import First
var key = member.GetAttribute<ImportAttribute>();
Import(instance, member, key == null ? null : key.InjectKey);
var a = member.GetCustomAttributes(typeof(ImportAttribute), true).Cast<ImportAttribute>().FirstOrDefault();
// add subscription
Subscriptions.Add(new InjectSubscription(member.GetMemberType(), instance, member, a == null ? null : a.InjectKey));
}
/// <summary>
/// Will unsubscribe from late injection
/// </summary>
/// <param name="instance"></param>
public static void UnSubscribe(object instance)
{
#if UNITY_WSA && !UNITY_EDITOR
var fields = instance.GetType().GetRuntimeFields().Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
var props = instance.GetType().GetRuntimeProperties().Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
#else
var fields = instance.GetType().GetFields().Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
var props = instance.GetType().GetProperties().Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
#endif
for (int i = 0;i < fields.Length;i++)
{
fields[i].SetValue(instance, null);
}
for (int i = 0;i < props.Length;i++)
{
props[i].SetValue(instance, null, null);
}
Subscriptions.RemoveAll(o => o.Instance == instance);
}
/// <summary>
/// Will remove instance member subscription
/// </summary>
public static void UnSubscribe(object instance, MemberInfo member)
{
//Remove Imports First
Clear(instance, member);
//remove
Subscriptions.RemoveAll(o => o.Instance == instance && Equals(o.Member, member));
}
#endregion
}
}
| |
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
namespace Lucene.Net.Codecs.Lucene3x
{
/*
* 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 BytesRef = Lucene.Net.Util.BytesRef;
using GrowableWriter = Lucene.Net.Util.Packed.GrowableWriter;
using MathUtil = Lucene.Net.Util.MathUtil;
using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s;
using PagedBytes = Lucene.Net.Util.PagedBytes;
using PagedBytesDataInput = Lucene.Net.Util.PagedBytes.PagedBytesDataInput;
using PagedBytesDataOutput = Lucene.Net.Util.PagedBytes.PagedBytesDataOutput;
using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator;
using Term = Lucene.Net.Index.Term;
/// <summary>
/// This stores a monotonically increasing set of <c>Term, TermInfo</c> pairs in an
/// index segment. Pairs are accessed either by <see cref="Term"/> or by ordinal position the
/// set. The <see cref="Index.Terms"/> and <see cref="TermInfo"/> are actually serialized and stored into a byte
/// array and pointers to the position of each are stored in a <see cref="int"/> array. </summary>
[Obsolete("Only for reading existing 3.x indexes")]
internal class TermInfosReaderIndex
{
private const int MAX_PAGE_BITS = 18; // 256 KB block
private Term[] fields;
private int totalIndexInterval;
private IComparer<BytesRef> comparer = BytesRef.UTF8SortedAsUTF16Comparer;
private readonly PagedBytesDataInput dataInput;
private readonly PackedInt32s.Reader indexToDataOffset;
private readonly int indexSize;
private readonly int skipInterval;
private readonly long ramBytesUsed;
/// <summary>
/// Loads the segment information at segment load time.
/// </summary>
/// <param name="indexEnum">
/// The term enum. </param>
/// <param name="indexDivisor">
/// The index divisor. </param>
/// <param name="tiiFileLength">
/// The size of the tii file, used to approximate the size of the
/// buffer. </param>
/// <param name="totalIndexInterval">
/// The total index interval. </param>
public TermInfosReaderIndex(SegmentTermEnum indexEnum, int indexDivisor, long tiiFileLength, int totalIndexInterval)
{
this.totalIndexInterval = totalIndexInterval;
indexSize = 1 + ((int)indexEnum.size - 1) / indexDivisor;
skipInterval = indexEnum.skipInterval;
// this is only an inital size, it will be GCed once the build is complete
long initialSize = (long)(tiiFileLength * 1.5) / indexDivisor;
PagedBytes dataPagedBytes = new PagedBytes(EstimatePageBits(initialSize));
PagedBytesDataOutput dataOutput = dataPagedBytes.GetDataOutput();
int bitEstimate = 1 + MathUtil.Log(tiiFileLength, 2);
GrowableWriter indexToTerms = new GrowableWriter(bitEstimate, indexSize, PackedInt32s.DEFAULT);
string currentField = null;
IList<string> fieldStrs = new List<string>();
int fieldCounter = -1;
for (int i = 0; indexEnum.Next(); i++)
{
Term term = indexEnum.Term();
if (currentField == null || !currentField.Equals(term.Field, StringComparison.Ordinal))
{
currentField = term.Field;
fieldStrs.Add(currentField);
fieldCounter++;
}
TermInfo termInfo = indexEnum.TermInfo();
indexToTerms.Set(i, dataOutput.GetPosition());
dataOutput.WriteVInt32(fieldCounter);
dataOutput.WriteString(term.Text());
dataOutput.WriteVInt32(termInfo.DocFreq);
if (termInfo.DocFreq >= skipInterval)
{
dataOutput.WriteVInt32(termInfo.SkipOffset);
}
dataOutput.WriteVInt64(termInfo.FreqPointer);
dataOutput.WriteVInt64(termInfo.ProxPointer);
dataOutput.WriteVInt64(indexEnum.indexPointer);
for (int j = 1; j < indexDivisor; j++)
{
if (!indexEnum.Next())
{
break;
}
}
}
fields = new Term[fieldStrs.Count];
for (int i = 0; i < fields.Length; i++)
{
fields[i] = new Term(fieldStrs[i]);
}
dataPagedBytes.Freeze(true);
dataInput = dataPagedBytes.GetDataInput();
indexToDataOffset = indexToTerms.Mutable;
ramBytesUsed = fields.Length * (RamUsageEstimator.NUM_BYTES_OBJECT_REF + RamUsageEstimator.ShallowSizeOfInstance(typeof(Term))) + dataPagedBytes.RamBytesUsed() + indexToDataOffset.RamBytesUsed();
}
private static int EstimatePageBits(long estSize)
{
return Math.Max(Math.Min(64 - Number.NumberOfLeadingZeros(estSize), MAX_PAGE_BITS), 4);
}
internal virtual void SeekEnum(SegmentTermEnum enumerator, int indexOffset)
{
PagedBytesDataInput input = (PagedBytesDataInput)dataInput.Clone();
input.SetPosition(indexToDataOffset.Get(indexOffset));
// read the term
int fieldId = input.ReadVInt32();
Term field = fields[fieldId];
Term term = new Term(field.Field, input.ReadString());
// read the terminfo
var termInfo = new TermInfo();
termInfo.DocFreq = input.ReadVInt32();
if (termInfo.DocFreq >= skipInterval)
{
termInfo.SkipOffset = input.ReadVInt32();
}
else
{
termInfo.SkipOffset = 0;
}
termInfo.FreqPointer = input.ReadVInt64();
termInfo.ProxPointer = input.ReadVInt64();
long pointer = input.ReadVInt64();
// perform the seek
enumerator.Seek(pointer, ((long)indexOffset * totalIndexInterval) - 1, term, termInfo);
}
/// <summary>
/// Binary search for the given term.
/// </summary>
/// <param name="term">
/// The term to locate. </param>
/// <exception cref="System.IO.IOException"> If there is a low-level I/O error. </exception>
internal virtual int GetIndexOffset(Term term)
{
int lo = 0;
int hi = indexSize - 1;
PagedBytesDataInput input = (PagedBytesDataInput)dataInput.Clone();
BytesRef scratch = new BytesRef();
while (hi >= lo)
{
int mid = (int)((uint)(lo + hi) >> 1);
int delta = CompareTo(term, mid, input, scratch);
if (delta < 0)
{
hi = mid - 1;
}
else if (delta > 0)
{
lo = mid + 1;
}
else
{
return mid;
}
}
return hi;
}
/// <summary>
/// Gets the term at the given position. For testing.
/// </summary>
/// <param name="termIndex">
/// The position to read the term from the index. </param>
/// <returns> The term. </returns>
/// <exception cref="System.IO.IOException"> If there is a low-level I/O error. </exception>
internal virtual Term GetTerm(int termIndex)
{
PagedBytesDataInput input = (PagedBytesDataInput)dataInput.Clone();
input.SetPosition(indexToDataOffset.Get(termIndex));
// read the term
int fieldId = input.ReadVInt32();
Term field = fields[fieldId];
return new Term(field.Field, input.ReadString());
}
/// <summary>
/// Returns the number of terms.
/// </summary>
/// <returns> int. </returns>
internal virtual int Length
{
get { return indexSize; }
}
/// <summary>
/// The compares the given term against the term in the index specified by the
/// term index. ie It returns negative N when term is less than index term;
/// </summary>
/// <param name="term">
/// The given term. </param>
/// <param name="termIndex">
/// The index of the of term to compare. </param>
/// <returns> int. </returns>
/// <exception cref="System.IO.IOException"> If there is a low-level I/O error. </exception>
internal virtual int CompareTo(Term term, int termIndex)
{
return CompareTo(term, termIndex, (PagedBytesDataInput)dataInput.Clone(), new BytesRef());
}
/// <summary>
/// Compare the fields of the terms first, and if not equals return from
/// compare. If equal compare terms.
/// </summary>
/// <param name="term">
/// The term to compare. </param>
/// <param name="termIndex">
/// The position of the term in the input to compare </param>
/// <param name="input">
/// The input buffer. </param>
/// <returns> int. </returns>
/// <exception cref="System.IO.IOException"> If there is a low-level I/O error. </exception>
private int CompareTo(Term term, int termIndex, PagedBytesDataInput input, BytesRef reuse)
{
// if term field does not equal mid's field index, then compare fields
// else if they are equal, compare term's string values...
int c = CompareField(term, termIndex, input);
if (c == 0)
{
reuse.Length = input.ReadVInt32();
reuse.Grow(reuse.Length);
input.ReadBytes(reuse.Bytes, 0, reuse.Length);
return comparer.Compare(term.Bytes, reuse);
}
return c;
}
/// <summary>
/// Compares the fields before checking the text of the terms.
/// </summary>
/// <param name="term">
/// The given term. </param>
/// <param name="termIndex">
/// The term that exists in the data block. </param>
/// <param name="input">
/// The data block. </param>
/// <returns> int. </returns>
/// <exception cref="System.IO.IOException"> If there is a low-level I/O error. </exception>
private int CompareField(Term term, int termIndex, PagedBytesDataInput input)
{
input.SetPosition(indexToDataOffset.Get(termIndex));
return term.Field.CompareToOrdinal(fields[input.ReadVInt32()].Field);
}
internal virtual long RamBytesUsed()
{
return ramBytesUsed;
}
}
}
| |
// Copyright (c) Valdis Iljuconoks. All rights reserved.
// Licensed under Apache-2.0. See the LICENSE file in the project root for more information
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DbLocalizationProvider.Abstractions;
using DbLocalizationProvider.Internal;
using DbLocalizationProvider.Logging;
using DbLocalizationProvider.Sync;
using Microsoft.Data.SqlClient;
namespace DbLocalizationProvider.Storage.SqlServer
{
/// <summary>
/// Repository for working with underlying MSSQL storage
/// </summary>
public class ResourceRepository : IResourceRepository
{
private readonly bool _enableInvariantCultureFallback;
private readonly ILogger _logger;
/// <summary>
/// Creates new instance of the class.
/// </summary>
/// <param name="configurationContext">Configuration settings.</param>
public ResourceRepository(ConfigurationContext configurationContext)
{
_enableInvariantCultureFallback = configurationContext.EnableInvariantCultureFallback;
_logger = configurationContext.Logger;
}
/// <summary>
/// Gets all resources.
/// </summary>
/// <returns>List of resources</returns>
public IEnumerable<LocalizationResource> GetAll()
{
try
{
using (var conn = new SqlConnection(Settings.DbContextConnectionString))
{
conn.Open();
var cmd = new SqlCommand(@"
SELECT
r.Id,
r.ResourceKey,
r.Author,
r.FromCode,
r.IsHidden,
r.IsModified,
r.ModificationDate,
r.Notes,
t.Id as TranslationId,
t.Value as Translation,
t.Language,
t.ModificationDate as TranslationModificationDate
FROM [dbo].[LocalizationResources] r
LEFT JOIN [dbo].[LocalizationResourceTranslations] t ON r.Id = t.ResourceId",
conn);
var reader = cmd.ExecuteReader();
var lookup = new Dictionary<string, LocalizationResource>();
void CreateTranslation(SqlDataReader sqlDataReader, LocalizationResource localizationResource)
{
if (!sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("TranslationId")))
{
localizationResource.Translations.Add(new LocalizationResourceTranslation
{
Id =
sqlDataReader.GetInt32(
sqlDataReader.GetOrdinal("TranslationId")),
ResourceId = localizationResource.Id,
Value = sqlDataReader.GetStringSafe("Translation"),
Language =
sqlDataReader.GetStringSafe("Language") ?? string.Empty,
ModificationDate =
reader.GetDateTime(
reader.GetOrdinal("TranslationModificationDate")),
LocalizationResource = localizationResource
});
}
}
while (reader.Read())
{
var key = reader.GetString(reader.GetOrdinal(nameof(LocalizationResource.ResourceKey)));
if (lookup.TryGetValue(key, out var resource))
{
CreateTranslation(reader, resource);
}
else
{
var result = CreateResourceFromSqlReader(key, reader);
CreateTranslation(reader, result);
lookup.Add(key, result);
}
}
return lookup.Values;
}
}
catch (Exception ex)
{
_logger?.Error("Failed to retrieve all resources.", ex);
return Enumerable.Empty<LocalizationResource>();
}
}
/// <summary>
/// Gets resource by the key.
/// </summary>
/// <param name="resourceKey">The resource key.</param>
/// <returns>Localized resource if found by given key</returns>
/// <exception cref="ArgumentNullException">resourceKey</exception>
public LocalizationResource GetByKey(string resourceKey)
{
if (resourceKey == null)
{
throw new ArgumentNullException(nameof(resourceKey));
}
try
{
using (var conn = new SqlConnection(Settings.DbContextConnectionString))
{
conn.Open();
var cmd = new SqlCommand(@"
SELECT
r.Id,
r.Author,
r.FromCode,
r.IsHidden,
r.IsModified,
r.ModificationDate,
r.Notes,
t.Id as TranslationId,
t.Value as Translation,
t.Language,
t.ModificationDate as TranslationModificationDate
FROM [dbo].[LocalizationResources] r
LEFT JOIN [dbo].[LocalizationResourceTranslations] t ON r.Id = t.ResourceId
WHERE ResourceKey = @key",
conn);
cmd.Parameters.AddWithValue("key", resourceKey);
var reader = cmd.ExecuteReader();
if (!reader.Read())
{
return null;
}
var result = CreateResourceFromSqlReader(resourceKey, reader);
// read 1st translation
// if TranslationId is NULL - there is no translations for given resource
if (!reader.IsDBNull(reader.GetOrdinal("TranslationId")))
{
result.Translations.Add(CreateTranslationFromSqlReader(reader, result));
while (reader.Read())
{
result.Translations.Add(CreateTranslationFromSqlReader(reader, result));
}
}
return result;
}
}
catch (Exception ex)
{
_logger?.Error($"Failed to retrieve resource by key {resourceKey}.", ex);
return null;
}
}
private LocalizationResource CreateResourceFromSqlReader(string key, SqlDataReader reader)
{
return new LocalizationResource(key, _enableInvariantCultureFallback)
{
Id = reader.GetInt32(reader.GetOrdinal(nameof(LocalizationResource.Id))),
Author = reader.GetStringSafe(nameof(LocalizationResource.Author)) ?? "unknown",
FromCode = reader.GetBooleanSafe(nameof(LocalizationResource.FromCode)),
IsHidden = reader.GetBooleanSafe(nameof(LocalizationResource.IsHidden)),
IsModified = reader.GetBooleanSafe(nameof(LocalizationResource.IsModified)),
ModificationDate = reader.GetDateTime(reader.GetOrdinal(nameof(LocalizationResource.ModificationDate))),
Notes = reader.GetStringSafe(nameof(LocalizationResource.Notes))
};
}
private LocalizationResourceTranslation CreateTranslationFromSqlReader(SqlDataReader reader, LocalizationResource result)
{
return new LocalizationResourceTranslation
{
Id = reader.GetInt32(reader.GetOrdinal("TranslationId")),
ResourceId = result.Id,
Value = reader.GetStringSafe("Translation"),
Language = reader.GetStringSafe("Language") ?? string.Empty,
ModificationDate = reader.GetDateTime(reader.GetOrdinal("TranslationModificationDate")),
LocalizationResource = result
};
}
/// <summary>
/// Adds the translation for the resource.
/// </summary>
/// <param name="resource">The resource.</param>
/// <param name="translation">The translation.</param>
/// <exception cref="ArgumentNullException">
/// resource
/// or
/// translation
/// </exception>
public void AddTranslation(LocalizationResource resource, LocalizationResourceTranslation translation)
{
if (resource == null)
{
throw new ArgumentNullException(nameof(resource));
}
if (translation == null)
{
throw new ArgumentNullException(nameof(translation));
}
using (var conn = new SqlConnection(Settings.DbContextConnectionString))
{
conn.Open();
var cmd = new SqlCommand(
"INSERT INTO [dbo].[LocalizationResourceTranslations] ([Language], [ResourceId], [Value], [ModificationDate]) VALUES (@language, @resourceId, @translation, @modificationDate)",
conn);
cmd.Parameters.AddWithValue("language", translation.Language);
cmd.Parameters.AddWithValue("resourceId", translation.ResourceId);
cmd.Parameters.AddWithValue("translation", translation.Value);
cmd.Parameters.AddWithValue("modificationDate", translation.ModificationDate);
cmd.ExecuteNonQuery();
}
}
/// <summary>
/// Updates the translation for the resource.
/// </summary>
/// <param name="resource">The resource.</param>
/// <param name="translation">The translation.</param>
/// <exception cref="ArgumentNullException">
/// resource
/// or
/// translation
/// </exception>
public void UpdateTranslation(LocalizationResource resource, LocalizationResourceTranslation translation)
{
if (resource == null)
{
throw new ArgumentNullException(nameof(resource));
}
if (translation == null)
{
throw new ArgumentNullException(nameof(translation));
}
using (var conn = new SqlConnection(Settings.DbContextConnectionString))
{
conn.Open();
var cmd = new SqlCommand(
"UPDATE [dbo].[LocalizationResourceTranslations] SET [Value] = @translation, [ModificationDate] = @modificationDate WHERE [Id] = @id",
conn);
cmd.Parameters.AddWithValue("translation", translation.Value);
cmd.Parameters.AddWithValue("id", translation.Id);
cmd.Parameters.AddWithValue("modificationDate", DateTime.UtcNow);
cmd.ExecuteNonQuery();
}
}
/// <summary>
/// Deletes the translation.
/// </summary>
/// <param name="resource">The resource.</param>
/// <param name="translation">The translation.</param>
/// <exception cref="ArgumentNullException">
/// resource
/// or
/// translation
/// </exception>
public void DeleteTranslation(LocalizationResource resource, LocalizationResourceTranslation translation)
{
if (resource == null)
{
throw new ArgumentNullException(nameof(resource));
}
if (translation == null)
{
throw new ArgumentNullException(nameof(translation));
}
using (var conn = new SqlConnection(Settings.DbContextConnectionString))
{
conn.Open();
var cmd = new SqlCommand("DELETE FROM [dbo].[LocalizationResourceTranslations] WHERE [Id] = @id", conn);
cmd.Parameters.AddWithValue("id", translation.Id);
cmd.ExecuteNonQuery();
}
}
/// <summary>
/// Updates the resource.
/// </summary>
/// <param name="resource">The resource.</param>
/// <exception cref="ArgumentNullException">resource</exception>
public void UpdateResource(LocalizationResource resource)
{
if (resource == null)
{
throw new ArgumentNullException(nameof(resource));
}
using (var conn = new SqlConnection(Settings.DbContextConnectionString))
{
conn.Open();
var cmd = new SqlCommand(
"UPDATE [dbo].[LocalizationResources] SET [IsModified] = @isModified, [ModificationDate] = @modificationDate, [Notes] = @notes WHERE [Id] = @id",
conn);
cmd.Parameters.AddWithValue("id", resource.Id);
cmd.Parameters.AddWithValue("modificationDate", resource.ModificationDate);
cmd.Parameters.AddWithValue("isModified", resource.IsModified);
cmd.Parameters.AddWithValue("notes", (object)resource.Notes ?? DBNull.Value);
cmd.ExecuteNonQuery();
}
}
/// <summary>
/// Deletes the resource.
/// </summary>
/// <param name="resource">The resource.</param>
/// <exception cref="ArgumentNullException">resource</exception>
public void DeleteResource(LocalizationResource resource)
{
if (resource == null)
{
throw new ArgumentNullException(nameof(resource));
}
using (var conn = new SqlConnection(Settings.DbContextConnectionString))
{
conn.Open();
var cmd = new SqlCommand("DELETE FROM [dbo].[LocalizationResources] WHERE [Id] = @id", conn);
cmd.Parameters.AddWithValue("id", resource.Id);
cmd.ExecuteNonQuery();
}
}
/// <summary>
/// Deletes all resources. DANGEROUS!
/// </summary>
public void DeleteAllResources()
{
using (var conn = new SqlConnection(Settings.DbContextConnectionString))
{
conn.Open();
var cmd = new SqlCommand("DELETE FROM [dbo].[LocalizationResourceTranslations]", conn);
cmd.ExecuteNonQuery();
cmd = new SqlCommand("DELETE FROM [dbo].[LocalizationResources]", conn);
cmd.ExecuteNonQuery();
}
}
/// <summary>
/// Inserts the resource in database.
/// </summary>
/// <param name="resource">The resource.</param>
/// <exception cref="ArgumentNullException">resource</exception>
public void InsertResource(LocalizationResource resource)
{
if (resource == null)
{
throw new ArgumentNullException(nameof(resource));
}
using (var conn = new SqlConnection(Settings.DbContextConnectionString))
{
conn.Open();
var cmd = new SqlCommand(
"INSERT INTO [dbo].[LocalizationResources] ([ResourceKey], [Author], [FromCode], [IsHidden], [IsModified], [ModificationDate], [Notes]) OUTPUT INSERTED.ID VALUES (@resourceKey, @author, @fromCode, @isHidden, @isModified, @modificationDate, @notes)",
conn);
cmd.Parameters.AddWithValue("resourceKey", resource.ResourceKey);
cmd.Parameters.AddWithValue("author", resource.Author ?? "unknown");
cmd.Parameters.AddWithValue("fromCode", resource.FromCode);
cmd.Parameters.AddWithValue("isHidden", resource.IsHidden);
cmd.Parameters.AddWithValue("isModified", resource.IsModified);
cmd.Parameters.AddWithValue("modificationDate", resource.ModificationDate);
cmd.Parameters.AddSafeWithValue("notes", resource.Notes);
// get inserted resource ID
var resourcePk = (int)cmd.ExecuteScalar();
// if there are also provided translations - execute those in the same connection also
if (resource.Translations.Any())
{
foreach (var translation in resource.Translations)
{
cmd = new SqlCommand(
"INSERT INTO [dbo].[LocalizationResourceTranslations] ([Language], [ResourceId], [Value], [ModificationDate]) VALUES (@language, @resourceId, @translation, @modificationDate)",
conn);
cmd.Parameters.AddWithValue("language", translation.Language);
cmd.Parameters.AddWithValue("resourceId", resourcePk);
cmd.Parameters.AddWithValue("translation", translation.Value);
cmd.Parameters.AddWithValue("modificationDate", resource.ModificationDate);
cmd.ExecuteNonQuery();
}
}
}
}
/// <summary>
/// Gets the available languages (reads in which languages translations are added).
/// </summary>
/// <param name="includeInvariant">if set to <c>true</c> [include invariant].</param>
/// <returns></returns>
public IEnumerable<CultureInfo> GetAvailableLanguages(bool includeInvariant)
{
try
{
using (var conn = new SqlConnection(Settings.DbContextConnectionString))
{
conn.Open();
var cmd = new SqlCommand(
"SELECT DISTINCT [Language] FROM [dbo].[LocalizationResourceTranslations] WHERE [Language] <> ''",
conn);
var reader = cmd.ExecuteReader();
var result = new List<CultureInfo>();
if (includeInvariant)
{
result.Add(CultureInfo.InvariantCulture);
}
while (reader.Read())
{
result.Add(new CultureInfo(reader.GetString(0)));
}
return result;
}
}
catch (Exception ex)
{
_logger?.Error($"Failed to retrieve all available languages.", ex);
return Enumerable.Empty<CultureInfo>();
}
}
/// <summary>
///Resets synchronization status of the resources.
/// </summary>
public void ResetSyncStatus()
{
using (var conn = new SqlConnection(Settings.DbContextConnectionString))
{
var cmd = new SqlCommand("UPDATE [dbo].[LocalizationResources] SET FromCode = 0", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
/// <summary>
/// Registers discovered resources.
/// </summary>
/// <param name="discoveredResources">Collection of discovered resources during scanning process.</param>
/// <param name="allResources">All existing resources (so you could compare and decide what script to generate).</param>
/// <param name="flexibleRefactoringMode">Run refactored resource sync in flexible / relaxed mode (leave existing resources in db).</param>
public void RegisterDiscoveredResources(
ICollection<DiscoveredResource> discoveredResources,
IEnumerable<LocalizationResource> allResources,
bool flexibleRefactoringMode)
{
// split work queue by 400 resources each
var groupedProperties = discoveredResources.SplitByCount(400);
Parallel.ForEach(
groupedProperties,
group =>
{
var sb = new StringBuilder();
sb.AppendLine("DECLARE @resourceId INT");
var refactoredResources = group.Where(r => !string.IsNullOrEmpty(r.OldResourceKey));
foreach (var refactoredResource in refactoredResources)
{
sb.Append($@"
IF EXISTS(SELECT 1 FROM LocalizationResources WITH(NOLOCK) WHERE ResourceKey = '{refactoredResource.OldResourceKey}'){(flexibleRefactoringMode ? " AND NOT EXISTS(SELECT 1 FROM LocalizationResources WITH(NOLOCK) WHERE ResourceKey = '" + refactoredResource.Key + "'" : string.Empty)})
BEGIN
UPDATE dbo.LocalizationResources SET ResourceKey = '{refactoredResource.Key}', FromCode = 1 WHERE ResourceKey = '{refactoredResource.OldResourceKey}'
END
");
}
foreach (var property in group)
{
var existingResource = allResources.FirstOrDefault(r => r.ResourceKey == property.Key);
if (existingResource == null)
{
sb.Append($@"
SET @resourceId = ISNULL((SELECT Id FROM LocalizationResources WHERE [ResourceKey] = '{property.Key}'), -1)
IF (@resourceId = -1)
BEGIN
INSERT INTO LocalizationResources ([ResourceKey], ModificationDate, Author, FromCode, IsModified, IsHidden)
VALUES ('{property.Key}', GETUTCDATE(), 'type-scanner', 1, 0, {Convert.ToInt32(property.IsHidden)})
SET @resourceId = SCOPE_IDENTITY()");
// add all translations
foreach (var propertyTranslation in property.Translations)
{
sb.Append($@"
INSERT INTO LocalizationResourceTranslations (ResourceId, [Language], [Value], [ModificationDate]) VALUES (@resourceId, '{propertyTranslation.Culture}', N'{propertyTranslation.Translation.Replace("'", "''")}', GETUTCDATE())");
}
sb.Append(@"
END
");
}
if (existingResource != null)
{
sb.AppendLine(
$"UPDATE LocalizationResources SET FromCode = 1, IsHidden = {Convert.ToInt32(property.IsHidden)} where [Id] = {existingResource.Id}");
var invariantTranslation = property.Translations.First(t => t.Culture == string.Empty);
sb.AppendLine(
$"UPDATE LocalizationResourceTranslations SET [Value] = N'{invariantTranslation.Translation.Replace("'", "''")}' where ResourceId={existingResource.Id} AND [Language]='{invariantTranslation.Culture}'");
if (existingResource.IsModified.HasValue && !existingResource.IsModified.Value)
{
foreach (var propertyTranslation in property.Translations)
{
AddTranslationScript(existingResource, sb, propertyTranslation);
}
}
}
}
using (var conn = new SqlConnection(Settings.DbContextConnectionString))
{
var cmd = new SqlCommand(sb.ToString(), conn) { CommandTimeout = 60 };
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
});
}
private static void AddTranslationScript(
LocalizationResource existingResource,
StringBuilder buffer,
DiscoveredTranslation resource)
{
var existingTranslation = existingResource.Translations.FirstOrDefault(t => t.Language == resource.Culture);
if (existingTranslation == null)
{
buffer.Append($@"
INSERT INTO [dbo].[LocalizationResourceTranslations] (ResourceId, [Language], [Value], [ModificationDate]) VALUES ({existingResource.Id}, '{resource.Culture}', N'{resource.Translation.Replace("'", "''")}', GETUTCDATE())");
}
else if (existingTranslation.Value == null || !existingTranslation.Value.Equals(resource.Translation))
{
buffer.Append($@"
UPDATE [dbo].[LocalizationResourceTranslations] SET [Value] = N'{resource.Translation.Replace("'", "''")}' WHERE ResourceId={existingResource.Id} and [Language]='{resource.Culture}'");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using ServiceStack.Common.Extensions;
using ServiceStack.Common.Tests;
using ServiceStack.Text.Tests.JsonTests;
namespace ServiceStack.Text.Tests.Support
{
[Ignore]
[TestFixture]
public class BenchmarkTests
: PerfTestBase
{
[Test]
public void Test_string_parsing()
{
const int stringSampleSize = 1024 * 10;
var testString = CreateRandomString(stringSampleSize);
var copyTo = new char[stringSampleSize];
CompareMultipleRuns(
"As char array",
() => {
var asChars = testString.ToCharArray();
for (var i = 0; i < stringSampleSize; i++)
{
copyTo[i] = asChars[i];
}
},
"As string",
() => {
for (var i = 0; i < stringSampleSize; i++)
{
copyTo[i] = testString[i];
}
});
}
public string CreateRandomString(int size)
{
var randString = new char[size];
for (var i = 0; i < size; i++)
{
randString[i] = (char)((i % 10) + '0');
}
return new string(randString);
}
static readonly char[] EscapeChars = new char[]
{
'"', '\n', '\r', '\t', '"', '\\', '\f', '\b',
};
public static readonly char[] JsvEscapeChars = new[]
{
'"', ',', '{', '}', '[', ']',
};
private const int LengthFromLargestChar = '\\' + 1;
private static readonly bool[] HasEscapeChars = new bool[LengthFromLargestChar];
[Test]
public void PrintEscapeChars()
{
//EscapeChars.ToList().OrderBy(x => (int)x).ForEach(x => Console.WriteLine(x + ": " + (int)x));
JsvEscapeChars.ToList().OrderBy(x => (int)x).ForEach(x => Console.WriteLine(x + ": " + (int)x));
}
[Test]
public void MeasureIndexOfEscapeChars()
{
foreach (var escapeChar in EscapeChars)
{
HasEscapeChars[escapeChar] = true;
}
var value = CreateRandomString(100);
var len = value.Length;
var hasEscapeChars = false;
CompareMultipleRuns(
"With bool flags",
() => {
for (var i = 0; i < len; i++)
{
var c = value[i];
if (c >= LengthFromLargestChar || !HasEscapeChars[c]) continue;
hasEscapeChars = true;
break;
}
},
"With IndexOfAny",
() => {
hasEscapeChars = value.IndexOfAny(EscapeChars) != -1;
});
Console.WriteLine(hasEscapeChars);
}
public class RuntimeType<T>
{
private static Type type = typeof(T);
internal static bool TestVarType()
{
return type == typeof(byte) || type == typeof(byte?)
|| type == typeof(short) || type == typeof(short?)
|| type == typeof(ushort) || type == typeof(ushort?)
|| type == typeof(int) || type == typeof(int?)
|| type == typeof(uint) || type == typeof(uint?)
|| type == typeof(long) || type == typeof(long?)
|| type == typeof(ulong) || type == typeof(ulong?)
|| type == typeof(bool) || type == typeof(bool?)
|| type != typeof(DateTime)
|| type != typeof(DateTime?)
|| type != typeof(Guid)
|| type != typeof(Guid?)
|| type != typeof(float) || type != typeof(float?)
|| type != typeof(double) || type != typeof(double?)
|| type != typeof(decimal) || type != typeof(decimal?);
}
internal static bool TestGenericType()
{
return typeof(T) == typeof(byte) || typeof(T) == typeof(byte?)
|| typeof(T) == typeof(short) || typeof(T) == typeof(short?)
|| typeof(T) == typeof(ushort) || typeof(T) == typeof(ushort?)
|| typeof(T) == typeof(int) || typeof(T) == typeof(int?)
|| typeof(T) == typeof(uint) || typeof(T) == typeof(uint?)
|| typeof(T) == typeof(long) || typeof(T) == typeof(long?)
|| typeof(T) == typeof(ulong) || typeof(T) == typeof(ulong?)
|| typeof(T) == typeof(bool) || typeof(T) == typeof(bool?)
|| typeof(T) != typeof(DateTime)
|| typeof(T) != typeof(DateTime?)
|| typeof(T) != typeof(Guid)
|| typeof(T) != typeof(Guid?)
|| typeof(T) != typeof(float) || typeof(T) != typeof(float?)
|| typeof(T) != typeof(double) || typeof(T) != typeof(double?)
|| typeof(T) != typeof(decimal) || typeof(T) != typeof(decimal?);
}
}
[Test]
public void TestVarOrGenericType()
{
var matchingTypesCount = 0;
CompareMultipleRuns(
"With var type",
() => {
if (RuntimeType<BenchmarkTests>.TestVarType())
{
matchingTypesCount++;
}
},
"With generic type",
() => {
if (RuntimeType<BenchmarkTests>.TestGenericType())
{
matchingTypesCount++;
}
});
Console.WriteLine(matchingTypesCount);
}
[Test]
public void Test_for_list_enumeration()
{
List<Cat> list = 20.Times(x => new Cat { Name = "Cat" });
var results = 0;
var listLength = list.Count;
CompareMultipleRuns(
"With foreach",
() => {
foreach (var cat in list)
{
results++;
}
},
"With for",
() => {
for (var i = 0; i < listLength; i++)
{
var cat = list[i];
results++;
}
});
Console.WriteLine(results);
}
[Test]
public void Test_for_Ilist_enumeration()
{
IList<Cat> list = 20.Times(x => new Cat { Name = "Cat" });
var results = 0;
var listLength = list.Count;
CompareMultipleRuns(
"With foreach",
() => {
foreach (var cat in list)
{
results++;
}
},
"With for",
() => {
for (var i = 0; i < listLength; i++)
{
var cat = list[i];
results++;
}
});
Console.WriteLine(results);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ServiceBus
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// QueuesOperations operations.
/// </summary>
public partial interface IQueuesOperations
{
/// <summary>
/// Gets the queues within a namespace.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639415.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<SBQueue>>> ListByNamespaceWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a Service Bus queue. This operation is
/// idempotent.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639395.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create or update a queue resource.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<SBQueue>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string queueName, SBQueue parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a queue from the specified namespace in a resource group.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639411.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string queueName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns a description for the specified queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639380.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<SBQueue>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string queueName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all authorization rules for a queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705607.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<SBAuthorizationRule>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string queueName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates an authorization rule for a queue.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
/// <param name='parameters'>
/// The shared access authorization rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<SBAuthorizationRule>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, SBAuthorizationRule parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a queue authorization rule.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705609.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets an authorization rule for a queue by rule name.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705611.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<SBAuthorizationRule>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Primary and secondary connection strings to the queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705608.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AccessKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Regenerates the primary or secondary connection strings to the
/// queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705606.aspx" />
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to regenerate the authorization rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AccessKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, RegenerateAccessKeyParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the queues within a namespace.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639415.aspx" />
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<SBQueue>>> ListByNamespaceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all authorization rules for a queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705607.aspx" />
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<SBAuthorizationRule>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#define DEBUG
namespace NLog.UnitTests
{
using System;
using System.Globalization;
using System.Threading;
using System.Diagnostics;
using Xunit;
public class NLogTraceListenerTests : NLogTestBase, IDisposable
{
private readonly CultureInfo previousCultureInfo;
public NLogTraceListenerTests()
{
this.previousCultureInfo = Thread.CurrentThread.CurrentCulture;
// set the culture info with the decimal separator (comma) different from InvariantCulture separator (point)
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
}
public void Dispose()
{
// restore previous culture info
Thread.CurrentThread.CurrentCulture = this.previousCultureInfo;
}
[Fact]
public void TraceWriteTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Debug.Listeners.Clear();
Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1" });
Debug.Write("Hello");
AssertDebugLastMessage("debug", "Logger1 Debug Hello");
Debug.Write("Hello", "Cat1");
AssertDebugLastMessage("debug", "Logger1 Debug Cat1: Hello");
Debug.Write(3.1415);
AssertDebugLastMessage("debug", string.Format("Logger1 Debug {0}", 3.1415));
Debug.Write(3.1415, "Cat2");
AssertDebugLastMessage("debug", string.Format("Logger1 Debug Cat2: {0}", 3.1415));
}
[Fact]
public void TraceWriteLineTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Debug.Listeners.Clear();
Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1" });
Debug.WriteLine("Hello");
AssertDebugLastMessage("debug", "Logger1 Debug Hello");
Debug.WriteLine("Hello", "Cat1");
AssertDebugLastMessage("debug", "Logger1 Debug Cat1: Hello");
Debug.WriteLine(3.1415);
AssertDebugLastMessage("debug", string.Format("Logger1 Debug {0}", 3.1415));
Debug.WriteLine(3.1415, "Cat2");
AssertDebugLastMessage("debug", string.Format("Logger1 Debug Cat2: {0}", 3.1415));
}
[Fact]
public void TraceWriteNonDefaultLevelTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
Debug.Listeners.Clear();
Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
Debug.Write("Hello");
AssertDebugLastMessage("debug", "Logger1 Trace Hello");
}
[Fact]
public void TraceConfiguration()
{
var listener = new NLogTraceListener();
listener.Attributes.Add("defaultLogLevel", "Warn");
listener.Attributes.Add("forceLogLevel", "Error");
listener.Attributes.Add("autoLoggerName", "1");
listener.Attributes.Add("DISABLEFLUSH", "true");
Assert.Equal(LogLevel.Warn, listener.DefaultLogLevel);
Assert.Equal(LogLevel.Error, listener.ForceLogLevel);
Assert.True(listener.AutoLoggerName);
Assert.True(listener.DisableFlush);
}
[Fact]
public void TraceFailTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Debug.Listeners.Clear();
Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1" });
Debug.Fail("Message");
AssertDebugLastMessage("debug", "Logger1 Error Message");
Debug.Fail("Message", "Detailed Message");
AssertDebugLastMessage("debug", "Logger1 Error Message Detailed Message");
}
[Fact]
public void AutoLoggerNameTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Debug.Listeners.Clear();
Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1", AutoLoggerName = true });
Debug.Write("Hello");
AssertDebugLastMessage("debug", this.GetType().FullName + " Debug Hello");
}
[Fact]
public void TraceDataTests()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
ts.TraceData(TraceEventType.Critical, 123, 42);
AssertDebugLastMessage("debug", "MySource1 Fatal 42 123");
ts.TraceData(TraceEventType.Critical, 145, 42, 3.14, "foo");
AssertDebugLastMessage("debug", string.Format("MySource1 Fatal 42, {0}, foo 145", 3.14.ToString(System.Globalization.CultureInfo.CurrentCulture)));
}
#if MONO
[Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")]
#else
[Fact]
#endif
public void LogInformationTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
ts.TraceInformation("Quick brown fox");
AssertDebugLastMessage("debug", "MySource1 Info Quick brown fox 0");
ts.TraceInformation("Mary had {0} lamb", "a little");
AssertDebugLastMessage("debug", "MySource1 Info Mary had a little lamb 0");
}
[Fact]
public void TraceEventTests()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
ts.TraceEvent(TraceEventType.Information, 123, "Quick brown {0} jumps over the lazy {1}.", "fox", "dog");
AssertDebugLastMessage("debug", "MySource1 Info Quick brown fox jumps over the lazy dog. 123");
ts.TraceEvent(TraceEventType.Information, 123);
AssertDebugLastMessage("debug", "MySource1 Info 123");
ts.TraceEvent(TraceEventType.Verbose, 145, "Bar");
AssertDebugLastMessage("debug", "MySource1 Trace Bar 145");
ts.TraceEvent(TraceEventType.Error, 145, "Foo");
AssertDebugLastMessage("debug", "MySource1 Error Foo 145");
ts.TraceEvent(TraceEventType.Suspend, 145, "Bar");
AssertDebugLastMessage("debug", "MySource1 Debug Bar 145");
ts.TraceEvent(TraceEventType.Resume, 145, "Foo");
AssertDebugLastMessage("debug", "MySource1 Debug Foo 145");
ts.TraceEvent(TraceEventType.Warning, 145, "Bar");
AssertDebugLastMessage("debug", "MySource1 Warn Bar 145");
ts.TraceEvent(TraceEventType.Critical, 145, "Foo");
AssertDebugLastMessage("debug", "MySource1 Fatal Foo 145");
}
#if MONO
[Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")]
#else
[Fact]
#endif
public void ForceLogLevelTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace, ForceLogLevel = LogLevel.Warn });
// force all logs to be Warn, DefaultLogLevel has no effect on TraceSource
ts.TraceInformation("Quick brown fox");
AssertDebugLastMessage("debug", "MySource1 Warn Quick brown fox 0");
ts.TraceInformation("Mary had {0} lamb", "a little");
AssertDebugLastMessage("debug", "MySource1 Warn Mary had a little lamb 0");
}
private static TraceSource CreateTraceSource()
{
var ts = new TraceSource("MySource1", SourceLevels.All);
#if MONO
// for some reason needed on Mono
ts.Switch = new SourceSwitch("MySource1", "Verbose");
ts.Switch.Level = SourceLevels.All;
#endif
return ts;
}
}
}
| |
using System.IO;
using Kitware.VTK;
using System;
// input file is C:\VTK\IO\Testing\Tcl\TestPolygonWriters.tcl
// output file is AVTestPolygonWriters.cs
/// <summary>
/// The testing class derived from AVTestPolygonWriters
/// </summary>
public class AVTestPolygonWritersClass
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVTestPolygonWriters(String [] argv)
{
//Prefix Content is: ""
// Create the RenderWindow, Renderer and both Actors[]
//[]
ren1 = vtkRenderer.New();
renWin = vtkRenderWindow.New();
renWin.AddRenderer((vtkRenderer)ren1);
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow((vtkRenderWindow)renWin);
// read data[]
//[]
input = new vtkPolyDataReader();
input.SetFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/brainImageSmooth.vtk");
//[]
// generate vectors[]
clean = new vtkCleanPolyData();
clean.SetInputConnection((vtkAlgorithmOutput)input.GetOutputPort());
smooth = new vtkWindowedSincPolyDataFilter();
smooth.SetInputConnection((vtkAlgorithmOutput)clean.GetOutputPort());
smooth.GenerateErrorVectorsOn();
smooth.GenerateErrorScalarsOn();
smooth.Update();
mapper = vtkPolyDataMapper.New();
mapper.SetInputConnection((vtkAlgorithmOutput)smooth.GetOutputPort());
mapper.SetScalarRange((double)((vtkDataSet)smooth.GetOutput()).GetScalarRange()[0],
(double)((vtkDataSet)smooth.GetOutput()).GetScalarRange()[1]);
brain = new vtkActor();
brain.SetMapper((vtkMapper)mapper);
// Add the actors to the renderer, set the background and size[]
//[]
ren1.AddActor((vtkProp)brain);
renWin.SetSize((int)320,(int)240);
ren1.GetActiveCamera().SetPosition((double)149.653,(double)-65.3464,(double)96.0401);
ren1.GetActiveCamera().SetFocalPoint((double)146.003,(double)22.3839,(double)0.260541);
ren1.GetActiveCamera().SetViewAngle((double)30);
ren1.GetActiveCamera().SetViewUp((double)-0.255578,(double)-0.717754,(double)-0.647695);
ren1.GetActiveCamera().SetClippingRange((double)79.2526,(double)194.052);
iren.Initialize();
renWin.Render();
// render the image[]
//[]
// prevent the tk window from showing up then start the event loop[]
//[]
// If the current directory is writable, then test the witers[]
//[]
try
{
channel = new StreamWriter("test.tmp");
tryCatchError = "NOERROR";
}
catch(Exception)
{tryCatchError = "ERROR";}
if(tryCatchError.Equals("NOERROR"))
{
channel.Close();
File.Delete("test.tmp");
//[]
//[]
// test the writers[]
dsw = new vtkDataSetWriter();
dsw.SetInputConnection((vtkAlgorithmOutput)smooth.GetOutputPort());
dsw.SetFileName((string)"brain.dsw");
dsw.Write();
File.Delete("brain.dsw");
pdw = new vtkPolyDataWriter();
pdw.SetInputConnection((vtkAlgorithmOutput)smooth.GetOutputPort());
pdw.SetFileName((string)"brain.pdw");
pdw.Write();
File.Delete("brain.pdw");
iv = new vtkIVWriter();
iv.SetInputConnection((vtkAlgorithmOutput)smooth.GetOutputPort());
iv.SetFileName((string)"brain.iv");
iv.Write();
File.Delete("brain.iv");
//[]
// the next writers only handle triangles[]
triangles = new vtkTriangleFilter();
triangles.SetInputConnection((vtkAlgorithmOutput)smooth.GetOutputPort());
iv2 = new vtkIVWriter();
iv2.SetInputConnection((vtkAlgorithmOutput)triangles.GetOutputPort());
iv2.SetFileName((string)"brain2.iv");
iv2.Write();
File.Delete("brain2.iv");
edges = new vtkExtractEdges();
edges.SetInputConnection((vtkAlgorithmOutput)triangles.GetOutputPort());
iv3 = new vtkIVWriter();
iv3.SetInputConnection((vtkAlgorithmOutput)edges.GetOutputPort());
iv3.SetFileName((string)"brain3.iv");
iv3.Write();
File.Delete("brain3.iv");
byu = new vtkBYUWriter();
byu.SetGeometryFileName((string)"brain.g");
byu.SetScalarFileName((string)"brain.s");
byu.SetDisplacementFileName((string)"brain.d");
byu.SetInputConnection((vtkAlgorithmOutput)triangles.GetOutputPort());
byu.Write();
File.Delete("brain.g");
File.Delete("brain.s");
File.Delete("brain.d");
mcubes = new vtkMCubesWriter();
mcubes.SetInputConnection((vtkAlgorithmOutput)triangles.GetOutputPort());
mcubes.SetFileName((string)"brain.tri");
mcubes.SetLimitsFileName((string)"brain.lim");
mcubes.Write();
File.Delete("brain.lim");
File.Delete("brain.tri");
stl = new vtkSTLWriter();
stl.SetInputConnection((vtkAlgorithmOutput)triangles.GetOutputPort());
stl.SetFileName((string)"brain.stl");
stl.Write();
File.Delete("brain.stl");
stlBinary = new vtkSTLWriter();
stlBinary.SetInputConnection((vtkAlgorithmOutput)triangles.GetOutputPort());
stlBinary.SetFileName((string)"brainBinary.stl");
stlBinary.SetFileType((int)2);
stlBinary.Write();
File.Delete("brainBinary.stl");
cgm = new vtkCGMWriter();
cgm.SetInputConnection((vtkAlgorithmOutput)triangles.GetOutputPort());
cgm.SetFileName((string)"brain.cgm");
cgm.Write();
File.Delete("brain.cgm");
}
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static vtkRenderer ren1;
static vtkRenderWindow renWin;
static vtkRenderWindowInteractor iren;
static vtkPolyDataReader input;
static vtkCleanPolyData clean;
static vtkWindowedSincPolyDataFilter smooth;
static vtkPolyDataMapper mapper;
static vtkActor brain;
static string tryCatchError;
static StreamWriter channel;
static vtkDataSetWriter dsw;
static vtkPolyDataWriter pdw;
static vtkIVWriter iv;
static vtkTriangleFilter triangles;
static vtkIVWriter iv2;
static vtkExtractEdges edges;
static vtkIVWriter iv3;
static vtkBYUWriter byu;
static vtkMCubesWriter mcubes;
static vtkSTLWriter stl;
static vtkSTLWriter stlBinary;
static vtkCGMWriter cgm;
///<summary> A Get Method for Static Variables </summary>
public static string GetVTK_DATA_ROOT()
{
return VTK_DATA_ROOT;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_DATA_ROOT(string toSet)
{
VTK_DATA_ROOT = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getthreshold()
{
return threshold;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setthreshold(int toSet)
{
threshold = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer Getren1()
{
return ren1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setren1(vtkRenderer toSet)
{
ren1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindow GetrenWin()
{
return renWin;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrenWin(vtkRenderWindow toSet)
{
renWin = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindowInteractor Getiren()
{
return iren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiren(vtkRenderWindowInteractor toSet)
{
iren = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataReader Getinput()
{
return input;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setinput(vtkPolyDataReader toSet)
{
input = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCleanPolyData Getclean()
{
return clean;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setclean(vtkCleanPolyData toSet)
{
clean = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkWindowedSincPolyDataFilter Getsmooth()
{
return smooth;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setsmooth(vtkWindowedSincPolyDataFilter toSet)
{
smooth = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper Getmapper()
{
return mapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setmapper(vtkPolyDataMapper toSet)
{
mapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor Getbrain()
{
return brain;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setbrain(vtkActor toSet)
{
brain = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static string GettryCatchError()
{
return tryCatchError;
}
///<summary> A Set Method for Static Variables </summary>
public static void SettryCatchError(string toSet)
{
tryCatchError = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static StreamWriter Getchannel()
{
return channel;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setchannel(StreamWriter toSet)
{
channel = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataSetWriter Getdsw()
{
return dsw;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setdsw(vtkDataSetWriter toSet)
{
dsw = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataWriter Getpdw()
{
return pdw;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setpdw(vtkPolyDataWriter toSet)
{
pdw = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkIVWriter Getiv()
{
return iv;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiv(vtkIVWriter toSet)
{
iv = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkTriangleFilter Gettriangles()
{
return triangles;
}
///<summary> A Set Method for Static Variables </summary>
public static void Settriangles(vtkTriangleFilter toSet)
{
triangles = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkIVWriter Getiv2()
{
return iv2;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiv2(vtkIVWriter toSet)
{
iv2 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkExtractEdges Getedges()
{
return edges;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setedges(vtkExtractEdges toSet)
{
edges = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkIVWriter Getiv3()
{
return iv3;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiv3(vtkIVWriter toSet)
{
iv3 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkBYUWriter Getbyu()
{
return byu;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setbyu(vtkBYUWriter toSet)
{
byu = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkMCubesWriter Getmcubes()
{
return mcubes;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setmcubes(vtkMCubesWriter toSet)
{
mcubes = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkSTLWriter Getstl()
{
return stl;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setstl(vtkSTLWriter toSet)
{
stl = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkSTLWriter GetstlBinary()
{
return stlBinary;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetstlBinary(vtkSTLWriter toSet)
{
stlBinary = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCGMWriter Getcgm()
{
return cgm;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setcgm(vtkCGMWriter toSet)
{
cgm = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(ren1!= null){ren1.Dispose();}
if(renWin!= null){renWin.Dispose();}
if(iren!= null){iren.Dispose();}
if(input!= null){input.Dispose();}
if(clean!= null){clean.Dispose();}
if(smooth!= null){smooth.Dispose();}
if(mapper!= null){mapper.Dispose();}
if(brain!= null){brain.Dispose();}
if(dsw!= null){dsw.Dispose();}
if(pdw!= null){pdw.Dispose();}
if(iv!= null){iv.Dispose();}
if(triangles!= null){triangles.Dispose();}
if(iv2!= null){iv2.Dispose();}
if(edges!= null){edges.Dispose();}
if(iv3!= null){iv3.Dispose();}
if(byu!= null){byu.Dispose();}
if(mcubes!= null){mcubes.Dispose();}
if(stl!= null){stl.Dispose();}
if(stlBinary!= null){stlBinary.Dispose();}
if(cgm!= null){cgm.Dispose();}
}
}
//--- end of script --//
| |
using System;
using System.IO;
using LanguageExt.Common;
using LanguageExt.TypeClasses;
using System.Collections.Generic;
using static LanguageExt.Prelude;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using LanguageExt.Sys.Traits;
namespace LanguageExt.Sys
{
/// <summary>
/// Environment IO
/// </summary>
public static class Environment<RT>
where RT : struct, HasEnvironment<RT>
{
/// <summary>
/// Gets the command line for this process.
/// </summary>
public static Eff<RT, string> commandLine =>
default(RT).EnvironmentEff.Map(static e => e.CommandLine());
/// <summary>
/// Gets a unique identifier for the current managed thread.
/// </summary>
public static Eff<RT, int> currentManagedThreadId =>
default(RT).EnvironmentEff.Map(static e => e.CurrentManagedThreadId());
/// <summary>
/// Terminates this process and returns an exit code to the operating system.
/// </summary>
public static Eff<RT, Unit> exit(int exitCode) =>
default(RT).EnvironmentEff.Map(e => e.Exit(exitCode));
/// <summary>
/// Gets the exit code of the process.
/// </summary>
public static Eff<RT, int> exitCode =>
default(RT).EnvironmentEff.Map(static e => e.ExitCode());
/// <summary>
/// Sets the exit code of the process.
/// </summary>
/// <param name="exitCode">exit code of the process</param>
public static Eff<RT, Unit> setExitCode(int exitCode) =>
default(RT).EnvironmentEff.Map(e => e.SetExitCode(exitCode));
/// <summary>
/// Replaces the name of each environment variable embedded in the specified string with the string equivalent of the value of the variable, then returns the resulting string.
/// </summary>
/// <param name="name">A string containing the names of zero or more environment variables. Each environment variable is quoted with the percent sign character (%).</param>
public static Eff<RT, string> expandEnvironmentVariables(string name) =>
default(RT).EnvironmentEff.Map(e => e.ExpandEnvironmentVariables(name));
/// <summary>
/// Immediately terminates a process after writing a message to the Windows Application event log, and then includes the message in error reporting to Microsoft.
/// </summary>
/// <param name="message">A message that explains why the process was terminated, or null if no explanation is provided.</param>
public static Eff<RT, Unit> failFast(Option<string> message) =>
default(RT).EnvironmentEff.Map(e => e.FailFast(message));
/// <summary>
/// Immediately terminates a process after writing a message to the Windows Application event log, and then includes the message and exception information in error reporting to Microsoft.
/// </summary>
/// <param name="message">A message that explains why the process was terminated, or null if no explanation is provided.</param>
/// <param name="exception">An exception that represents the error that caused the termination. This is typically the exception in a catch block.</param>
public static Eff<RT, Unit> failFast(Option<string> message, Option<Exception> exception) =>
default(RT).EnvironmentEff.Map(e => e.FailFast(message, exception));
/// <summary>
/// Returns a string array containing the command-line arguments for the current process.
/// </summary>
public static Eff<RT, Seq<string>> commandLineArgs =>
default(RT).EnvironmentEff.Map(static e => e.GetCommandLineArgs());
/// <summary>
/// Retrieves the value of an environment variable from the current process.
/// </summary>
/// <param name="variable">The name of an environment variable.</param>
public static Eff<RT, Option<string>> getEnvironmentVariable(string variable) =>
default(RT).EnvironmentEff.Map(e => e.GetEnvironmentVariable(variable));
/// <summary>
/// Retrieves the value of an environment variable from the current process or from the Windows operating system registry key for the current user or local machine.
/// </summary>
/// <param name="variable">The name of an environment variable.</param>
/// <param name="target">Target</param>
public static Eff<RT, Option<string>> getEnvironmentVariable(string variable, EnvironmentVariableTarget target) =>
default(RT).EnvironmentEff.Map(e => e.GetEnvironmentVariable(variable, target));
/// <summary>
/// Retrieves all environment variable names and their values from the current process.
/// </summary>
public static Eff<RT, HashMap<string, string>> environmentVariables =>
default(RT).EnvironmentEff.Map(static e => e.GetEnvironmentVariables());
/// <summary>
/// Retrieves all environment variable names and their values from the current process, or from the Windows operating system registry key for the current user or local machine.
/// </summary>
/// <param name="target">One of the System.EnvironmentVariableTarget values. Only System.EnvironmentVariableTarget.Process is supported on .NET Core running on Unix-based systems.</param>
public static Eff<RT, HashMap<string, string>> getEnvironmentVariables(System.EnvironmentVariableTarget target) =>
default(RT).EnvironmentEff.Map(e => e.GetEnvironmentVariables(target));
/// <summary>
/// Gets the path to the system special folder that is identified by the specified enumeration.
/// </summary>
/// <param name="folder">One of enumeration values that identifies a system special folder.</param>
public static Eff<RT, string> getFolderPath(System.Environment.SpecialFolder folder) =>
default(RT).EnvironmentEff.Map(e => e.GetFolderPath(folder));
/// <summary>
/// Gets the path to the system special folder that is identified by the specified enumeration, and uses a specified option for accessing special folders.
/// </summary>
/// <param name="folder">One of the enumeration values that identifies a system special folder.</param>
/// <param name="option">One of the enumeration values that specifies options to use for accessing a special folder.</param>
public static Eff<RT, string> getFolderPath(System.Environment.SpecialFolder folder, System.Environment.SpecialFolderOption option) =>
default(RT).EnvironmentEff.Map(e => e.GetFolderPath(folder, option));
/// <summary>
/// Returns an array of string containing the names of the logical drives on the current computer.
/// </summary>
public static Eff<RT, Seq<string>> logicalDrives =>
default(RT).EnvironmentEff.Map(static e => e.GetLogicalDrives());
/// <summary>
/// Gets a value that indicates whether the current application domain is being unloaded or the common language runtime (CLR) is shutting down.
/// </summary>
public static Eff<RT, bool> hasShutdownStarted =>
default(RT).EnvironmentEff.Map(static e => e.HasShutdownStarted());
/// <summary>
/// Determines whether the current operating system is a 64-bit operating system.
/// </summary>
public static Eff<RT, bool> is64BitOperatingSystem =>
default(RT).EnvironmentEff.Map(static e => e.Is64BitOperatingSystem());
/// <summary>
/// Determines whether the current process is a 64-bit process.
/// </summary>
public static Eff<RT, bool> is64BitProcess =>
default(RT).EnvironmentEff.Map(static e => e.Is64BitProcess());
/// <summary>
/// Gets the NetBIOS name of this local computer.
/// </summary>
public static Eff<RT, string> machineName =>
default(RT).EnvironmentEff.Map(static e => e.MachineName());
/// <summary>
/// Gets the newline string defined for this environment.
/// </summary>
public static Eff<RT, string> newLine =>
default(RT).EnvironmentEff.Map(static e => e.NewLine());
/// <summary>
/// Gets an OperatingSystem object that contains the current platform identifier and version number.
/// </summary>
public static Eff<RT, OperatingSystem> osVersion =>
default(RT).EnvironmentEff.Map(static e => e.OSVersion());
/// <summary>
/// Gets the number of processors on the current machine.
/// </summary>
public static Eff<RT, int> processorCount =>
default(RT).EnvironmentEff.Map(static e => e.ProcessorCount());
/// <summary>
/// Creates, modifies, or deletes an environment variable stored in the current process.
/// </summary>
/// <param name="variable">The name of an environment variable.</param>
/// <param name="value">A value to assign to variable .</param>
public static Eff<RT, Unit> setEnvironmentVariable(string variable, Option<string> value) =>
default(RT).EnvironmentEff.Map(e => e.SetEnvironmentVariable(variable, value));
/// <summary>
/// Creates, modifies, or deletes an environment variable stored in the current process or in the Windows operating system registry key reserved for the current user or local machine.
/// </summary>
/// <param name="variable">The name of an environment variable.</param>
/// <param name="value">A value to assign to variable.</param>
/// <param name="target">One of the enumeration values that specifies the location of the environment variable.</param>
public static Eff<RT, Unit> SetEnvironmentVariable(string variable, Option<string> value, EnvironmentVariableTarget target) =>
default(RT).EnvironmentEff.Map(e => e.SetEnvironmentVariable(variable, value, target));
/// <summary>
/// Gets current stack trace information.
/// </summary>
public static Eff<RT, string> stackTrace =>
default(RT).EnvironmentEff.Map(static e => e.StackTrace());
/// <summary>
/// Gets the fully qualified path of the system directory.
/// </summary>
public static Eff<RT, string> systemDirectory =>
default(RT).EnvironmentEff.Map(static e => e.SystemDirectory());
/// <summary>
/// Gets the number of bytes in the operating system's memory page.
/// </summary>
public static Eff<RT, int> systemPageSize =>
default(RT).EnvironmentEff.Map(static e => e.SystemPageSize());
/// <summary>
/// Gets the number of milliseconds elapsed since the system started.
/// </summary>
public static Eff<RT, int> tickCount =>
default(RT).EnvironmentEff.Map(static e => e.TickCount());
/// <summary>
/// Gets the network domain name associated with the current user.
/// </summary>
public static Eff<RT, string> userDomainName =>
default(RT).EnvironmentEff.Map(static e => e.UserDomainName());
/// <summary>
/// Gets a value indicating whether the current process is running in user interactive mode.
/// </summary>
public static Eff<RT, bool> userInteractive =>
default(RT).EnvironmentEff.Map(static e => e.UserInteractive());
/// <summary>
/// Gets the user name of the person who is currently logged on to the operating system.
/// </summary>
public static Eff<RT, string> userName =>
default(RT).EnvironmentEff.Map(static e => e.UserName());
/// <summary>
/// Gets a Version object that describes the major, minor, build, and revision numbers of the common language runtime.
/// </summary>
public static Eff<RT, Version> version =>
default(RT).EnvironmentEff.Map(static e => e.Version());
/// <summary>
/// Gets the amount of physical memory mapped to the process context.
/// </summary>
public static Eff<RT, long> workingSet =>
default(RT).EnvironmentEff.Map(static e => e.WorkingSet());
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace settings4net.TestWebApp.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
namespace Microsoft.Azure.Batch.FileStaging
{
/// <summary>
/// Provides for file staging of a local file to blob storage.
/// </summary>
public sealed class FileToStage : IFileStagingProvider
{
/// <summary>
/// The name of the local file to stage to blob storage
/// </summary>
public string LocalFileToStage
{
get;
internal set;
}
/// <summary>
/// The target filename, on the compute node, to which the blob contents will be downloaded.
/// </summary>
public string NodeFileName
{
get;
internal set;
}
/// <summary>
/// The instances of ResourcesFile for the staged local file.
/// For this implementation, successful file staging of this object will
/// result in a collection with only one entry.
/// </summary>
public IEnumerable<ResourceFile> StagedFiles
{
get;
internal set;
}
/// <summary>
/// The exception, if any, caught while attempting to stage this file.
/// </summary>
public Exception Exception
{
get;
internal set;
}
#region constructors
private FileToStage()
{
}
/// <summary>
/// Specifies that a local file should be staged to blob storage.
/// The specified account will be charged for storage costs.
/// </summary>
/// <param name="localFileToStage">The name of the local file.</param>
/// <param name="storageCredentials">The storage credentials to be used when creating the default container.</param>
/// <param name="nodeFileName">Optional name to be given to the file on the compute node. If this parameter is null or missing
/// the name on the compute node will be set to the value of localFileToStage stripped of all path information.</param>
public FileToStage(string localFileToStage, StagingStorageAccount storageCredentials, string nodeFileName = null)
{
this.LocalFileToStage = localFileToStage;
this.StagingStorageAccount = storageCredentials;
if (string.IsNullOrWhiteSpace(this.LocalFileToStage))
{
throw new ArgumentOutOfRangeException("localFileToStage");
}
// map null to base name of local file
if (string.IsNullOrWhiteSpace(nodeFileName))
{
this.NodeFileName = Path.GetFileName(this.LocalFileToStage);
}
else
{
this.NodeFileName = nodeFileName;
}
}
#endregion // constructors
#region // IFileStagingProvider
/// <summary>
/// See <see cref="IFileStagingProvider.StageFilesAsync"/>.
/// </summary>
/// <param name="filesToStage">The instances of IFileStagingProvider to stage.</param>
/// <param name="fileStagingArtifact">IFileStagingProvider specific staging artifacts including error/progress.</param>
/// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns>
public async System.Threading.Tasks.Task StageFilesAsync(List<IFileStagingProvider> filesToStage, IFileStagingArtifact fileStagingArtifact)
{
System.Threading.Tasks.Task taskForStaticStaging = FileToStage.StageFilesInternalAsync(filesToStage, fileStagingArtifact);
await taskForStaticStaging.ConfigureAwait(continueOnCapturedContext: false);
return;
}
/// <summary>
/// See <see cref="IFileStagingProvider.CreateStagingArtifact"/>.
/// </summary>
/// <returns>An instance of IFileStagingArtifact with default values.</returns>
public IFileStagingArtifact CreateStagingArtifact()
{
return new SequentialFileStagingArtifact() as IFileStagingArtifact;
}
/// <summary>
/// See <see cref="IFileStagingProvider.Validate"/>.
/// </summary>
public void Validate()
{
if (!File.Exists(this.LocalFileToStage))
{
throw new FileNotFoundException(string.Format(ErrorMessages.FileStagingLocalFileNotFound, this.LocalFileToStage));
}
}
#endregion // IFileStagingProvier
#region internal/private
// the staging code needs to get the secrets
internal StagingStorageAccount StagingStorageAccount { get; set; }
/// <summary>
/// combine container and blob into an URL.
/// </summary>
/// <param name="container">container url</param>
/// <param name="blob">blob url</param>
/// <returns>full url</returns>
private static string ConstructBlobSource(string container, string blob)
{
int index = container.IndexOf("?");
if (index != -1)
{
//SAS
string containerAbsoluteUrl = container.Substring(0, index);
return containerAbsoluteUrl + "/" + blob + container.Substring(index);
}
else
{
return container + "/" + blob;
}
}
/// <summary>
/// create a container if doesn't exist, setting permission with policy, and return assosciated SAS signature
/// </summary>
/// <param name="account">storage account</param>
/// <param name="key">storage key</param>
/// <param name="container">container to be created</param>
/// <param name="policy">name for the policy</param>
/// <param name="start">start time of the policy</param>
/// <param name="end">expire time of the policy</param>
/// <param name="permissions">permission on the name</param>
/// <param name="blobUri">blob URI</param>
/// <returns>the SAS for the container, in full URI format.</returns>
private static string CreateContainerWithPolicySASIfNotExist(string account, string key, Uri blobUri, string container, string policy, DateTime start, DateTime end, SharedAccessBlobPermissions permissions)
{
// 1. form the credentail and initial client
CloudStorageAccount storageaccount = new CloudStorageAccount(new WindowsAzure.Storage.Auth.StorageCredentials(account, key),
blobEndpoint: blobUri,
queueEndpoint: null,
tableEndpoint: null,
fileEndpoint: null);
CloudBlobClient client = storageaccount.CreateCloudBlobClient();
// 2. create container if it doesn't exist
CloudBlobContainer storagecontainer = client.GetContainerReference(container);
storagecontainer.CreateIfNotExistsAsync().GetAwaiter().GetResult();
// 3. validate policy, create/overwrite if doesn't match
bool policyFound = false;
SharedAccessBlobPolicy accesspolicy = new SharedAccessBlobPolicy()
{
SharedAccessExpiryTime = end,
SharedAccessStartTime = start,
Permissions = permissions
};
BlobContainerPermissions blobPermissions = storagecontainer.GetPermissionsAsync().GetAwaiter().GetResult();
if (blobPermissions.SharedAccessPolicies.ContainsKey(policy))
{
SharedAccessBlobPolicy containerpolicy = blobPermissions.SharedAccessPolicies[policy];
if (!(permissions == (containerpolicy.Permissions & permissions) && start <= containerpolicy.SharedAccessStartTime && end >= containerpolicy.SharedAccessExpiryTime))
{
blobPermissions.SharedAccessPolicies[policy] = accesspolicy;
}
else
{
policyFound = true;
}
}
else
{
blobPermissions.SharedAccessPolicies.Add(policy, accesspolicy);
}
if (!policyFound)
{
storagecontainer.SetPermissionsAsync(blobPermissions).GetAwaiter().GetResult();
}
// 4. genereate SAS and return
string container_sas = storagecontainer.GetSharedAccessSignature(new SharedAccessBlobPolicy(), policy);
string container_url = storagecontainer.Uri.AbsoluteUri + container_sas;
return container_url;
}
private static void CreateDefaultBlobContainerAndSASIfNeededReturn(List<IFileStagingProvider> filesToStage, SequentialFileStagingArtifact seqArtifact)
{
if ((null != filesToStage) && (filesToStage.Count > 0))
{
// construct the name of the new blob container.
seqArtifact.BlobContainerCreated = FileStagingNamingHelpers.ConstructDefaultName(seqArtifact.NamingFragment).ToLowerInvariant();
// get any instance for the storage credentials
FileToStage anyRealInstance = FindAtLeastOne(filesToStage);
if (null != anyRealInstance)
{
StagingStorageAccount creds = anyRealInstance.StagingStorageAccount;
string policyName = Batch.Constants.DefaultConveniencePrefix + Constants.DefaultContainerPolicyFragment;
DateTime startTime = DateTime.UtcNow;
DateTime expiredAtTime = startTime + new TimeSpan(24 /* hrs*/, 0, 0);
seqArtifact.DefaultContainerSAS = CreateContainerWithPolicySASIfNotExist(
creds.StorageAccount,
creds.StorageAccountKey,
creds.BlobUri,
seqArtifact.BlobContainerCreated,
policyName,
startTime,
expiredAtTime,
SharedAccessBlobPermissions.Read);
return; // done
}
}
}
/// <summary>
/// Since this is the SequentialFileStagingProvider, all files are supposed to be of this type.
/// Find any one and return the implementation instance.
/// </summary>
/// <param name="filesToStage"></param>
/// <returns>Null means there was not even one.</returns>
private static FileToStage FindAtLeastOne(List<IFileStagingProvider> filesToStage)
{
if ((null != filesToStage) && (filesToStage.Count > 0))
{
foreach(IFileStagingProvider curProvider in filesToStage)
{
FileToStage thisIsReal = curProvider as FileToStage;
if (null != thisIsReal)
{
return thisIsReal;
}
}
}
return null;
}
/// <summary>
/// Starts an asynchronous call to stage the given files.
/// </summary>
private static async System.Threading.Tasks.Task StageFilesInternalAsync(List<IFileStagingProvider> filesToStage, IFileStagingArtifact fileStagingArtifact)
{
if (null == filesToStage)
{
throw new ArgumentNullException("filesToStage");
}
if (null == fileStagingArtifact)
{
throw new ArgumentNullException("filesStagingArtifact");
}
SequentialFileStagingArtifact seqArtifact = fileStagingArtifact as SequentialFileStagingArtifact;
if (null == seqArtifact)
{
throw new ArgumentOutOfRangeException(ErrorMessages.FileStagingIncorrectArtifact);
}
// is there any work to do?
if (null == FindAtLeastOne(filesToStage))
{
return; // now work to do. none of the files belong to this provider
}
// is there any work to do
if ((null == filesToStage) || (filesToStage.Count <= 0))
{
return; // we are done
}
// create a Run task to create the blob containers if needed
System.Threading.Tasks.Task createContainerTask = System.Threading.Tasks.Task.Run(() => { CreateDefaultBlobContainerAndSASIfNeededReturn(filesToStage, seqArtifact); });
// wait for container to be created
await createContainerTask.ConfigureAwait(continueOnCapturedContext: false);
// begin staging the files
System.Threading.Tasks.Task stageTask = StageFilesAsync(filesToStage, seqArtifact);
// wait for files to be staged
await stageTask.ConfigureAwait(continueOnCapturedContext: false);
}
/// <summary>
/// Stages all files in the queue
/// </summary>
private async static System.Threading.Tasks.Task StageFilesAsync(List<IFileStagingProvider> filesToStage, SequentialFileStagingArtifact seqArtifacts)
{
foreach (IFileStagingProvider currentFile in filesToStage)
{
// for "retry" and/or "double calls" we ignore files that have already been staged
if (null == currentFile.StagedFiles)
{
FileToStage fts = currentFile as FileToStage;
if (null != fts)
{
System.Threading.Tasks.Task stageTask = StageOneFileAsync(fts, seqArtifacts);
await stageTask.ConfigureAwait(continueOnCapturedContext: false);
}
}
}
}
/// <summary>
/// Stage a single file.
/// </summary>
private async static System.Threading.Tasks.Task StageOneFileAsync(FileToStage stageThisFile, SequentialFileStagingArtifact seqArtifacts)
{
StagingStorageAccount storecreds = stageThisFile.StagingStorageAccount;
string containerName = seqArtifacts.BlobContainerCreated;
// TODO: this flattens all files to the top of the compute node/task relative file directory. solve the hiearchy problem (virt dirs?)
string blobName = Path.GetFileName(stageThisFile.LocalFileToStage);
// Create the storage account with the connection string.
CloudStorageAccount storageAccount = new CloudStorageAccount(
new WindowsAzure.Storage.Auth.StorageCredentials(storecreds.StorageAccount, storecreds.StorageAccountKey),
blobEndpoint: storecreds.BlobUri,
queueEndpoint: null,
tableEndpoint: null,
fileEndpoint: null);
CloudBlobClient client = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = client.GetContainerReference(containerName);
ICloudBlob blob = container.GetBlockBlobReference(blobName);
bool doesBlobExist;
try
{
// fetch attributes so we can compare file lengths
System.Threading.Tasks.Task fetchTask = blob.FetchAttributesAsync();
await fetchTask.ConfigureAwait(continueOnCapturedContext: false);
doesBlobExist = true;
}
catch (StorageException scex)
{
// check to see if blob does not exist
if ((int)System.Net.HttpStatusCode.NotFound == scex.RequestInformation.HttpStatusCode)
{
doesBlobExist = false;
}
else
{
throw; // unknown exception, throw to caller
}
}
bool mustUploadBlob = true; // we do not re-upload blobs if they have already been uploaded
if (doesBlobExist) // if the blob exists, compare
{
FileInfo fi = new FileInfo(stageThisFile.LocalFileToStage);
// since we don't have a hash of the contents... we check length
if (blob.Properties.Length == fi.Length)
{
mustUploadBlob = false;
}
}
if (mustUploadBlob)
{
// upload the file
System.Threading.Tasks.Task uploadTask = blob.UploadFromFileAsync(stageThisFile.LocalFileToStage);
await uploadTask.ConfigureAwait(continueOnCapturedContext: false);
}
// get the SAS for the blob
string blobSAS = ConstructBlobSource(seqArtifacts.DefaultContainerSAS, blobName);
string nodeFileName = stageThisFile.NodeFileName;
// create a new ResourceFile and populate it. This file is now staged!
stageThisFile.StagedFiles = new ResourceFile[] { new ResourceFile(blobSAS, nodeFileName) };
}
#endregion internal/private
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
/// <summary>
/// SByte.Parse(String,NumberStyle,IFormatProvider)
/// </summary>
public class SByteParse3
{
public static int Main()
{
SByteParse3 sbyteParse3 = new SByteParse3();
TestLibrary.TestFramework.BeginTestCase("SByteParse3");
if (sbyteParse3.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
return retVal;
}
#region PositiveTest
public bool PosTest1()
{
bool retVal = true;
IFormatProvider provider = new CultureInfo("en-us");
TestLibrary.TestFramework.BeginScenario("PosTest1: the string represents SByte MaxValue 1");
try
{
string sourceStr = SByte.MaxValue.ToString();
NumberStyles style = NumberStyles.Any;
sbyte SByteVale = sbyte.Parse(sourceStr, style, provider);
if (SByteVale != sbyte.MaxValue)
{
TestLibrary.TestFramework.LogError("001", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
IFormatProvider provider = new CultureInfo("el-GR");
TestLibrary.TestFramework.BeginScenario("PosTest2: the string represents sbyte MaxValue 2");
try
{
string sourceStr = sbyte.MaxValue.ToString();
NumberStyles style = NumberStyles.Any;
sbyte SByteVal = sbyte.Parse(sourceStr, style, provider);
if (SByteVal != sbyte.MaxValue)
{
TestLibrary.TestFramework.LogError("003", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
CultureInfo myculture = new CultureInfo("en-us");
IFormatProvider provider = myculture.NumberFormat;
TestLibrary.TestFramework.BeginScenario("PosTest3: the string represents sbyte MinValue 1");
try
{
string sourceStr= sbyte.MinValue.ToString();
NumberStyles style = NumberStyles.Any;
sbyte SByteVal = sbyte.Parse(sourceStr, style, provider);
if (SByteVal != sbyte.MinValue)
{
TestLibrary.TestFramework.LogError("005", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
CultureInfo myculture = new CultureInfo("el-GR");
IFormatProvider provider = myculture.NumberFormat;
TestLibrary.TestFramework.BeginScenario("PosTest4: the string represents sbyte MinValue 2");
try
{
string sourceStr= sbyte.MinValue.ToString();
NumberStyles style = NumberStyles.Any;
sbyte SByteVal = sbyte.Parse(sourceStr, style, provider);
if (SByteVal != sbyte.MinValue)
{
TestLibrary.TestFramework.LogError("007", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
CultureInfo mycultrue = new CultureInfo("en-us");
IFormatProvider provider = mycultrue.NumberFormat;
TestLibrary.TestFramework.BeginScenario("PosTest5: the string format is [ws][sign]digits[ws] 1");
try
{
sbyte SByteVal = (sbyte)this.GetInt32(0, 127);
string sourceStr = "\u0020" + "+" + SByteVal.ToString();
NumberStyles style = NumberStyles.Any;
sbyte result = sbyte.Parse(sourceStr, style, provider);
if (result != SByteVal)
{
TestLibrary.TestFramework.LogError("009", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
CultureInfo mycultrue = new CultureInfo("en-us");
IFormatProvider provider = mycultrue.NumberFormat;
TestLibrary.TestFramework.BeginScenario("PosTest6: the string format is [ws][sign]digits[ws] 2");
try
{
sbyte SByteVal = (sbyte)this.GetInt32(0, 128);
string sourceStr = "\u0020" + "-" + SByteVal.ToString();
NumberStyles style = NumberStyles.Any;
sbyte result = sbyte.Parse(sourceStr, style, provider);
if (result != SByteVal * (-1))
{
TestLibrary.TestFramework.LogError("011", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
CultureInfo mycultrue = new CultureInfo("en-us");
IFormatProvider provider = mycultrue.NumberFormat;
TestLibrary.TestFramework.BeginScenario("PosTest7: the string format is [ws][sign]digits[ws] 3");
try
{
sbyte SByteVal = (sbyte)this.GetInt32(0, 128);
string sourceStr = "\u0020" + "-" + SByteVal.ToString() + "\u0020";
NumberStyles style = NumberStyles.Any;
sbyte result = sbyte.Parse(sourceStr, style, provider);
if (result != SByteVal * (-1))
{
TestLibrary.TestFramework.LogError("013", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
CultureInfo mycultrue = new CultureInfo("en-us");
IFormatProvider provider = mycultrue.NumberFormat;
TestLibrary.TestFramework.BeginScenario("PosTest8: the string format is [ws][sign]digits[ws] 4");
try
{
sbyte SByteVal = (sbyte)this.GetInt32(0, 128);
string sourceStr = "\u0020" + "-0" + SByteVal.ToString() + "\u0020";
NumberStyles style = NumberStyles.Any;
sbyte result = sbyte.Parse(sourceStr, style, provider);
if (result != SByteVal * (-1))
{
TestLibrary.TestFramework.LogError("015", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest9()
{
bool retVal = true;
CultureInfo mycultrue = new CultureInfo("en-us");
IFormatProvider provider = mycultrue.NumberFormat;
TestLibrary.TestFramework.BeginScenario("PosTest9: the string formed with acceptable characters");
try
{
string sourceStr = "\u0020" + "7f" + "\u0020";
NumberStyles style = NumberStyles.HexNumber;
sbyte result = sbyte.Parse(sourceStr, style, provider);
if (result != sbyte.MaxValue)
{
TestLibrary.TestFramework.LogError("017", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("018", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTest
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: the string is null");
try
{
string sourceStr = null;
NumberStyles style = NumberStyles.Any;
IFormatProvider provider = new CultureInfo("en-us");
sbyte desSByte = sbyte.Parse(sourceStr, style, provider);
TestLibrary.TestFramework.LogError("N001", "the string is null but not throw exception");
retVal = false;
}
catch (ArgumentNullException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: the string does not consist of an optional sign follow by a sequence of digit");
try
{
string sourceStr = "helloworld";
NumberStyles style = NumberStyles.Any;
IFormatProvider provider = new CultureInfo("en-us");
sbyte desSByte = sbyte.Parse(sourceStr, style, provider);
TestLibrary.TestFramework.LogError("N003", "the string does not consist of an optional sign follow by a sequence of digit but not throw exception");
retVal = false;
}
catch (FormatException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: the string represents digit less than SByte MinValue");
try
{
string sourceStr = "-129";
NumberStyles style = NumberStyles.Any;
IFormatProvider provider = new CultureInfo("en-us");
sbyte desSByte = sbyte.Parse(sourceStr, style, provider);
TestLibrary.TestFramework.LogError("N005", "the string represents digit less than SByte MinValue");
retVal = false;
}
catch (OverflowException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: the string represents digit greater than SByte MaxValue");
try
{
string sourceStr = "128";
NumberStyles style = NumberStyles.Any;
IFormatProvider provider = new CultureInfo("en-us");
sbyte desSByte = sbyte.Parse(sourceStr, style, provider);
TestLibrary.TestFramework.LogError("N007", "the string represents digit greater than SByte MaxValue but not throw exception");
retVal = false;
}
catch (OverflowException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest5: the NumberStyle value is not a NumberStyle");
try
{
string sourceStr = this.GetInt32(0, 128).ToString();
NumberStyles style = (NumberStyles)(-1);
IFormatProvider provider = new CultureInfo("en-us");
sbyte desSByte = sbyte.Parse(sourceStr, style, provider);
TestLibrary.TestFramework.LogError("N009", "the NumberStyle value is not a NumberStyle but not throw exception");
retVal = false;
}
catch (ArgumentException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N010", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region HelpMethod
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
#endregion
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Core.DataStorageModelsWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using System.Text;
using System.Collections.Generic;
using log4net;
using OpenSim.Framework;
namespace OpenSim.Server.Base
{
public static class ServerUtils
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static string SLAssetTypeToContentType(int assetType)
{
switch (assetType)
{
case 0:
return "image/jp2";
case 1:
return "application/ogg";
case 2:
return "application/x-metaverse-callingcard";
case 3:
return "application/x-metaverse-landmark";
case 5:
return "application/x-metaverse-clothing";
case 6:
return "application/x-metaverse-primitive";
case 7:
return "application/x-metaverse-notecard";
case 8:
return "application/x-metaverse-folder";
case 10:
return "application/x-metaverse-lsl";
case 11:
return "application/x-metaverse-lso";
case 12:
return "image/tga";
case 13:
return "application/x-metaverse-bodypart";
case 17:
return "audio/x-wav";
case 19:
return "image/jpeg";
case 20:
return "application/x-metaverse-animation";
case 21:
return "application/x-metaverse-gesture";
case 22:
return "application/x-metaverse-simstate";
default:
return "application/octet-stream";
}
}
public static byte[] SerializeResult(XmlSerializer xs, object data)
{
MemoryStream ms = new MemoryStream();
XmlTextWriter xw = new XmlTextWriter(ms, Util.UTF8);
xw.Formatting = Formatting.Indented;
xs.Serialize(xw, data);
xw.Flush();
ms.Seek(0, SeekOrigin.Begin);
byte[] ret = ms.GetBuffer();
Array.Resize(ref ret, (int)ms.Length);
return ret;
}
public static T LoadPlugin<T>(string dllName, Object[] args) where T:class
{
string[] parts = dllName.Split(new char[] {':'});
dllName = parts[0];
string className = String.Empty;
if (parts.Length > 1)
className = parts[1];
return LoadPlugin<T>(dllName, className, args);
}
public static T LoadPlugin<T>(string dllName, string className, Object[] args) where T:class
{
string interfaceName = typeof(T).ToString();
try
{
Assembly pluginAssembly = Assembly.LoadFrom(dllName);
foreach (Type pluginType in pluginAssembly.GetTypes())
{
if (pluginType.IsPublic)
{
if (className != String.Empty &&
pluginType.ToString() !=
pluginType.Namespace + "." + className)
continue;
Type typeInterface =
pluginType.GetInterface(interfaceName, true);
if (typeInterface != null)
{
T plug = null;
try
{
plug = (T)Activator.CreateInstance(pluginType,
args);
}
catch (Exception e)
{
if (!(e is System.MissingMethodException))
m_log.ErrorFormat("Error loading plugin from {0}, exception {1}", dllName, e.InnerException);
return null;
}
return plug;
}
}
}
return null;
}
catch (Exception e)
{
m_log.ErrorFormat("Error loading plugin from {0}, exception {1}", dllName, e);
return null;
}
}
public static Dictionary<string, object> ParseQueryString(string query)
{
Dictionary<string, object> result = new Dictionary<string, object>();
string[] terms = query.Split(new char[] {'&'});
if (terms.Length == 0)
return result;
foreach (string t in terms)
{
string[] elems = t.Split(new char[] {'='});
if (elems.Length == 0)
continue;
string name = System.Web.HttpUtility.UrlDecode(elems[0]);
string value = String.Empty;
if (elems.Length > 1)
value = System.Web.HttpUtility.UrlDecode(elems[1]);
if (name.EndsWith("[]"))
{
if (result.ContainsKey(name))
{
if (!(result[name] is List<string>))
continue;
List<string> l = (List<string>)result[name];
l.Add(value);
}
else
{
List<string> newList = new List<string>();
newList.Add(value);
result[name] = newList;
}
}
else
{
if (!result.ContainsKey(name))
result[name] = value;
}
}
return result;
}
public static string BuildQueryString(Dictionary<string, object> data)
{
string qstring = String.Empty;
string part;
foreach (KeyValuePair<string, object> kvp in data)
{
if (kvp.Value is List<string>)
{
List<string> l = (List<String>)kvp.Value;
foreach (string s in l)
{
part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
"[]=" + System.Web.HttpUtility.UrlEncode(s);
if (qstring != String.Empty)
qstring += "&";
qstring += part;
}
}
else
{
if (kvp.Value.ToString() != String.Empty)
{
part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
"=" + System.Web.HttpUtility.UrlEncode(kvp.Value.ToString());
}
else
{
part = System.Web.HttpUtility.UrlEncode(kvp.Key);
}
if (qstring != String.Empty)
qstring += "&";
qstring += part;
}
}
return qstring;
}
public static string BuildXmlResponse(Dictionary<string, object> data)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
BuildXmlData(rootElement, data);
return doc.InnerXml;
}
private static void BuildXmlData(XmlElement parent, Dictionary<string, object> data)
{
foreach (KeyValuePair<string, object> kvp in data)
{
XmlElement elem = parent.OwnerDocument.CreateElement("",
kvp.Key, "");
if (kvp.Value is Dictionary<string, object>)
{
XmlAttribute type = parent.OwnerDocument.CreateAttribute("",
"type", "");
type.Value = "List";
elem.Attributes.Append(type);
BuildXmlData(elem, (Dictionary<string, object>)kvp.Value);
}
else
{
elem.AppendChild(parent.OwnerDocument.CreateTextNode(
kvp.Value.ToString()));
}
parent.AppendChild(elem);
}
}
public static Dictionary<string, object> ParseXmlResponse(string data)
{
//m_log.DebugFormat("[XXX]: received xml string: {0}", data);
Dictionary<string, object> ret = new Dictionary<string, object>();
XmlDocument doc = new XmlDocument();
doc.LoadXml(data);
XmlNodeList rootL = doc.GetElementsByTagName("ServerResponse");
if (rootL.Count != 1)
return ret;
XmlNode rootNode = rootL[0];
ret = ParseElement(rootNode);
return ret;
}
private static Dictionary<string, object> ParseElement(XmlNode element)
{
Dictionary<string, object> ret = new Dictionary<string, object>();
XmlNodeList partL = element.ChildNodes;
foreach (XmlNode part in partL)
{
XmlNode type = part.Attributes.GetNamedItem("type");
if (type == null || type.Value != "List")
{
ret[part.Name] = part.InnerText;
}
else
{
ret[part.Name] = ParseElement(part);
}
}
return ret;
}
}
}
| |
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 MamEstudiosHospitalProvincial class.
/// </summary>
[Serializable]
public partial class MamEstudiosHospitalProvincialCollection : ActiveList<MamEstudiosHospitalProvincial, MamEstudiosHospitalProvincialCollection>
{
public MamEstudiosHospitalProvincialCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>MamEstudiosHospitalProvincialCollection</returns>
public MamEstudiosHospitalProvincialCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
MamEstudiosHospitalProvincial 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 MAM_EstudiosHospitalProvincial table.
/// </summary>
[Serializable]
public partial class MamEstudiosHospitalProvincial : ActiveRecord<MamEstudiosHospitalProvincial>, IActiveRecord
{
#region .ctors and Default Settings
public MamEstudiosHospitalProvincial()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public MamEstudiosHospitalProvincial(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public MamEstudiosHospitalProvincial(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public MamEstudiosHospitalProvincial(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("MAM_EstudiosHospitalProvincial", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdMamografiaHP = new TableSchema.TableColumn(schema);
colvarIdMamografiaHP.ColumnName = "idMamografiaHP";
colvarIdMamografiaHP.DataType = DbType.Int32;
colvarIdMamografiaHP.MaxLength = 0;
colvarIdMamografiaHP.AutoIncrement = true;
colvarIdMamografiaHP.IsNullable = false;
colvarIdMamografiaHP.IsPrimaryKey = true;
colvarIdMamografiaHP.IsForeignKey = false;
colvarIdMamografiaHP.IsReadOnly = false;
colvarIdMamografiaHP.DefaultSetting = @"";
colvarIdMamografiaHP.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdMamografiaHP);
TableSchema.TableColumn colvarIdHistoria = new TableSchema.TableColumn(schema);
colvarIdHistoria.ColumnName = "idHistoria";
colvarIdHistoria.DataType = DbType.Int32;
colvarIdHistoria.MaxLength = 0;
colvarIdHistoria.AutoIncrement = false;
colvarIdHistoria.IsNullable = true;
colvarIdHistoria.IsPrimaryKey = false;
colvarIdHistoria.IsForeignKey = false;
colvarIdHistoria.IsReadOnly = false;
colvarIdHistoria.DefaultSetting = @"";
colvarIdHistoria.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdHistoria);
TableSchema.TableColumn colvarTipoDocumento = new TableSchema.TableColumn(schema);
colvarTipoDocumento.ColumnName = "tipoDocumento";
colvarTipoDocumento.DataType = DbType.AnsiString;
colvarTipoDocumento.MaxLength = 10;
colvarTipoDocumento.AutoIncrement = false;
colvarTipoDocumento.IsNullable = true;
colvarTipoDocumento.IsPrimaryKey = false;
colvarTipoDocumento.IsForeignKey = false;
colvarTipoDocumento.IsReadOnly = false;
colvarTipoDocumento.DefaultSetting = @"";
colvarTipoDocumento.ForeignKeyTableName = "";
schema.Columns.Add(colvarTipoDocumento);
TableSchema.TableColumn colvarDocumento = new TableSchema.TableColumn(schema);
colvarDocumento.ColumnName = "Documento";
colvarDocumento.DataType = DbType.Int32;
colvarDocumento.MaxLength = 0;
colvarDocumento.AutoIncrement = false;
colvarDocumento.IsNullable = true;
colvarDocumento.IsPrimaryKey = false;
colvarDocumento.IsForeignKey = false;
colvarDocumento.IsReadOnly = false;
colvarDocumento.DefaultSetting = @"";
colvarDocumento.ForeignKeyTableName = "";
schema.Columns.Add(colvarDocumento);
TableSchema.TableColumn colvarApellido = new TableSchema.TableColumn(schema);
colvarApellido.ColumnName = "Apellido";
colvarApellido.DataType = DbType.AnsiString;
colvarApellido.MaxLength = 50;
colvarApellido.AutoIncrement = false;
colvarApellido.IsNullable = true;
colvarApellido.IsPrimaryKey = false;
colvarApellido.IsForeignKey = false;
colvarApellido.IsReadOnly = false;
colvarApellido.DefaultSetting = @"";
colvarApellido.ForeignKeyTableName = "";
schema.Columns.Add(colvarApellido);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "Nombre";
colvarNombre.DataType = DbType.AnsiString;
colvarNombre.MaxLength = 50;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = true;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
TableSchema.TableColumn colvarFechaNacimiento = new TableSchema.TableColumn(schema);
colvarFechaNacimiento.ColumnName = "fechaNacimiento";
colvarFechaNacimiento.DataType = DbType.DateTime;
colvarFechaNacimiento.MaxLength = 0;
colvarFechaNacimiento.AutoIncrement = false;
colvarFechaNacimiento.IsNullable = true;
colvarFechaNacimiento.IsPrimaryKey = false;
colvarFechaNacimiento.IsForeignKey = false;
colvarFechaNacimiento.IsReadOnly = false;
colvarFechaNacimiento.DefaultSetting = @"";
colvarFechaNacimiento.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaNacimiento);
TableSchema.TableColumn colvarObraSocial = new TableSchema.TableColumn(schema);
colvarObraSocial.ColumnName = "obraSocial";
colvarObraSocial.DataType = DbType.AnsiString;
colvarObraSocial.MaxLength = 2000;
colvarObraSocial.AutoIncrement = false;
colvarObraSocial.IsNullable = true;
colvarObraSocial.IsPrimaryKey = false;
colvarObraSocial.IsForeignKey = false;
colvarObraSocial.IsReadOnly = false;
colvarObraSocial.DefaultSetting = @"('')";
colvarObraSocial.ForeignKeyTableName = "";
schema.Columns.Add(colvarObraSocial);
TableSchema.TableColumn colvarInformacionContacto = new TableSchema.TableColumn(schema);
colvarInformacionContacto.ColumnName = "informacionContacto";
colvarInformacionContacto.DataType = DbType.AnsiString;
colvarInformacionContacto.MaxLength = 500;
colvarInformacionContacto.AutoIncrement = false;
colvarInformacionContacto.IsNullable = true;
colvarInformacionContacto.IsPrimaryKey = false;
colvarInformacionContacto.IsForeignKey = false;
colvarInformacionContacto.IsReadOnly = false;
colvarInformacionContacto.DefaultSetting = @"";
colvarInformacionContacto.ForeignKeyTableName = "";
schema.Columns.Add(colvarInformacionContacto);
TableSchema.TableColumn colvarDireccion = new TableSchema.TableColumn(schema);
colvarDireccion.ColumnName = "Direccion";
colvarDireccion.DataType = DbType.AnsiString;
colvarDireccion.MaxLength = 500;
colvarDireccion.AutoIncrement = false;
colvarDireccion.IsNullable = true;
colvarDireccion.IsPrimaryKey = false;
colvarDireccion.IsForeignKey = false;
colvarDireccion.IsReadOnly = false;
colvarDireccion.DefaultSetting = @"";
colvarDireccion.ForeignKeyTableName = "";
schema.Columns.Add(colvarDireccion);
TableSchema.TableColumn colvarSolicitudProfesional = new TableSchema.TableColumn(schema);
colvarSolicitudProfesional.ColumnName = "SolicitudProfesional";
colvarSolicitudProfesional.DataType = DbType.Int32;
colvarSolicitudProfesional.MaxLength = 0;
colvarSolicitudProfesional.AutoIncrement = false;
colvarSolicitudProfesional.IsNullable = true;
colvarSolicitudProfesional.IsPrimaryKey = false;
colvarSolicitudProfesional.IsForeignKey = true;
colvarSolicitudProfesional.IsReadOnly = false;
colvarSolicitudProfesional.DefaultSetting = @"";
colvarSolicitudProfesional.ForeignKeyTableName = "Sys_Profesional";
schema.Columns.Add(colvarSolicitudProfesional);
TableSchema.TableColumn colvarSolicitudCentroSalud = new TableSchema.TableColumn(schema);
colvarSolicitudCentroSalud.ColumnName = "SolicitudCentroSalud";
colvarSolicitudCentroSalud.DataType = DbType.Int32;
colvarSolicitudCentroSalud.MaxLength = 0;
colvarSolicitudCentroSalud.AutoIncrement = false;
colvarSolicitudCentroSalud.IsNullable = true;
colvarSolicitudCentroSalud.IsPrimaryKey = false;
colvarSolicitudCentroSalud.IsForeignKey = true;
colvarSolicitudCentroSalud.IsReadOnly = false;
colvarSolicitudCentroSalud.DefaultSetting = @"";
colvarSolicitudCentroSalud.ForeignKeyTableName = "Sys_Efector";
schema.Columns.Add(colvarSolicitudCentroSalud);
TableSchema.TableColumn colvarBiradIzquierdo = new TableSchema.TableColumn(schema);
colvarBiradIzquierdo.ColumnName = "BiradIzquierdo";
colvarBiradIzquierdo.DataType = DbType.Int32;
colvarBiradIzquierdo.MaxLength = 0;
colvarBiradIzquierdo.AutoIncrement = false;
colvarBiradIzquierdo.IsNullable = true;
colvarBiradIzquierdo.IsPrimaryKey = false;
colvarBiradIzquierdo.IsForeignKey = false;
colvarBiradIzquierdo.IsReadOnly = false;
colvarBiradIzquierdo.DefaultSetting = @"";
colvarBiradIzquierdo.ForeignKeyTableName = "";
schema.Columns.Add(colvarBiradIzquierdo);
TableSchema.TableColumn colvarBiradDerecho = new TableSchema.TableColumn(schema);
colvarBiradDerecho.ColumnName = "BiradDerecho";
colvarBiradDerecho.DataType = DbType.Int32;
colvarBiradDerecho.MaxLength = 0;
colvarBiradDerecho.AutoIncrement = false;
colvarBiradDerecho.IsNullable = true;
colvarBiradDerecho.IsPrimaryKey = false;
colvarBiradDerecho.IsForeignKey = false;
colvarBiradDerecho.IsReadOnly = false;
colvarBiradDerecho.DefaultSetting = @"";
colvarBiradDerecho.ForeignKeyTableName = "";
schema.Columns.Add(colvarBiradDerecho);
TableSchema.TableColumn colvarBiradDefinitivo = new TableSchema.TableColumn(schema);
colvarBiradDefinitivo.ColumnName = "BiradDefinitivo";
colvarBiradDefinitivo.DataType = DbType.Int32;
colvarBiradDefinitivo.MaxLength = 0;
colvarBiradDefinitivo.AutoIncrement = false;
colvarBiradDefinitivo.IsNullable = true;
colvarBiradDefinitivo.IsPrimaryKey = false;
colvarBiradDefinitivo.IsForeignKey = false;
colvarBiradDefinitivo.IsReadOnly = false;
colvarBiradDefinitivo.DefaultSetting = @"";
colvarBiradDefinitivo.ForeignKeyTableName = "";
schema.Columns.Add(colvarBiradDefinitivo);
TableSchema.TableColumn colvarFechaPlaca = new TableSchema.TableColumn(schema);
colvarFechaPlaca.ColumnName = "fechaPlaca";
colvarFechaPlaca.DataType = DbType.DateTime;
colvarFechaPlaca.MaxLength = 0;
colvarFechaPlaca.AutoIncrement = false;
colvarFechaPlaca.IsNullable = true;
colvarFechaPlaca.IsPrimaryKey = false;
colvarFechaPlaca.IsForeignKey = false;
colvarFechaPlaca.IsReadOnly = false;
colvarFechaPlaca.DefaultSetting = @"";
colvarFechaPlaca.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaPlaca);
TableSchema.TableColumn colvarFechaInforme = new TableSchema.TableColumn(schema);
colvarFechaInforme.ColumnName = "fechaInforme";
colvarFechaInforme.DataType = DbType.DateTime;
colvarFechaInforme.MaxLength = 0;
colvarFechaInforme.AutoIncrement = false;
colvarFechaInforme.IsNullable = true;
colvarFechaInforme.IsPrimaryKey = false;
colvarFechaInforme.IsForeignKey = false;
colvarFechaInforme.IsReadOnly = false;
colvarFechaInforme.DefaultSetting = @"";
colvarFechaInforme.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaInforme);
TableSchema.TableColumn colvarInforme = new TableSchema.TableColumn(schema);
colvarInforme.ColumnName = "informe";
colvarInforme.DataType = DbType.AnsiString;
colvarInforme.MaxLength = 5000;
colvarInforme.AutoIncrement = false;
colvarInforme.IsNullable = true;
colvarInforme.IsPrimaryKey = false;
colvarInforme.IsForeignKey = false;
colvarInforme.IsReadOnly = false;
colvarInforme.DefaultSetting = @"";
colvarInforme.ForeignKeyTableName = "";
schema.Columns.Add(colvarInforme);
TableSchema.TableColumn colvarIdMotivo = new TableSchema.TableColumn(schema);
colvarIdMotivo.ColumnName = "idMotivo";
colvarIdMotivo.DataType = DbType.Int32;
colvarIdMotivo.MaxLength = 0;
colvarIdMotivo.AutoIncrement = false;
colvarIdMotivo.IsNullable = true;
colvarIdMotivo.IsPrimaryKey = false;
colvarIdMotivo.IsForeignKey = false;
colvarIdMotivo.IsReadOnly = false;
colvarIdMotivo.DefaultSetting = @"";
colvarIdMotivo.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdMotivo);
TableSchema.TableColumn colvarMotivo = new TableSchema.TableColumn(schema);
colvarMotivo.ColumnName = "motivo";
colvarMotivo.DataType = DbType.AnsiString;
colvarMotivo.MaxLength = 100;
colvarMotivo.AutoIncrement = false;
colvarMotivo.IsNullable = true;
colvarMotivo.IsPrimaryKey = false;
colvarMotivo.IsForeignKey = false;
colvarMotivo.IsReadOnly = false;
colvarMotivo.DefaultSetting = @"";
colvarMotivo.ForeignKeyTableName = "";
schema.Columns.Add(colvarMotivo);
TableSchema.TableColumn colvarIdMotivoSitam = new TableSchema.TableColumn(schema);
colvarIdMotivoSitam.ColumnName = "idMotivoSitam";
colvarIdMotivoSitam.DataType = DbType.Int32;
colvarIdMotivoSitam.MaxLength = 0;
colvarIdMotivoSitam.AutoIncrement = false;
colvarIdMotivoSitam.IsNullable = true;
colvarIdMotivoSitam.IsPrimaryKey = false;
colvarIdMotivoSitam.IsForeignKey = false;
colvarIdMotivoSitam.IsReadOnly = false;
colvarIdMotivoSitam.DefaultSetting = @"";
colvarIdMotivoSitam.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdMotivoSitam);
TableSchema.TableColumn colvarIdTipoEstudio = new TableSchema.TableColumn(schema);
colvarIdTipoEstudio.ColumnName = "idTipoEstudio";
colvarIdTipoEstudio.DataType = DbType.Int32;
colvarIdTipoEstudio.MaxLength = 0;
colvarIdTipoEstudio.AutoIncrement = false;
colvarIdTipoEstudio.IsNullable = true;
colvarIdTipoEstudio.IsPrimaryKey = false;
colvarIdTipoEstudio.IsForeignKey = true;
colvarIdTipoEstudio.IsReadOnly = false;
colvarIdTipoEstudio.DefaultSetting = @"";
colvarIdTipoEstudio.ForeignKeyTableName = "MAM_TipoEstudio";
schema.Columns.Add(colvarIdTipoEstudio);
TableSchema.TableColumn colvarIdTipoEstudioSitam = new TableSchema.TableColumn(schema);
colvarIdTipoEstudioSitam.ColumnName = "idTipoEstudioSitam";
colvarIdTipoEstudioSitam.DataType = DbType.Int32;
colvarIdTipoEstudioSitam.MaxLength = 0;
colvarIdTipoEstudioSitam.AutoIncrement = false;
colvarIdTipoEstudioSitam.IsNullable = true;
colvarIdTipoEstudioSitam.IsPrimaryKey = false;
colvarIdTipoEstudioSitam.IsForeignKey = false;
colvarIdTipoEstudioSitam.IsReadOnly = false;
colvarIdTipoEstudioSitam.DefaultSetting = @"";
colvarIdTipoEstudioSitam.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdTipoEstudioSitam);
TableSchema.TableColumn colvarObservaciones = new TableSchema.TableColumn(schema);
colvarObservaciones.ColumnName = "observaciones";
colvarObservaciones.DataType = DbType.AnsiString;
colvarObservaciones.MaxLength = 500;
colvarObservaciones.AutoIncrement = false;
colvarObservaciones.IsNullable = true;
colvarObservaciones.IsPrimaryKey = false;
colvarObservaciones.IsForeignKey = false;
colvarObservaciones.IsReadOnly = false;
colvarObservaciones.DefaultSetting = @"";
colvarObservaciones.ForeignKeyTableName = "";
schema.Columns.Add(colvarObservaciones);
TableSchema.TableColumn colvarPasadoSips = new TableSchema.TableColumn(schema);
colvarPasadoSips.ColumnName = "pasadoSips";
colvarPasadoSips.DataType = DbType.Boolean;
colvarPasadoSips.MaxLength = 0;
colvarPasadoSips.AutoIncrement = false;
colvarPasadoSips.IsNullable = false;
colvarPasadoSips.IsPrimaryKey = false;
colvarPasadoSips.IsForeignKey = false;
colvarPasadoSips.IsReadOnly = false;
colvarPasadoSips.DefaultSetting = @"((0))";
colvarPasadoSips.ForeignKeyTableName = "";
schema.Columns.Add(colvarPasadoSips);
TableSchema.TableColumn colvarActivo = new TableSchema.TableColumn(schema);
colvarActivo.ColumnName = "activo";
colvarActivo.DataType = DbType.Boolean;
colvarActivo.MaxLength = 0;
colvarActivo.AutoIncrement = false;
colvarActivo.IsNullable = false;
colvarActivo.IsPrimaryKey = false;
colvarActivo.IsForeignKey = false;
colvarActivo.IsReadOnly = false;
colvarActivo.DefaultSetting = @"((1))";
colvarActivo.ForeignKeyTableName = "";
schema.Columns.Add(colvarActivo);
TableSchema.TableColumn colvarCreatedBy = new TableSchema.TableColumn(schema);
colvarCreatedBy.ColumnName = "CreatedBy";
colvarCreatedBy.DataType = DbType.AnsiString;
colvarCreatedBy.MaxLength = 50;
colvarCreatedBy.AutoIncrement = false;
colvarCreatedBy.IsNullable = true;
colvarCreatedBy.IsPrimaryKey = false;
colvarCreatedBy.IsForeignKey = false;
colvarCreatedBy.IsReadOnly = false;
colvarCreatedBy.DefaultSetting = @"";
colvarCreatedBy.ForeignKeyTableName = "";
schema.Columns.Add(colvarCreatedBy);
TableSchema.TableColumn colvarCreatedOn = new TableSchema.TableColumn(schema);
colvarCreatedOn.ColumnName = "CreatedOn";
colvarCreatedOn.DataType = DbType.DateTime;
colvarCreatedOn.MaxLength = 0;
colvarCreatedOn.AutoIncrement = false;
colvarCreatedOn.IsNullable = true;
colvarCreatedOn.IsPrimaryKey = false;
colvarCreatedOn.IsForeignKey = false;
colvarCreatedOn.IsReadOnly = false;
colvarCreatedOn.DefaultSetting = @"";
colvarCreatedOn.ForeignKeyTableName = "";
schema.Columns.Add(colvarCreatedOn);
TableSchema.TableColumn colvarModifiedBy = new TableSchema.TableColumn(schema);
colvarModifiedBy.ColumnName = "ModifiedBy";
colvarModifiedBy.DataType = DbType.AnsiString;
colvarModifiedBy.MaxLength = 50;
colvarModifiedBy.AutoIncrement = false;
colvarModifiedBy.IsNullable = true;
colvarModifiedBy.IsPrimaryKey = false;
colvarModifiedBy.IsForeignKey = false;
colvarModifiedBy.IsReadOnly = false;
colvarModifiedBy.DefaultSetting = @"";
colvarModifiedBy.ForeignKeyTableName = "";
schema.Columns.Add(colvarModifiedBy);
TableSchema.TableColumn colvarModifiedOn = new TableSchema.TableColumn(schema);
colvarModifiedOn.ColumnName = "ModifiedOn";
colvarModifiedOn.DataType = DbType.DateTime;
colvarModifiedOn.MaxLength = 0;
colvarModifiedOn.AutoIncrement = false;
colvarModifiedOn.IsNullable = true;
colvarModifiedOn.IsPrimaryKey = false;
colvarModifiedOn.IsForeignKey = false;
colvarModifiedOn.IsReadOnly = false;
colvarModifiedOn.DefaultSetting = @"";
colvarModifiedOn.ForeignKeyTableName = "";
schema.Columns.Add(colvarModifiedOn);
TableSchema.TableColumn colvarInformeProfesional = new TableSchema.TableColumn(schema);
colvarInformeProfesional.ColumnName = "informeProfesional";
colvarInformeProfesional.DataType = DbType.Int32;
colvarInformeProfesional.MaxLength = 0;
colvarInformeProfesional.AutoIncrement = false;
colvarInformeProfesional.IsNullable = true;
colvarInformeProfesional.IsPrimaryKey = false;
colvarInformeProfesional.IsForeignKey = false;
colvarInformeProfesional.IsReadOnly = false;
colvarInformeProfesional.DefaultSetting = @"((0))";
colvarInformeProfesional.ForeignKeyTableName = "";
schema.Columns.Add(colvarInformeProfesional);
TableSchema.TableColumn colvarLocalidad = new TableSchema.TableColumn(schema);
colvarLocalidad.ColumnName = "localidad";
colvarLocalidad.DataType = DbType.AnsiString;
colvarLocalidad.MaxLength = 100;
colvarLocalidad.AutoIncrement = false;
colvarLocalidad.IsNullable = true;
colvarLocalidad.IsPrimaryKey = false;
colvarLocalidad.IsForeignKey = false;
colvarLocalidad.IsReadOnly = false;
colvarLocalidad.DefaultSetting = @"";
colvarLocalidad.ForeignKeyTableName = "";
schema.Columns.Add(colvarLocalidad);
TableSchema.TableColumn colvarInformacionCelular = new TableSchema.TableColumn(schema);
colvarInformacionCelular.ColumnName = "informacionCelular";
colvarInformacionCelular.DataType = DbType.AnsiString;
colvarInformacionCelular.MaxLength = 20;
colvarInformacionCelular.AutoIncrement = false;
colvarInformacionCelular.IsNullable = true;
colvarInformacionCelular.IsPrimaryKey = false;
colvarInformacionCelular.IsForeignKey = false;
colvarInformacionCelular.IsReadOnly = false;
colvarInformacionCelular.DefaultSetting = @"";
colvarInformacionCelular.ForeignKeyTableName = "";
schema.Columns.Add(colvarInformacionCelular);
TableSchema.TableColumn colvarSolicitudProfesionalSSS = new TableSchema.TableColumn(schema);
colvarSolicitudProfesionalSSS.ColumnName = "solicitudProfesionalSSS";
colvarSolicitudProfesionalSSS.DataType = DbType.Int32;
colvarSolicitudProfesionalSSS.MaxLength = 0;
colvarSolicitudProfesionalSSS.AutoIncrement = false;
colvarSolicitudProfesionalSSS.IsNullable = true;
colvarSolicitudProfesionalSSS.IsPrimaryKey = false;
colvarSolicitudProfesionalSSS.IsForeignKey = false;
colvarSolicitudProfesionalSSS.IsReadOnly = false;
colvarSolicitudProfesionalSSS.DefaultSetting = @"((0))";
colvarSolicitudProfesionalSSS.ForeignKeyTableName = "";
schema.Columns.Add(colvarSolicitudProfesionalSSS);
TableSchema.TableColumn colvarSolicitudProfesionalDNI = new TableSchema.TableColumn(schema);
colvarSolicitudProfesionalDNI.ColumnName = "solicitudProfesionalDNI";
colvarSolicitudProfesionalDNI.DataType = DbType.Int32;
colvarSolicitudProfesionalDNI.MaxLength = 0;
colvarSolicitudProfesionalDNI.AutoIncrement = false;
colvarSolicitudProfesionalDNI.IsNullable = true;
colvarSolicitudProfesionalDNI.IsPrimaryKey = false;
colvarSolicitudProfesionalDNI.IsForeignKey = false;
colvarSolicitudProfesionalDNI.IsReadOnly = false;
colvarSolicitudProfesionalDNI.DefaultSetting = @"((0))";
colvarSolicitudProfesionalDNI.ForeignKeyTableName = "";
schema.Columns.Add(colvarSolicitudProfesionalDNI);
TableSchema.TableColumn colvarInformeProfesionalSSS = new TableSchema.TableColumn(schema);
colvarInformeProfesionalSSS.ColumnName = "informeProfesionalSSS";
colvarInformeProfesionalSSS.DataType = DbType.Int32;
colvarInformeProfesionalSSS.MaxLength = 0;
colvarInformeProfesionalSSS.AutoIncrement = false;
colvarInformeProfesionalSSS.IsNullable = true;
colvarInformeProfesionalSSS.IsPrimaryKey = false;
colvarInformeProfesionalSSS.IsForeignKey = false;
colvarInformeProfesionalSSS.IsReadOnly = false;
colvarInformeProfesionalSSS.DefaultSetting = @"((0))";
colvarInformeProfesionalSSS.ForeignKeyTableName = "";
schema.Columns.Add(colvarInformeProfesionalSSS);
TableSchema.TableColumn colvarInformeProfesionalDNI = new TableSchema.TableColumn(schema);
colvarInformeProfesionalDNI.ColumnName = "informeProfesionalDNI";
colvarInformeProfesionalDNI.DataType = DbType.Int32;
colvarInformeProfesionalDNI.MaxLength = 0;
colvarInformeProfesionalDNI.AutoIncrement = false;
colvarInformeProfesionalDNI.IsNullable = true;
colvarInformeProfesionalDNI.IsPrimaryKey = false;
colvarInformeProfesionalDNI.IsForeignKey = false;
colvarInformeProfesionalDNI.IsReadOnly = false;
colvarInformeProfesionalDNI.DefaultSetting = @"((0))";
colvarInformeProfesionalDNI.ForeignKeyTableName = "";
schema.Columns.Add(colvarInformeProfesionalDNI);
TableSchema.TableColumn colvarEquipo = new TableSchema.TableColumn(schema);
colvarEquipo.ColumnName = "equipo";
colvarEquipo.DataType = DbType.AnsiString;
colvarEquipo.MaxLength = 50;
colvarEquipo.AutoIncrement = false;
colvarEquipo.IsNullable = true;
colvarEquipo.IsPrimaryKey = false;
colvarEquipo.IsForeignKey = false;
colvarEquipo.IsReadOnly = false;
colvarEquipo.DefaultSetting = @"('')";
colvarEquipo.ForeignKeyTableName = "";
schema.Columns.Add(colvarEquipo);
TableSchema.TableColumn colvarMotivoConsulta = new TableSchema.TableColumn(schema);
colvarMotivoConsulta.ColumnName = "motivoConsulta";
colvarMotivoConsulta.DataType = DbType.AnsiString;
colvarMotivoConsulta.MaxLength = 100;
colvarMotivoConsulta.AutoIncrement = false;
colvarMotivoConsulta.IsNullable = true;
colvarMotivoConsulta.IsPrimaryKey = false;
colvarMotivoConsulta.IsForeignKey = false;
colvarMotivoConsulta.IsReadOnly = false;
colvarMotivoConsulta.DefaultSetting = @"('')";
colvarMotivoConsulta.ForeignKeyTableName = "";
schema.Columns.Add(colvarMotivoConsulta);
TableSchema.TableColumn colvarProtocolo = new TableSchema.TableColumn(schema);
colvarProtocolo.ColumnName = "protocolo";
colvarProtocolo.DataType = DbType.Int32;
colvarProtocolo.MaxLength = 0;
colvarProtocolo.AutoIncrement = false;
colvarProtocolo.IsNullable = true;
colvarProtocolo.IsPrimaryKey = false;
colvarProtocolo.IsForeignKey = false;
colvarProtocolo.IsReadOnly = false;
colvarProtocolo.DefaultSetting = @"((0))";
colvarProtocolo.ForeignKeyTableName = "";
schema.Columns.Add(colvarProtocolo);
TableSchema.TableColumn colvarProtocoloPrefijo = new TableSchema.TableColumn(schema);
colvarProtocoloPrefijo.ColumnName = "protocoloPrefijo";
colvarProtocoloPrefijo.DataType = DbType.AnsiStringFixedLength;
colvarProtocoloPrefijo.MaxLength = 10;
colvarProtocoloPrefijo.AutoIncrement = false;
colvarProtocoloPrefijo.IsNullable = true;
colvarProtocoloPrefijo.IsPrimaryKey = false;
colvarProtocoloPrefijo.IsForeignKey = false;
colvarProtocoloPrefijo.IsReadOnly = false;
colvarProtocoloPrefijo.DefaultSetting = @"('')";
colvarProtocoloPrefijo.ForeignKeyTableName = "";
schema.Columns.Add(colvarProtocoloPrefijo);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("MAM_EstudiosHospitalProvincial",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdMamografiaHP")]
[Bindable(true)]
public int IdMamografiaHP
{
get { return GetColumnValue<int>(Columns.IdMamografiaHP); }
set { SetColumnValue(Columns.IdMamografiaHP, value); }
}
[XmlAttribute("IdHistoria")]
[Bindable(true)]
public int? IdHistoria
{
get { return GetColumnValue<int?>(Columns.IdHistoria); }
set { SetColumnValue(Columns.IdHistoria, value); }
}
[XmlAttribute("TipoDocumento")]
[Bindable(true)]
public string TipoDocumento
{
get { return GetColumnValue<string>(Columns.TipoDocumento); }
set { SetColumnValue(Columns.TipoDocumento, value); }
}
[XmlAttribute("Documento")]
[Bindable(true)]
public int? Documento
{
get { return GetColumnValue<int?>(Columns.Documento); }
set { SetColumnValue(Columns.Documento, value); }
}
[XmlAttribute("Apellido")]
[Bindable(true)]
public string Apellido
{
get { return GetColumnValue<string>(Columns.Apellido); }
set { SetColumnValue(Columns.Apellido, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
[XmlAttribute("FechaNacimiento")]
[Bindable(true)]
public DateTime? FechaNacimiento
{
get { return GetColumnValue<DateTime?>(Columns.FechaNacimiento); }
set { SetColumnValue(Columns.FechaNacimiento, value); }
}
[XmlAttribute("ObraSocial")]
[Bindable(true)]
public string ObraSocial
{
get { return GetColumnValue<string>(Columns.ObraSocial); }
set { SetColumnValue(Columns.ObraSocial, value); }
}
[XmlAttribute("InformacionContacto")]
[Bindable(true)]
public string InformacionContacto
{
get { return GetColumnValue<string>(Columns.InformacionContacto); }
set { SetColumnValue(Columns.InformacionContacto, value); }
}
[XmlAttribute("Direccion")]
[Bindable(true)]
public string Direccion
{
get { return GetColumnValue<string>(Columns.Direccion); }
set { SetColumnValue(Columns.Direccion, value); }
}
[XmlAttribute("SolicitudProfesional")]
[Bindable(true)]
public int? SolicitudProfesional
{
get { return GetColumnValue<int?>(Columns.SolicitudProfesional); }
set { SetColumnValue(Columns.SolicitudProfesional, value); }
}
[XmlAttribute("SolicitudCentroSalud")]
[Bindable(true)]
public int? SolicitudCentroSalud
{
get { return GetColumnValue<int?>(Columns.SolicitudCentroSalud); }
set { SetColumnValue(Columns.SolicitudCentroSalud, value); }
}
[XmlAttribute("BiradIzquierdo")]
[Bindable(true)]
public int? BiradIzquierdo
{
get { return GetColumnValue<int?>(Columns.BiradIzquierdo); }
set { SetColumnValue(Columns.BiradIzquierdo, value); }
}
[XmlAttribute("BiradDerecho")]
[Bindable(true)]
public int? BiradDerecho
{
get { return GetColumnValue<int?>(Columns.BiradDerecho); }
set { SetColumnValue(Columns.BiradDerecho, value); }
}
[XmlAttribute("BiradDefinitivo")]
[Bindable(true)]
public int? BiradDefinitivo
{
get { return GetColumnValue<int?>(Columns.BiradDefinitivo); }
set { SetColumnValue(Columns.BiradDefinitivo, value); }
}
[XmlAttribute("FechaPlaca")]
[Bindable(true)]
public DateTime? FechaPlaca
{
get { return GetColumnValue<DateTime?>(Columns.FechaPlaca); }
set { SetColumnValue(Columns.FechaPlaca, value); }
}
[XmlAttribute("FechaInforme")]
[Bindable(true)]
public DateTime? FechaInforme
{
get { return GetColumnValue<DateTime?>(Columns.FechaInforme); }
set { SetColumnValue(Columns.FechaInforme, value); }
}
[XmlAttribute("Informe")]
[Bindable(true)]
public string Informe
{
get { return GetColumnValue<string>(Columns.Informe); }
set { SetColumnValue(Columns.Informe, value); }
}
[XmlAttribute("IdMotivo")]
[Bindable(true)]
public int? IdMotivo
{
get { return GetColumnValue<int?>(Columns.IdMotivo); }
set { SetColumnValue(Columns.IdMotivo, value); }
}
[XmlAttribute("Motivo")]
[Bindable(true)]
public string Motivo
{
get { return GetColumnValue<string>(Columns.Motivo); }
set { SetColumnValue(Columns.Motivo, value); }
}
[XmlAttribute("IdMotivoSitam")]
[Bindable(true)]
public int? IdMotivoSitam
{
get { return GetColumnValue<int?>(Columns.IdMotivoSitam); }
set { SetColumnValue(Columns.IdMotivoSitam, value); }
}
[XmlAttribute("IdTipoEstudio")]
[Bindable(true)]
public int? IdTipoEstudio
{
get { return GetColumnValue<int?>(Columns.IdTipoEstudio); }
set { SetColumnValue(Columns.IdTipoEstudio, value); }
}
[XmlAttribute("IdTipoEstudioSitam")]
[Bindable(true)]
public int? IdTipoEstudioSitam
{
get { return GetColumnValue<int?>(Columns.IdTipoEstudioSitam); }
set { SetColumnValue(Columns.IdTipoEstudioSitam, value); }
}
[XmlAttribute("Observaciones")]
[Bindable(true)]
public string Observaciones
{
get { return GetColumnValue<string>(Columns.Observaciones); }
set { SetColumnValue(Columns.Observaciones, value); }
}
[XmlAttribute("PasadoSips")]
[Bindable(true)]
public bool PasadoSips
{
get { return GetColumnValue<bool>(Columns.PasadoSips); }
set { SetColumnValue(Columns.PasadoSips, value); }
}
[XmlAttribute("Activo")]
[Bindable(true)]
public bool Activo
{
get { return GetColumnValue<bool>(Columns.Activo); }
set { SetColumnValue(Columns.Activo, value); }
}
[XmlAttribute("CreatedBy")]
[Bindable(true)]
public string CreatedBy
{
get { return GetColumnValue<string>(Columns.CreatedBy); }
set { SetColumnValue(Columns.CreatedBy, value); }
}
[XmlAttribute("CreatedOn")]
[Bindable(true)]
public DateTime? CreatedOn
{
get { return GetColumnValue<DateTime?>(Columns.CreatedOn); }
set { SetColumnValue(Columns.CreatedOn, value); }
}
[XmlAttribute("ModifiedBy")]
[Bindable(true)]
public string ModifiedBy
{
get { return GetColumnValue<string>(Columns.ModifiedBy); }
set { SetColumnValue(Columns.ModifiedBy, value); }
}
[XmlAttribute("ModifiedOn")]
[Bindable(true)]
public DateTime? ModifiedOn
{
get { return GetColumnValue<DateTime?>(Columns.ModifiedOn); }
set { SetColumnValue(Columns.ModifiedOn, value); }
}
[XmlAttribute("InformeProfesional")]
[Bindable(true)]
public int? InformeProfesional
{
get { return GetColumnValue<int?>(Columns.InformeProfesional); }
set { SetColumnValue(Columns.InformeProfesional, value); }
}
[XmlAttribute("Localidad")]
[Bindable(true)]
public string Localidad
{
get { return GetColumnValue<string>(Columns.Localidad); }
set { SetColumnValue(Columns.Localidad, value); }
}
[XmlAttribute("InformacionCelular")]
[Bindable(true)]
public string InformacionCelular
{
get { return GetColumnValue<string>(Columns.InformacionCelular); }
set { SetColumnValue(Columns.InformacionCelular, value); }
}
[XmlAttribute("SolicitudProfesionalSSS")]
[Bindable(true)]
public int? SolicitudProfesionalSSS
{
get { return GetColumnValue<int?>(Columns.SolicitudProfesionalSSS); }
set { SetColumnValue(Columns.SolicitudProfesionalSSS, value); }
}
[XmlAttribute("SolicitudProfesionalDNI")]
[Bindable(true)]
public int? SolicitudProfesionalDNI
{
get { return GetColumnValue<int?>(Columns.SolicitudProfesionalDNI); }
set { SetColumnValue(Columns.SolicitudProfesionalDNI, value); }
}
[XmlAttribute("InformeProfesionalSSS")]
[Bindable(true)]
public int? InformeProfesionalSSS
{
get { return GetColumnValue<int?>(Columns.InformeProfesionalSSS); }
set { SetColumnValue(Columns.InformeProfesionalSSS, value); }
}
[XmlAttribute("InformeProfesionalDNI")]
[Bindable(true)]
public int? InformeProfesionalDNI
{
get { return GetColumnValue<int?>(Columns.InformeProfesionalDNI); }
set { SetColumnValue(Columns.InformeProfesionalDNI, value); }
}
[XmlAttribute("Equipo")]
[Bindable(true)]
public string Equipo
{
get { return GetColumnValue<string>(Columns.Equipo); }
set { SetColumnValue(Columns.Equipo, value); }
}
[XmlAttribute("MotivoConsulta")]
[Bindable(true)]
public string MotivoConsulta
{
get { return GetColumnValue<string>(Columns.MotivoConsulta); }
set { SetColumnValue(Columns.MotivoConsulta, value); }
}
[XmlAttribute("Protocolo")]
[Bindable(true)]
public int? Protocolo
{
get { return GetColumnValue<int?>(Columns.Protocolo); }
set { SetColumnValue(Columns.Protocolo, value); }
}
[XmlAttribute("ProtocoloPrefijo")]
[Bindable(true)]
public string ProtocoloPrefijo
{
get { return GetColumnValue<string>(Columns.ProtocoloPrefijo); }
set { SetColumnValue(Columns.ProtocoloPrefijo, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a SysEfector ActiveRecord object related to this MamEstudiosHospitalProvincial
///
/// </summary>
public DalSic.SysEfector SysEfector
{
get { return DalSic.SysEfector.FetchByID(this.SolicitudCentroSalud); }
set { SetColumnValue("SolicitudCentroSalud", value.IdEfector); }
}
/// <summary>
/// Returns a MamTipoEstudio ActiveRecord object related to this MamEstudiosHospitalProvincial
///
/// </summary>
public DalSic.MamTipoEstudio MamTipoEstudio
{
get { return DalSic.MamTipoEstudio.FetchByID(this.IdTipoEstudio); }
set { SetColumnValue("idTipoEstudio", value.IdTipoEstudio); }
}
/// <summary>
/// Returns a SysProfesional ActiveRecord object related to this MamEstudiosHospitalProvincial
///
/// </summary>
public DalSic.SysProfesional SysProfesional
{
get { return DalSic.SysProfesional.FetchByID(this.SolicitudProfesional); }
set { SetColumnValue("SolicitudProfesional", value.IdProfesional); }
}
#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? varIdHistoria,string varTipoDocumento,int? varDocumento,string varApellido,string varNombre,DateTime? varFechaNacimiento,string varObraSocial,string varInformacionContacto,string varDireccion,int? varSolicitudProfesional,int? varSolicitudCentroSalud,int? varBiradIzquierdo,int? varBiradDerecho,int? varBiradDefinitivo,DateTime? varFechaPlaca,DateTime? varFechaInforme,string varInforme,int? varIdMotivo,string varMotivo,int? varIdMotivoSitam,int? varIdTipoEstudio,int? varIdTipoEstudioSitam,string varObservaciones,bool varPasadoSips,bool varActivo,string varCreatedBy,DateTime? varCreatedOn,string varModifiedBy,DateTime? varModifiedOn,int? varInformeProfesional,string varLocalidad,string varInformacionCelular,int? varSolicitudProfesionalSSS,int? varSolicitudProfesionalDNI,int? varInformeProfesionalSSS,int? varInformeProfesionalDNI,string varEquipo,string varMotivoConsulta,int? varProtocolo,string varProtocoloPrefijo)
{
MamEstudiosHospitalProvincial item = new MamEstudiosHospitalProvincial();
item.IdHistoria = varIdHistoria;
item.TipoDocumento = varTipoDocumento;
item.Documento = varDocumento;
item.Apellido = varApellido;
item.Nombre = varNombre;
item.FechaNacimiento = varFechaNacimiento;
item.ObraSocial = varObraSocial;
item.InformacionContacto = varInformacionContacto;
item.Direccion = varDireccion;
item.SolicitudProfesional = varSolicitudProfesional;
item.SolicitudCentroSalud = varSolicitudCentroSalud;
item.BiradIzquierdo = varBiradIzquierdo;
item.BiradDerecho = varBiradDerecho;
item.BiradDefinitivo = varBiradDefinitivo;
item.FechaPlaca = varFechaPlaca;
item.FechaInforme = varFechaInforme;
item.Informe = varInforme;
item.IdMotivo = varIdMotivo;
item.Motivo = varMotivo;
item.IdMotivoSitam = varIdMotivoSitam;
item.IdTipoEstudio = varIdTipoEstudio;
item.IdTipoEstudioSitam = varIdTipoEstudioSitam;
item.Observaciones = varObservaciones;
item.PasadoSips = varPasadoSips;
item.Activo = varActivo;
item.CreatedBy = varCreatedBy;
item.CreatedOn = varCreatedOn;
item.ModifiedBy = varModifiedBy;
item.ModifiedOn = varModifiedOn;
item.InformeProfesional = varInformeProfesional;
item.Localidad = varLocalidad;
item.InformacionCelular = varInformacionCelular;
item.SolicitudProfesionalSSS = varSolicitudProfesionalSSS;
item.SolicitudProfesionalDNI = varSolicitudProfesionalDNI;
item.InformeProfesionalSSS = varInformeProfesionalSSS;
item.InformeProfesionalDNI = varInformeProfesionalDNI;
item.Equipo = varEquipo;
item.MotivoConsulta = varMotivoConsulta;
item.Protocolo = varProtocolo;
item.ProtocoloPrefijo = varProtocoloPrefijo;
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 varIdMamografiaHP,int? varIdHistoria,string varTipoDocumento,int? varDocumento,string varApellido,string varNombre,DateTime? varFechaNacimiento,string varObraSocial,string varInformacionContacto,string varDireccion,int? varSolicitudProfesional,int? varSolicitudCentroSalud,int? varBiradIzquierdo,int? varBiradDerecho,int? varBiradDefinitivo,DateTime? varFechaPlaca,DateTime? varFechaInforme,string varInforme,int? varIdMotivo,string varMotivo,int? varIdMotivoSitam,int? varIdTipoEstudio,int? varIdTipoEstudioSitam,string varObservaciones,bool varPasadoSips,bool varActivo,string varCreatedBy,DateTime? varCreatedOn,string varModifiedBy,DateTime? varModifiedOn,int? varInformeProfesional,string varLocalidad,string varInformacionCelular,int? varSolicitudProfesionalSSS,int? varSolicitudProfesionalDNI,int? varInformeProfesionalSSS,int? varInformeProfesionalDNI,string varEquipo,string varMotivoConsulta,int? varProtocolo,string varProtocoloPrefijo)
{
MamEstudiosHospitalProvincial item = new MamEstudiosHospitalProvincial();
item.IdMamografiaHP = varIdMamografiaHP;
item.IdHistoria = varIdHistoria;
item.TipoDocumento = varTipoDocumento;
item.Documento = varDocumento;
item.Apellido = varApellido;
item.Nombre = varNombre;
item.FechaNacimiento = varFechaNacimiento;
item.ObraSocial = varObraSocial;
item.InformacionContacto = varInformacionContacto;
item.Direccion = varDireccion;
item.SolicitudProfesional = varSolicitudProfesional;
item.SolicitudCentroSalud = varSolicitudCentroSalud;
item.BiradIzquierdo = varBiradIzquierdo;
item.BiradDerecho = varBiradDerecho;
item.BiradDefinitivo = varBiradDefinitivo;
item.FechaPlaca = varFechaPlaca;
item.FechaInforme = varFechaInforme;
item.Informe = varInforme;
item.IdMotivo = varIdMotivo;
item.Motivo = varMotivo;
item.IdMotivoSitam = varIdMotivoSitam;
item.IdTipoEstudio = varIdTipoEstudio;
item.IdTipoEstudioSitam = varIdTipoEstudioSitam;
item.Observaciones = varObservaciones;
item.PasadoSips = varPasadoSips;
item.Activo = varActivo;
item.CreatedBy = varCreatedBy;
item.CreatedOn = varCreatedOn;
item.ModifiedBy = varModifiedBy;
item.ModifiedOn = varModifiedOn;
item.InformeProfesional = varInformeProfesional;
item.Localidad = varLocalidad;
item.InformacionCelular = varInformacionCelular;
item.SolicitudProfesionalSSS = varSolicitudProfesionalSSS;
item.SolicitudProfesionalDNI = varSolicitudProfesionalDNI;
item.InformeProfesionalSSS = varInformeProfesionalSSS;
item.InformeProfesionalDNI = varInformeProfesionalDNI;
item.Equipo = varEquipo;
item.MotivoConsulta = varMotivoConsulta;
item.Protocolo = varProtocolo;
item.ProtocoloPrefijo = varProtocoloPrefijo;
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 IdMamografiaHPColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdHistoriaColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn TipoDocumentoColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn DocumentoColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn ApellidoColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn FechaNacimientoColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn ObraSocialColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn InformacionContactoColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn DireccionColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn SolicitudProfesionalColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn SolicitudCentroSaludColumn
{
get { return Schema.Columns[11]; }
}
public static TableSchema.TableColumn BiradIzquierdoColumn
{
get { return Schema.Columns[12]; }
}
public static TableSchema.TableColumn BiradDerechoColumn
{
get { return Schema.Columns[13]; }
}
public static TableSchema.TableColumn BiradDefinitivoColumn
{
get { return Schema.Columns[14]; }
}
public static TableSchema.TableColumn FechaPlacaColumn
{
get { return Schema.Columns[15]; }
}
public static TableSchema.TableColumn FechaInformeColumn
{
get { return Schema.Columns[16]; }
}
public static TableSchema.TableColumn InformeColumn
{
get { return Schema.Columns[17]; }
}
public static TableSchema.TableColumn IdMotivoColumn
{
get { return Schema.Columns[18]; }
}
public static TableSchema.TableColumn MotivoColumn
{
get { return Schema.Columns[19]; }
}
public static TableSchema.TableColumn IdMotivoSitamColumn
{
get { return Schema.Columns[20]; }
}
public static TableSchema.TableColumn IdTipoEstudioColumn
{
get { return Schema.Columns[21]; }
}
public static TableSchema.TableColumn IdTipoEstudioSitamColumn
{
get { return Schema.Columns[22]; }
}
public static TableSchema.TableColumn ObservacionesColumn
{
get { return Schema.Columns[23]; }
}
public static TableSchema.TableColumn PasadoSipsColumn
{
get { return Schema.Columns[24]; }
}
public static TableSchema.TableColumn ActivoColumn
{
get { return Schema.Columns[25]; }
}
public static TableSchema.TableColumn CreatedByColumn
{
get { return Schema.Columns[26]; }
}
public static TableSchema.TableColumn CreatedOnColumn
{
get { return Schema.Columns[27]; }
}
public static TableSchema.TableColumn ModifiedByColumn
{
get { return Schema.Columns[28]; }
}
public static TableSchema.TableColumn ModifiedOnColumn
{
get { return Schema.Columns[29]; }
}
public static TableSchema.TableColumn InformeProfesionalColumn
{
get { return Schema.Columns[30]; }
}
public static TableSchema.TableColumn LocalidadColumn
{
get { return Schema.Columns[31]; }
}
public static TableSchema.TableColumn InformacionCelularColumn
{
get { return Schema.Columns[32]; }
}
public static TableSchema.TableColumn SolicitudProfesionalSSSColumn
{
get { return Schema.Columns[33]; }
}
public static TableSchema.TableColumn SolicitudProfesionalDNIColumn
{
get { return Schema.Columns[34]; }
}
public static TableSchema.TableColumn InformeProfesionalSSSColumn
{
get { return Schema.Columns[35]; }
}
public static TableSchema.TableColumn InformeProfesionalDNIColumn
{
get { return Schema.Columns[36]; }
}
public static TableSchema.TableColumn EquipoColumn
{
get { return Schema.Columns[37]; }
}
public static TableSchema.TableColumn MotivoConsultaColumn
{
get { return Schema.Columns[38]; }
}
public static TableSchema.TableColumn ProtocoloColumn
{
get { return Schema.Columns[39]; }
}
public static TableSchema.TableColumn ProtocoloPrefijoColumn
{
get { return Schema.Columns[40]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdMamografiaHP = @"idMamografiaHP";
public static string IdHistoria = @"idHistoria";
public static string TipoDocumento = @"tipoDocumento";
public static string Documento = @"Documento";
public static string Apellido = @"Apellido";
public static string Nombre = @"Nombre";
public static string FechaNacimiento = @"fechaNacimiento";
public static string ObraSocial = @"obraSocial";
public static string InformacionContacto = @"informacionContacto";
public static string Direccion = @"Direccion";
public static string SolicitudProfesional = @"SolicitudProfesional";
public static string SolicitudCentroSalud = @"SolicitudCentroSalud";
public static string BiradIzquierdo = @"BiradIzquierdo";
public static string BiradDerecho = @"BiradDerecho";
public static string BiradDefinitivo = @"BiradDefinitivo";
public static string FechaPlaca = @"fechaPlaca";
public static string FechaInforme = @"fechaInforme";
public static string Informe = @"informe";
public static string IdMotivo = @"idMotivo";
public static string Motivo = @"motivo";
public static string IdMotivoSitam = @"idMotivoSitam";
public static string IdTipoEstudio = @"idTipoEstudio";
public static string IdTipoEstudioSitam = @"idTipoEstudioSitam";
public static string Observaciones = @"observaciones";
public static string PasadoSips = @"pasadoSips";
public static string Activo = @"activo";
public static string CreatedBy = @"CreatedBy";
public static string CreatedOn = @"CreatedOn";
public static string ModifiedBy = @"ModifiedBy";
public static string ModifiedOn = @"ModifiedOn";
public static string InformeProfesional = @"informeProfesional";
public static string Localidad = @"localidad";
public static string InformacionCelular = @"informacionCelular";
public static string SolicitudProfesionalSSS = @"solicitudProfesionalSSS";
public static string SolicitudProfesionalDNI = @"solicitudProfesionalDNI";
public static string InformeProfesionalSSS = @"informeProfesionalSSS";
public static string InformeProfesionalDNI = @"informeProfesionalDNI";
public static string Equipo = @"equipo";
public static string MotivoConsulta = @"motivoConsulta";
public static string Protocolo = @"protocolo";
public static string ProtocoloPrefijo = @"protocoloPrefijo";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
/*
* WebSocketBehavior.cs
*
* The MIT License
*
* Copyright (c) 2012-2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace WebSocketSharp.Server
{
using System;
using System.IO;
using System.Threading.Tasks;
using WebSocketSharp.Net;
using WebSocketSharp.Net.WebSockets;
using ErrorEventArgs = WebSocketSharp.ErrorEventArgs;
/// <summary>
/// Exposes the methods and properties used to define the behavior of a WebSocket service
/// provided by the <see cref="WebSocketServer"/> or <see cref="WebSocketServer"/>.
/// </summary>
/// <remarks>
/// The WebSocketBehavior class is an abstract class.
/// </remarks>
public abstract class WebSocketBehavior : IWebSocketSession
{
private WebSocketContext _context;
private Func<CookieCollection, CookieCollection, bool> _cookiesValidator;
private string _id;
private Func<string, bool> _originValidator;
private string _protocol;
private WebSocketSessionManager _sessions;
private DateTime _start;
private WebSocket _websocket;
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketBehavior"/> class.
/// </summary>
protected WebSocketBehavior()
{
_start = DateTime.MaxValue;
}
/// <summary>
/// Gets the information in the current connection request to the WebSocket service.
/// </summary>
/// <value>
/// A <see cref="WebSocketContext"/> that provides the access to the current connection request,
/// or <see langword="null"/> if the WebSocket connection isn't established.
/// </value>
public WebSocketContext Context => _context;
/// <summary>
/// Gets or sets the delegate called to validate the HTTP cookies included in a connection
/// request to the WebSocket service.
/// </summary>
/// <remarks>
/// The delegate is called when the <see cref="WebSocket"/> used in the current session
/// validates the connection request.
/// </remarks>
/// <value>
/// <para>
/// A <c>Func<CookieCollection, CookieCollection, bool></c> delegate that references
/// the method(s) used to validate the cookies. 1st <see cref="CookieCollection"/> passed to
/// this delegate contains the cookies to validate if any. 2nd <see cref="CookieCollection"/>
/// passed to this delegate receives the cookies to send to the client.
/// </para>
/// <para>
/// This delegate should return <c>true</c> if the cookies are valid.
/// </para>
/// <para>
/// The default value is <see langword="null"/>, and it does nothing to validate.
/// </para>
/// </value>
public Func<CookieCollection, CookieCollection, bool> CookiesValidator
{
get
{
return _cookiesValidator;
}
set
{
_cookiesValidator = value;
}
}
/// <summary>
/// Gets the unique ID of the current session.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the unique ID of the current session,
/// or <see langword="null"/> if the WebSocket connection isn't established.
/// </value>
public string Id => _id;
/// <summary>
/// Gets or sets the delegate called to validate the Origin header included in a connection
/// request to the WebSocket service.
/// </summary>
/// <remarks>
/// The delegate is called when the <see cref="WebSocket"/> used in the current session
/// validates the connection request.
/// </remarks>
/// <value>
/// <para>
/// A <c>Func<string, bool></c> delegate that references the method(s) used to validate
/// the origin header. A <see cref="string"/> passed to this delegate represents the value of
/// the origin header to validate if any.
/// </para>
/// <para>
/// This delegate should return <c>true</c> if the origin header is valid.
/// </para>
/// <para>
/// The default value is <see langword="null"/>, and it does nothing to validate.
/// </para>
/// </value>
public Func<string, bool> OriginValidator
{
get
{
return _originValidator;
}
set
{
_originValidator = value;
}
}
/// <summary>
/// Gets or sets the WebSocket subprotocol used in the current session.
/// </summary>
/// <remarks>
/// Set operation of this property is available before the WebSocket connection has been
/// established.
/// </remarks>
/// <value>
/// <para>
/// A <see cref="string"/> that represents the subprotocol if any.
/// The default value is <see cref="string.Empty"/>.
/// </para>
/// <para>
/// The value to set must be a token defined in
/// <see href="http://tools.ietf.org/html/rfc2616#section-2.2">RFC 2616</see>.
/// </para>
/// </value>
public string Protocol
{
get
{
return _websocket != null
? _websocket.Protocol
: _protocol ?? string.Empty;
}
set
{
if (State != WebSocketState.Connecting)
return;
if (value != null && (value.Length == 0 || !value.IsToken()))
return;
_protocol = value;
}
}
/// <summary>
/// Gets the time that the current session has started.
/// </summary>
/// <value>
/// A <see cref="DateTime"/> that represents the time that the current session has started,
/// or <see cref="DateTime.MaxValue"/> if the WebSocket connection isn't established.
/// </value>
public DateTime StartTime => _start;
/// <summary>
/// Gets the state of the <see cref="WebSocket"/> used in the current session.
/// </summary>
/// <value>
/// One of the <see cref="WebSocketState"/> enum values, indicates the state of
/// the <see cref="WebSocket"/> used in the current session.
/// </value>
public WebSocketState State => _websocket?.ReadyState ?? WebSocketState.Connecting;
/// <summary>
/// Gets the access to the sessions in the WebSocket service.
/// </summary>
/// <value>
/// A <see cref="WebSocketSessionManager"/> that provides the access to the sessions, or <see langword="null"/> if the WebSocket connection isn't established.
/// </value>
protected WebSocketSessionManager Sessions => _sessions;
internal async Task Start(WebSocketContext context, WebSocketSessionManager sessions)
{
if (_websocket != null)
{
await context.WebSocket.InnerClose(HttpStatusCode.ServiceUnavailable).ConfigureAwait(false);
return;
}
_context = context;
_sessions = sessions;
_websocket = context.WebSocket;
_websocket.CustomHandshakeRequestChecker = CheckIfValidConnectionRequest;
_websocket.Protocol = _protocol;
var waitTime = sessions.WaitTime;
_websocket.WaitTime = waitTime;
_websocket.SetOnOpen(InnerOnOpen);
_websocket.SetOnMessage(OnMessage);
_websocket.SetOnError(OnError);
_websocket.SetOnClose(InnerOnClose);
await _websocket.ConnectAsServer().ConfigureAwait(false);
}
/// <summary>
/// Calls the <see cref="OnError"/> method with the specified <paramref name="message"/> and
/// <paramref name="exception"/>.
/// </summary>
/// <remarks>
/// This method doesn't call the <see cref="OnError"/> method if <paramref name="message"/> is
/// <see langword="null"/> or empty.
/// </remarks>
/// <param name="message">
/// A <see cref="string"/> that represents the error message.
/// </param>
/// <param name="exception">
/// An <see cref="Exception"/> instance that represents the cause of the error if any.
/// </param>
protected void Error(string message, Exception exception)
{
if (message != null && message.Length > 0)
OnError(new ErrorEventArgs(message, exception));
}
/// <summary>
/// Called when the WebSocket connection used in the current session has been closed.
/// </summary>
/// <param name="e">
/// A <see cref="CloseEventArgs"/> that represents the event data passed to
/// a <see cref="WebSocket.OnClose"/> event.
/// </param>
protected virtual Task OnClose(CloseEventArgs e)
{
return Task.FromResult(false);
}
/// <summary>
/// Called when the <see cref="WebSocket"/> used in the current session gets an error.
/// </summary>
/// <param name="e">
/// A <see cref="WebSocketSharp.ErrorEventArgs"/> that represents the event data passed to
/// a <see cref="WebSocket.OnError"/> event.
/// </param>
protected virtual Task OnError(ErrorEventArgs e)
{
return Task.FromResult(false);
}
/// <summary>
/// Called when the <see cref="WebSocket"/> used in the current session receives a message.
/// </summary>
/// <param name="e">
/// A <see cref="MessageEventArgs"/> that represents the event data passed to
/// a <see cref="WebSocket.OnMessage"/> event.
/// </param>
protected virtual Task OnMessage(MessageEventArgs e)
{
return Task.FromResult(false);
}
/// <summary>
/// Called when the WebSocket connection used in the current session has been established.
/// </summary>
protected virtual Task OnOpen()
{
return Task.FromResult(false);
}
/// <summary>
/// Sends a binary <paramref name="data"/> to the client on the current session.
/// </summary>
/// <remarks>
/// This method is available after the WebSocket connection has been established.
/// </remarks>
/// <param name="data">
/// An array of <see cref="byte"/> that represents the binary data to send.
/// </param>
protected Task<bool> Send(byte[] data)
{
return _websocket != null ? _websocket.Send(data) : Task.FromResult(false);
}
/// <summary>
/// Sends the specified <paramref name="stream"/> as a binary data to the client
/// on the current session.
/// </summary>
/// <remarks>
/// This method is available after the WebSocket connection has been established.
/// </remarks>
/// <param name="stream">
/// A <see cref="FileInfo"/> that represents the file to send.
/// </param>
protected Task<bool> Send(Stream stream)
{
return _websocket != null ? _websocket.Send(stream) : Task.FromResult(false);
}
/// <summary>
/// Sends a text <paramref name="data"/> to the client on the current session.
/// </summary>
/// <remarks>
/// This method is available after the WebSocket connection has been established.
/// </remarks>
/// <param name="data">
/// A <see cref="string"/> that represents the text data to send.
/// </param>
protected Task<bool> Send(string data)
{
return _websocket != null ? _websocket.Send(data) : Task.FromResult(false);
}
private async Task<string> CheckIfValidConnectionRequest(WebSocketContext context)
{
return _originValidator != null && !_originValidator(await context.GetOrigin().ConfigureAwait(false))
? "Invalid Origin header."
: _cookiesValidator != null &&
!_cookiesValidator(await context.GetCookieCollection().ConfigureAwait(false), context.WebSocket.CookieCollection)
? "Invalid Cookies."
: null;
}
private Task InnerOnClose(CloseEventArgs e)
{
if (_id == null)
{
return Task.FromResult(false);
}
_sessions.Remove(_id);
return OnClose(e);
}
private Task InnerOnOpen()
{
_id = _sessions.Add(this);
if (_id == null)
{
_websocket.Close(CloseStatusCode.Away);
return Task.FromResult(false);
}
_start = DateTime.Now;
return OnOpen();
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// UserChannelResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.IpMessaging.V2.Service.User
{
public class UserChannelResource : Resource
{
public sealed class ChannelStatusEnum : StringEnum
{
private ChannelStatusEnum(string value) : base(value) {}
public ChannelStatusEnum() {}
public static implicit operator ChannelStatusEnum(string value)
{
return new ChannelStatusEnum(value);
}
public static readonly ChannelStatusEnum Joined = new ChannelStatusEnum("joined");
public static readonly ChannelStatusEnum Invited = new ChannelStatusEnum("invited");
public static readonly ChannelStatusEnum NotParticipating = new ChannelStatusEnum("not_participating");
}
public sealed class NotificationLevelEnum : StringEnum
{
private NotificationLevelEnum(string value) : base(value) {}
public NotificationLevelEnum() {}
public static implicit operator NotificationLevelEnum(string value)
{
return new NotificationLevelEnum(value);
}
public static readonly NotificationLevelEnum Default = new NotificationLevelEnum("default");
public static readonly NotificationLevelEnum Muted = new NotificationLevelEnum("muted");
}
private static Request BuildReadRequest(ReadUserChannelOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.IpMessaging,
"/v2/Services/" + options.PathServiceSid + "/Users/" + options.PathUserSid + "/Channels",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read UserChannel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of UserChannel </returns>
public static ResourceSet<UserChannelResource> Read(ReadUserChannelOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<UserChannelResource>.FromJson("channels", response.Content);
return new ResourceSet<UserChannelResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read UserChannel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of UserChannel </returns>
public static async System.Threading.Tasks.Task<ResourceSet<UserChannelResource>> ReadAsync(ReadUserChannelOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<UserChannelResource>.FromJson("channels", response.Content);
return new ResourceSet<UserChannelResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathUserSid"> The user_sid </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of UserChannel </returns>
public static ResourceSet<UserChannelResource> Read(string pathServiceSid,
string pathUserSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadUserChannelOptions(pathServiceSid, pathUserSid){PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathUserSid"> The user_sid </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of UserChannel </returns>
public static async System.Threading.Tasks.Task<ResourceSet<UserChannelResource>> ReadAsync(string pathServiceSid,
string pathUserSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadUserChannelOptions(pathServiceSid, pathUserSid){PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<UserChannelResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<UserChannelResource>.FromJson("channels", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<UserChannelResource> NextPage(Page<UserChannelResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.IpMessaging)
);
var response = client.Request(request);
return Page<UserChannelResource>.FromJson("channels", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<UserChannelResource> PreviousPage(Page<UserChannelResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.IpMessaging)
);
var response = client.Request(request);
return Page<UserChannelResource>.FromJson("channels", response.Content);
}
private static Request BuildFetchRequest(FetchUserChannelOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.IpMessaging,
"/v2/Services/" + options.PathServiceSid + "/Users/" + options.PathUserSid + "/Channels/" + options.PathChannelSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch UserChannel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of UserChannel </returns>
public static UserChannelResource Fetch(FetchUserChannelOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch UserChannel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of UserChannel </returns>
public static async System.Threading.Tasks.Task<UserChannelResource> FetchAsync(FetchUserChannelOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathUserSid"> The user_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of UserChannel </returns>
public static UserChannelResource Fetch(string pathServiceSid,
string pathUserSid,
string pathChannelSid,
ITwilioRestClient client = null)
{
var options = new FetchUserChannelOptions(pathServiceSid, pathUserSid, pathChannelSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathUserSid"> The user_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of UserChannel </returns>
public static async System.Threading.Tasks.Task<UserChannelResource> FetchAsync(string pathServiceSid,
string pathUserSid,
string pathChannelSid,
ITwilioRestClient client = null)
{
var options = new FetchUserChannelOptions(pathServiceSid, pathUserSid, pathChannelSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeleteUserChannelOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.IpMessaging,
"/v2/Services/" + options.PathServiceSid + "/Users/" + options.PathUserSid + "/Channels/" + options.PathChannelSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete UserChannel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of UserChannel </returns>
public static bool Delete(DeleteUserChannelOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete UserChannel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of UserChannel </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteUserChannelOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathUserSid"> The user_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of UserChannel </returns>
public static bool Delete(string pathServiceSid,
string pathUserSid,
string pathChannelSid,
ITwilioRestClient client = null)
{
var options = new DeleteUserChannelOptions(pathServiceSid, pathUserSid, pathChannelSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathUserSid"> The user_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of UserChannel </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid,
string pathUserSid,
string pathChannelSid,
ITwilioRestClient client = null)
{
var options = new DeleteUserChannelOptions(pathServiceSid, pathUserSid, pathChannelSid);
return await DeleteAsync(options, client);
}
#endif
private static Request BuildUpdateRequest(UpdateUserChannelOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.IpMessaging,
"/v2/Services/" + options.PathServiceSid + "/Users/" + options.PathUserSid + "/Channels/" + options.PathChannelSid + "",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update UserChannel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of UserChannel </returns>
public static UserChannelResource Update(UpdateUserChannelOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update UserChannel parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of UserChannel </returns>
public static async System.Threading.Tasks.Task<UserChannelResource> UpdateAsync(UpdateUserChannelOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// update
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathUserSid"> The user_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="notificationLevel"> The notification_level </param>
/// <param name="lastConsumedMessageIndex"> The last_consumed_message_index </param>
/// <param name="lastConsumptionTimestamp"> The last_consumption_timestamp </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of UserChannel </returns>
public static UserChannelResource Update(string pathServiceSid,
string pathUserSid,
string pathChannelSid,
UserChannelResource.NotificationLevelEnum notificationLevel = null,
int? lastConsumedMessageIndex = null,
DateTime? lastConsumptionTimestamp = null,
ITwilioRestClient client = null)
{
var options = new UpdateUserChannelOptions(pathServiceSid, pathUserSid, pathChannelSid){NotificationLevel = notificationLevel, LastConsumedMessageIndex = lastConsumedMessageIndex, LastConsumptionTimestamp = lastConsumptionTimestamp};
return Update(options, client);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathUserSid"> The user_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="notificationLevel"> The notification_level </param>
/// <param name="lastConsumedMessageIndex"> The last_consumed_message_index </param>
/// <param name="lastConsumptionTimestamp"> The last_consumption_timestamp </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of UserChannel </returns>
public static async System.Threading.Tasks.Task<UserChannelResource> UpdateAsync(string pathServiceSid,
string pathUserSid,
string pathChannelSid,
UserChannelResource.NotificationLevelEnum notificationLevel = null,
int? lastConsumedMessageIndex = null,
DateTime? lastConsumptionTimestamp = null,
ITwilioRestClient client = null)
{
var options = new UpdateUserChannelOptions(pathServiceSid, pathUserSid, pathChannelSid){NotificationLevel = notificationLevel, LastConsumedMessageIndex = lastConsumedMessageIndex, LastConsumptionTimestamp = lastConsumptionTimestamp};
return await UpdateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a UserChannelResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> UserChannelResource object represented by the provided JSON </returns>
public static UserChannelResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<UserChannelResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The account_sid
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The service_sid
/// </summary>
[JsonProperty("service_sid")]
public string ServiceSid { get; private set; }
/// <summary>
/// The channel_sid
/// </summary>
[JsonProperty("channel_sid")]
public string ChannelSid { get; private set; }
/// <summary>
/// The user_sid
/// </summary>
[JsonProperty("user_sid")]
public string UserSid { get; private set; }
/// <summary>
/// The member_sid
/// </summary>
[JsonProperty("member_sid")]
public string MemberSid { get; private set; }
/// <summary>
/// The status
/// </summary>
[JsonProperty("status")]
[JsonConverter(typeof(StringEnumConverter))]
public UserChannelResource.ChannelStatusEnum Status { get; private set; }
/// <summary>
/// The last_consumed_message_index
/// </summary>
[JsonProperty("last_consumed_message_index")]
public int? LastConsumedMessageIndex { get; private set; }
/// <summary>
/// The unread_messages_count
/// </summary>
[JsonProperty("unread_messages_count")]
public int? UnreadMessagesCount { get; private set; }
/// <summary>
/// The links
/// </summary>
[JsonProperty("links")]
public Dictionary<string, string> Links { get; private set; }
/// <summary>
/// The url
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// The notification_level
/// </summary>
[JsonProperty("notification_level")]
[JsonConverter(typeof(StringEnumConverter))]
public UserChannelResource.NotificationLevelEnum NotificationLevel { get; private set; }
private UserChannelResource()
{
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2017 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 --
using System;
using System.Globalization;
namespace MsgPack
{
partial class TimestampStringConverter
{
// Currently, custom format and normal date time format except 'o' or 'O' 's' are NOT supported.
public static TimestampParseResult TryParseExact( string input, string format, IFormatProvider formatProvider, DateTimeStyles styles, out Timestamp result )
{
if ( format != "o" && format != "O" && format != "s" )
{
result = default( Timestamp );
return TimestampParseResult.UnsupportedFormat;
}
var numberFormat = NumberFormatInfo.GetInstance( formatProvider );
var position = 0;
if ( !ParseWhitespace( input, ref position, ( styles & DateTimeStyles.AllowLeadingWhite ) != 0, /* isTrailing */false ) )
{
result = default( Timestamp );
return TimestampParseResult.LeadingWhitespaceNotAllowed;
}
long year;
if ( !ParseYear( input, ref position, numberFormat, out year ) )
{
result = default( Timestamp );
return TimestampParseResult.InvalidYear;
}
if ( !ParseDelimiter( input, ref position, DateDelimiter ) )
{
result = default( Timestamp );
return TimestampParseResult.InvalidYearMonthDeilimiter;
}
var isLeapYear = Timestamp.IsLeapYearInternal( year );
int month;
if ( !ParseDigitRange( input, 2, ref position, 1, 12, out month ) )
{
result = default( Timestamp );
return TimestampParseResult.InvalidMonth;
}
if ( !ParseDelimiter( input, ref position, DateDelimiter ) )
{
result = default( Timestamp );
return TimestampParseResult.InvalidMonthDayDelimiter;
}
int day;
if ( !ParseDay( input, ref position, month, isLeapYear, out day ) )
{
result = default( Timestamp );
return TimestampParseResult.InvalidDay;
}
if ( !ParseDelimiter( input, ref position, DateTimeDelimiter ) )
{
result = default( Timestamp );
return TimestampParseResult.InvalidDateTimeDelimiter;
}
int hour;
if ( !ParseDigitRange( input, 2, ref position, 0, 23, out hour ) )
{
result = default( Timestamp );
return TimestampParseResult.InvalidHour;
}
if ( !ParseDelimiter( input, ref position, TimeDelimiter ) )
{
result = default( Timestamp );
return TimestampParseResult.InvalidHourMinuteDelimiter;
}
int minute;
if ( !ParseDigitRange( input, 2, ref position, 0, 59, out minute ) )
{
result = default( Timestamp );
return TimestampParseResult.InvalidMinute;
}
if ( !ParseDelimiter( input, ref position, TimeDelimiter ) )
{
result = default( Timestamp );
return TimestampParseResult.InvalidMinuteSecondDelimiter;
}
int second;
if ( !ParseDigitRange( input, 2, ref position, 0, 59, out second ) )
{
result = default( Timestamp );
return TimestampParseResult.InvalidSecond;
}
var nanosecond = 0;
if ( format != "s" )
{
// "o" or "O"
if ( !ParseDelimiter( input, ref position, SubsecondDelimiter ) )
{
result = default( Timestamp );
return TimestampParseResult.InvalidSubsecondDelimiter;
}
if ( !ParseDigitRange( input, 9, ref position, 0, 999999999, out nanosecond ) )
{
result = default( Timestamp );
return TimestampParseResult.InvalidNanoSecond;
}
}
if ( !ParseDelimiter( input, ref position, UtcSign ) )
{
result = default( Timestamp );
return TimestampParseResult.MissingUtcSign;
}
if ( !ParseWhitespace( input, ref position, ( styles & DateTimeStyles.AllowTrailingWhite ) != 0, /* isTrailing */true ) )
{
result = default( Timestamp );
return TimestampParseResult.TrailingWhitespaceNotAllowed;
}
if ( position != input.Length )
{
result = default( Timestamp );
return TimestampParseResult.ExtraCharactors;
}
var components = new Timestamp.Value();
components.Year = year;
components.Month = month;
components.Day = day;
components.Hour = hour;
components.Minute = minute;
components.Second = second;
components.Nanoseconds = unchecked( ( uint )nanosecond );
try
{
result = Timestamp.FromComponents( ref components, isLeapYear );
}
catch ( OverflowException )
{
result = default( Timestamp );
return TimestampParseResult.YearOutOfRange;
}
return TimestampParseResult.Success;
}
private static bool ParseWhitespace( string input, ref int position, bool allowWhitespace, bool isTrailing )
{
if ( input.Length <= position )
{
return isTrailing;
}
if ( !allowWhitespace )
{
return !Char.IsWhiteSpace( input[ position ] );
}
while ( position < input.Length && Char.IsWhiteSpace( input[ position ] ) )
{
position++;
}
return true;
}
private static bool ParseDelimiter( string input, ref int position, char delimiter )
{
if ( input.Length <= position )
{
return false;
}
if ( input[ position ] != delimiter )
{
return false;
}
position++;
return true;
}
private static bool ParseSign( string input, ref int position, NumberFormatInfo numberFormat, out int sign )
{
if ( input.Length <= position )
{
sign = default( int );
return false;
}
if ( IsDigit( input[ position ] ) )
{
sign = 1;
return true;
}
if ( StartsWith( input, position, numberFormat.NegativeSign ) )
{
position += numberFormat.NegativeSign.Length;
sign = -1;
return true;
}
if ( StartsWith( input, position, numberFormat.PositiveSign ) )
{
position += numberFormat.NegativeSign.Length;
sign = 1;
return true;
}
sign = default( int );
return false;
}
private static bool StartsWith( string input, int startIndex, string comparison )
{
for ( var i = 0; i < comparison.Length; i++ )
{
if ( i + startIndex >= input.Length )
{
return false;
}
if ( input[ i + startIndex ] != comparison[ i ] )
{
return false;
}
}
return true;
}
private static bool ParseDigit( string input, int minLength, ref int position, out long digit )
{
var startPosition = position;
var bits = 0L;
while ( position < input.Length )
{
var c = input[ position ];
if ( !IsDigit( c ) )
{
break;
}
bits = bits * 10 + ( c - '0' );
position++;
}
digit = bits;
return position >= startPosition + minLength;
}
private static bool IsDigit( char c )
{
return '0' <= c && c <= '9';
}
private static bool ParseDigitRange( string input, int minLength, ref int position, int min, int max, out int result )
{
long digit;
if ( !ParseDigit( input, minLength, ref position, out digit ) )
{
result = default( int );
return false;
}
if ( digit < min || max < digit )
{
result = default( int );
return false;
}
result = unchecked( ( int )digit );
return true;
}
private static bool ParseYear( string input, ref int position, NumberFormatInfo numberFormat, out long year )
{
int sign;
if ( !ParseSign( input, ref position, numberFormat, out sign ) )
{
year = default( long );
return false;
}
long digit;
if ( !ParseDigit( input, 4, ref position, out digit ) )
{
year = default( long );
return false;
}
// as of ISO 8601, 0001-01-01 -1 day is 0000-12-31.
year = digit * sign;
return true;
}
private static bool ParseDay( string input, ref int position, int month, bool isLeapYear, out int day )
{
long digit;
if ( !ParseDigit( input, 2, ref position, out digit ) )
{
day = default( int );
return false;
}
var lastDay = Timestamp.GetLastDay( month, isLeapYear );
if ( digit < 1 || lastDay < digit )
{
day = default( int );
return false;
}
day = unchecked( ( int )digit );
return true;
}
}
}
| |
/*
* Copyright (c) 2006-2008, openmetaverse.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.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Threading;
using OpenMetaverse;
using OpenMetaverse.Packets;
namespace OpenMetaverse
{
public partial class AgentManager
{
#region Enums
/// <summary>
/// Used to specify movement actions for your agent
/// </summary>
[Flags]
public enum ControlFlags
{
/// <summary>Empty flag</summary>
NONE = 0,
/// <summary>Move Forward (SL Keybinding: W/Up Arrow)</summary>
AGENT_CONTROL_AT_POS = 0x1 << CONTROL_AT_POS_INDEX,
/// <summary>Move Backward (SL Keybinding: S/Down Arrow)</summary>
AGENT_CONTROL_AT_NEG = 0x1 << CONTROL_AT_NEG_INDEX,
/// <summary>Move Left (SL Keybinding: Shift-(A/Left Arrow))</summary>
AGENT_CONTROL_LEFT_POS = 0x1 << CONTROL_LEFT_POS_INDEX,
/// <summary>Move Right (SL Keybinding: Shift-(D/Right Arrow))</summary>
AGENT_CONTROL_LEFT_NEG = 0x1 << CONTROL_LEFT_NEG_INDEX,
/// <summary>Not Flying: Jump/Flying: Move Up (SL Keybinding: E)</summary>
AGENT_CONTROL_UP_POS = 0x1 << CONTROL_UP_POS_INDEX,
/// <summary>Not Flying: Croutch/Flying: Move Down (SL Keybinding: C)</summary>
AGENT_CONTROL_UP_NEG = 0x1 << CONTROL_UP_NEG_INDEX,
/// <summary>Unused</summary>
AGENT_CONTROL_PITCH_POS = 0x1 << CONTROL_PITCH_POS_INDEX,
/// <summary>Unused</summary>
AGENT_CONTROL_PITCH_NEG = 0x1 << CONTROL_PITCH_NEG_INDEX,
/// <summary>Unused</summary>
AGENT_CONTROL_YAW_POS = 0x1 << CONTROL_YAW_POS_INDEX,
/// <summary>Unused</summary>
AGENT_CONTROL_YAW_NEG = 0x1 << CONTROL_YAW_NEG_INDEX,
/// <summary>ORed with AGENT_CONTROL_AT_* if the keyboard is being used</summary>
AGENT_CONTROL_FAST_AT = 0x1 << CONTROL_FAST_AT_INDEX,
/// <summary>ORed with AGENT_CONTROL_LEFT_* if the keyboard is being used</summary>
AGENT_CONTROL_FAST_LEFT = 0x1 << CONTROL_FAST_LEFT_INDEX,
/// <summary>ORed with AGENT_CONTROL_UP_* if the keyboard is being used</summary>
AGENT_CONTROL_FAST_UP = 0x1 << CONTROL_FAST_UP_INDEX,
/// <summary>Fly</summary>
AGENT_CONTROL_FLY = 0x1 << CONTROL_FLY_INDEX,
/// <summary></summary>
AGENT_CONTROL_STOP = 0x1 << CONTROL_STOP_INDEX,
/// <summary>Finish our current animation</summary>
AGENT_CONTROL_FINISH_ANIM = 0x1 << CONTROL_FINISH_ANIM_INDEX,
/// <summary>Stand up from the ground or a prim seat</summary>
AGENT_CONTROL_STAND_UP = 0x1 << CONTROL_STAND_UP_INDEX,
/// <summary>Sit on the ground at our current location</summary>
AGENT_CONTROL_SIT_ON_GROUND = 0x1 << CONTROL_SIT_ON_GROUND_INDEX,
/// <summary>Whether mouselook is currently enabled</summary>
AGENT_CONTROL_MOUSELOOK = 0x1 << CONTROL_MOUSELOOK_INDEX,
/// <summary>Legacy, used if a key was pressed for less than a certain amount of time</summary>
AGENT_CONTROL_NUDGE_AT_POS = 0x1 << CONTROL_NUDGE_AT_POS_INDEX,
/// <summary>Legacy, used if a key was pressed for less than a certain amount of time</summary>
AGENT_CONTROL_NUDGE_AT_NEG = 0x1 << CONTROL_NUDGE_AT_NEG_INDEX,
/// <summary>Legacy, used if a key was pressed for less than a certain amount of time</summary>
AGENT_CONTROL_NUDGE_LEFT_POS = 0x1 << CONTROL_NUDGE_LEFT_POS_INDEX,
/// <summary>Legacy, used if a key was pressed for less than a certain amount of time</summary>
AGENT_CONTROL_NUDGE_LEFT_NEG = 0x1 << CONTROL_NUDGE_LEFT_NEG_INDEX,
/// <summary>Legacy, used if a key was pressed for less than a certain amount of time</summary>
AGENT_CONTROL_NUDGE_UP_POS = 0x1 << CONTROL_NUDGE_UP_POS_INDEX,
/// <summary>Legacy, used if a key was pressed for less than a certain amount of time</summary>
AGENT_CONTROL_NUDGE_UP_NEG = 0x1 << CONTROL_NUDGE_UP_NEG_INDEX,
/// <summary></summary>
AGENT_CONTROL_TURN_LEFT = 0x1 << CONTROL_TURN_LEFT_INDEX,
/// <summary></summary>
AGENT_CONTROL_TURN_RIGHT = 0x1 << CONTROL_TURN_RIGHT_INDEX,
/// <summary>Set when the avatar is idled or set to away. Note that the away animation is
/// activated separately from setting this flag</summary>
AGENT_CONTROL_AWAY = 0x1 << CONTROL_AWAY_INDEX,
/// <summary></summary>
AGENT_CONTROL_LBUTTON_DOWN = 0x1 << CONTROL_LBUTTON_DOWN_INDEX,
/// <summary></summary>
AGENT_CONTROL_LBUTTON_UP = 0x1 << CONTROL_LBUTTON_UP_INDEX,
/// <summary></summary>
AGENT_CONTROL_ML_LBUTTON_DOWN = 0x1 << CONTROL_ML_LBUTTON_DOWN_INDEX,
/// <summary></summary>
AGENT_CONTROL_ML_LBUTTON_UP = 0x1 << CONTROL_ML_LBUTTON_UP_INDEX
}
#endregion Enums
#region AgentUpdate Constants
private const int CONTROL_AT_POS_INDEX = 0;
private const int CONTROL_AT_NEG_INDEX = 1;
private const int CONTROL_LEFT_POS_INDEX = 2;
private const int CONTROL_LEFT_NEG_INDEX = 3;
private const int CONTROL_UP_POS_INDEX = 4;
private const int CONTROL_UP_NEG_INDEX = 5;
private const int CONTROL_PITCH_POS_INDEX = 6;
private const int CONTROL_PITCH_NEG_INDEX = 7;
private const int CONTROL_YAW_POS_INDEX = 8;
private const int CONTROL_YAW_NEG_INDEX = 9;
private const int CONTROL_FAST_AT_INDEX = 10;
private const int CONTROL_FAST_LEFT_INDEX = 11;
private const int CONTROL_FAST_UP_INDEX = 12;
private const int CONTROL_FLY_INDEX = 13;
private const int CONTROL_STOP_INDEX = 14;
private const int CONTROL_FINISH_ANIM_INDEX = 15;
private const int CONTROL_STAND_UP_INDEX = 16;
private const int CONTROL_SIT_ON_GROUND_INDEX = 17;
private const int CONTROL_MOUSELOOK_INDEX = 18;
private const int CONTROL_NUDGE_AT_POS_INDEX = 19;
private const int CONTROL_NUDGE_AT_NEG_INDEX = 20;
private const int CONTROL_NUDGE_LEFT_POS_INDEX = 21;
private const int CONTROL_NUDGE_LEFT_NEG_INDEX = 22;
private const int CONTROL_NUDGE_UP_POS_INDEX = 23;
private const int CONTROL_NUDGE_UP_NEG_INDEX = 24;
private const int CONTROL_TURN_LEFT_INDEX = 25;
private const int CONTROL_TURN_RIGHT_INDEX = 26;
private const int CONTROL_AWAY_INDEX = 27;
private const int CONTROL_LBUTTON_DOWN_INDEX = 28;
private const int CONTROL_LBUTTON_UP_INDEX = 29;
private const int CONTROL_ML_LBUTTON_DOWN_INDEX = 30;
private const int CONTROL_ML_LBUTTON_UP_INDEX = 31;
private const int TOTAL_CONTROLS = 32;
#endregion AgentUpdate Constants
/// <summary>
/// Agent movement and camera control
///
/// Agent movement is controlled by setting specific <seealso cref="T:AgentManager.ControlFlags"/>
/// After the control flags are set, An AgentUpdate is required to update the simulator of the specified flags
/// This is most easily accomplished by setting one or more of the AgentMovement properties
///
/// Movement of an avatar is always based on a compass direction, for example AtPos will move the
/// agent from West to East or forward on the X Axis, AtNeg will of course move agent from
/// East to West or backward on the X Axis, LeftPos will be South to North or forward on the Y Axis
/// The Z axis is Up, finer grained control of movements can be done using the Nudge properties
/// </summary>
public partial class AgentMovement
{
#region Properties
/// <summary>Move agent positive along the X axis</summary>
public bool AtPos
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_AT_POS); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_AT_POS, value); }
}
/// <summary>Move agent negative along the X axis</summary>
public bool AtNeg
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG, value); }
}
/// <summary>Move agent positive along the Y axis</summary>
public bool LeftPos
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS, value); }
}
/// <summary>Move agent negative along the Y axis</summary>
public bool LeftNeg
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG, value); }
}
/// <summary>Move agent positive along the Z axis</summary>
public bool UpPos
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_UP_POS); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_UP_POS, value); }
}
/// <summary>Move agent negative along the Z axis</summary>
public bool UpNeg
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG, value); }
}
/// <summary></summary>
public bool PitchPos
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_PITCH_POS); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_PITCH_POS, value); }
}
/// <summary></summary>
public bool PitchNeg
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_PITCH_NEG); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_PITCH_NEG, value); }
}
/// <summary></summary>
public bool YawPos
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS, value); }
}
/// <summary></summary>
public bool YawNeg
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG, value); }
}
/// <summary></summary>
public bool FastAt
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FAST_AT); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FAST_AT, value); }
}
/// <summary></summary>
public bool FastLeft
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FAST_LEFT); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FAST_LEFT, value); }
}
/// <summary></summary>
public bool FastUp
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FAST_UP); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FAST_UP, value); }
}
/// <summary>Causes simulator to make agent fly</summary>
public bool Fly
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FLY); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FLY, value); }
}
/// <summary>Stop movement</summary>
public bool Stop
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_STOP); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_STOP, value); }
}
/// <summary>Finish animation</summary>
public bool FinishAnim
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FINISH_ANIM); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FINISH_ANIM, value); }
}
/// <summary>Stand up from a sit</summary>
public bool StandUp
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_STAND_UP); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_STAND_UP, value); }
}
/// <summary>Tells simulator to sit agent on ground</summary>
public bool SitOnGround
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_SIT_ON_GROUND); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_SIT_ON_GROUND, value); }
}
/// <summary>Place agent into mouselook mode</summary>
public bool Mouselook
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK, value); }
}
/// <summary>Nudge agent positive along the X axis</summary>
public bool NudgeAtPos
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS, value); }
}
/// <summary>Nudge agent negative along the X axis</summary>
public bool NudgeAtNeg
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG, value); }
}
/// <summary>Nudge agent positive along the Y axis</summary>
public bool NudgeLeftPos
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS, value); }
}
/// <summary>Nudge agent negative along the Y axis</summary>
public bool NudgeLeftNeg
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG, value); }
}
/// <summary>Nudge agent positive along the Z axis</summary>
public bool NudgeUpPos
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS, value); }
}
/// <summary>Nudge agent negative along the Z axis</summary>
public bool NudgeUpNeg
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG, value); }
}
/// <summary></summary>
public bool TurnLeft
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_TURN_LEFT); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_TURN_LEFT, value); }
}
/// <summary></summary>
public bool TurnRight
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_TURN_RIGHT); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_TURN_RIGHT, value); }
}
/// <summary>Tell simulator to mark agent as away</summary>
public bool Away
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_AWAY); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_AWAY, value); }
}
/// <summary></summary>
public bool LButtonDown
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN, value); }
}
/// <summary></summary>
public bool LButtonUp
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP, value); }
}
/// <summary></summary>
public bool MLButtonDown
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN, value); }
}
/// <summary></summary>
public bool MLButtonUp
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_UP); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_UP, value); }
}
/// <summary>
/// Returns "always run" value, or changes it by sending a SetAlwaysRunPacket
/// </summary>
public bool AlwaysRun
{
get
{
return alwaysRun;
}
set
{
alwaysRun = value;
SetAlwaysRunPacket run = new SetAlwaysRunPacket();
run.AgentData.AgentID = Client.Self.AgentID;
run.AgentData.SessionID = Client.Self.SessionID;
run.AgentData.AlwaysRun = alwaysRun;
Client.Network.SendPacket(run);
}
}
/// <summary>The current value of the agent control flags</summary>
public uint AgentControls
{
get { return agentControls; }
}
/// <summary>Gets or sets the interval in milliseconds at which
/// AgentUpdate packets are sent to the current simulator. Setting
/// this to a non-zero value will also enable the packet sending if
/// it was previously off, and setting it to zero will disable</summary>
public int UpdateInterval
{
get
{
return updateInterval;
}
set
{
if (value > 0)
{
if (updateTimer != null)
{
updateTimer.Change(value, value);
}
updateInterval = value;
}
else
{
if (updateTimer != null)
{
updateTimer.Change(Timeout.Infinite, Timeout.Infinite);
}
updateInterval = 0;
}
}
}
/// <summary>Gets or sets whether AgentUpdate packets are sent to
/// the current simulator</summary>
public bool UpdateEnabled
{
get { return (updateInterval != 0); }
}
/// <summary>Reset movement controls every time we send an update</summary>
public bool AutoResetControls
{
get { return autoResetControls; }
set { autoResetControls = value; }
}
#endregion Properties
/// <summary>Agent camera controls</summary>
public AgentCamera Camera;
/// <summary>Currently only used for hiding your group title</summary>
public AgentFlags Flags = AgentFlags.None;
/// <summary>Action state of the avatar, which can currently be
/// typing and editing</summary>
public AgentState State = AgentState.None;
/// <summary></summary>
public Quaternion BodyRotation = Quaternion.Identity;
/// <summary></summary>
public Quaternion HeadRotation = Quaternion.Identity;
#region Change tracking
/// <summary></summary>
private Quaternion LastBodyRotation;
/// <summary></summary>
private Quaternion LastHeadRotation;
/// <summary></summary>
private Vector3 LastCameraCenter;
/// <summary></summary>
private Vector3 LastCameraXAxis;
/// <summary></summary>
private Vector3 LastCameraYAxis;
/// <summary></summary>
private Vector3 LastCameraZAxis;
/// <summary></summary>
private float LastFar;
#endregion Change tracking
private bool alwaysRun;
private GridClient Client;
private uint agentControls;
private int duplicateCount;
private AgentState lastState;
/// <summary>Timer for sending AgentUpdate packets</summary>
private Timer updateTimer;
private int updateInterval;
private bool autoResetControls;
/// <summary>Default constructor</summary>
public AgentMovement(GridClient client)
{
Client = client;
Camera = new AgentCamera();
Client.Network.LoginProgress += Network_OnConnected;
Client.Network.Disconnected += Network_OnDisconnected;
updateInterval = Settings.DEFAULT_AGENT_UPDATE_INTERVAL;
}
private void CleanupTimer()
{
if (updateTimer != null)
{
updateTimer.Dispose();
updateTimer = null;
}
}
private void Network_OnDisconnected(object sender, DisconnectedEventArgs e)
{
CleanupTimer();
}
private void Network_OnConnected(object sender, LoginProgressEventArgs e)
{
if (e.Status == LoginStatus.Success)
{
CleanupTimer();
updateTimer = new Timer(new TimerCallback(UpdateTimer_Elapsed), null, updateInterval, updateInterval);
}
}
/// <summary>
/// Send an AgentUpdate with the camera set at the current agent
/// position and pointing towards the heading specified
/// </summary>
/// <param name="heading">Camera rotation in radians</param>
/// <param name="reliable">Whether to send the AgentUpdate reliable
/// or not</param>
public void UpdateFromHeading(double heading, bool reliable)
{
Camera.Position = Client.Self.SimPosition;
Camera.LookDirection(heading);
BodyRotation.Z = (float)Math.Sin(heading / 2.0d);
BodyRotation.W = (float)Math.Cos(heading / 2.0d);
HeadRotation = BodyRotation;
SendUpdate(reliable);
}
/// <summary>
/// Rotates the avatar body and camera toward a target position.
/// This will also anchor the camera position on the avatar
/// </summary>
/// <param name="target">Region coordinates to turn toward</param>
public bool TurnToward(Vector3 target)
{
return TurnToward(target, true);
}
/// <summary>
/// Rotates the avatar body and camera toward a target position.
/// This will also anchor the camera position on the avatar
/// </summary>
/// <param name="target">Region coordinates to turn toward</param>
/// <param name="sendUpdate">whether to send update or not</param>
public bool TurnToward(Vector3 target, bool sendUpdate)
{
if (Client.Settings.SEND_AGENT_UPDATES)
{
Quaternion parentRot = Quaternion.Identity;
if (Client.Self.SittingOn > 0)
{
if (!Client.Network.CurrentSim.ObjectsPrimitives.ContainsKey(Client.Self.SittingOn))
{
Logger.Log("Attempted TurnToward but parent prim is not in dictionary", Helpers.LogLevel.Warning, Client);
return false;
}
else parentRot = Client.Network.CurrentSim.ObjectsPrimitives[Client.Self.SittingOn].Rotation;
}
Quaternion between = Vector3.RotationBetween(Vector3.UnitX, Vector3.Normalize(target - Client.Self.SimPosition));
Quaternion rot = between * (Quaternion.Identity / parentRot);
BodyRotation = rot;
HeadRotation = rot;
Camera.LookAt(Client.Self.SimPosition, target);
if (sendUpdate) SendUpdate();
return true;
}
else
{
Logger.Log("Attempted TurnToward but agent updates are disabled", Helpers.LogLevel.Warning, Client);
return false;
}
}
/// <summary>
/// Send new AgentUpdate packet to update our current camera
/// position and rotation
/// </summary>
public void SendUpdate()
{
SendUpdate(false, Client.Network.CurrentSim);
}
/// <summary>
/// Send new AgentUpdate packet to update our current camera
/// position and rotation
/// </summary>
/// <param name="reliable">Whether to require server acknowledgement
/// of this packet</param>
public void SendUpdate(bool reliable)
{
SendUpdate(reliable, Client.Network.CurrentSim);
}
/// <summary>
/// Send new AgentUpdate packet to update our current camera
/// position and rotation
/// </summary>
/// <param name="reliable">Whether to require server acknowledgement
/// of this packet</param>
/// <param name="simulator">Simulator to send the update to</param>
public void SendUpdate(bool reliable, Simulator simulator)
{
// Since version 1.40.4 of the Linden simulator, sending this update
// causes corruption of the agent position in the simulator
if (simulator != null && (!simulator.AgentMovementComplete))
return;
Vector3 origin = Camera.Position;
Vector3 xAxis = Camera.LeftAxis;
Vector3 yAxis = Camera.AtAxis;
Vector3 zAxis = Camera.UpAxis;
// Attempted to sort these in a rough order of how often they might change
if (agentControls == 0 &&
yAxis == LastCameraYAxis &&
origin == LastCameraCenter &&
State == lastState &&
HeadRotation == LastHeadRotation &&
BodyRotation == LastBodyRotation &&
xAxis == LastCameraXAxis &&
Camera.Far == LastFar &&
zAxis == LastCameraZAxis)
{
++duplicateCount;
}
else
{
duplicateCount = 0;
}
if (Client.Settings.DISABLE_AGENT_UPDATE_DUPLICATE_CHECK || duplicateCount < 10)
{
// Store the current state to do duplicate checking
LastHeadRotation = HeadRotation;
LastBodyRotation = BodyRotation;
LastCameraYAxis = yAxis;
LastCameraCenter = origin;
LastCameraXAxis = xAxis;
LastCameraZAxis = zAxis;
LastFar = Camera.Far;
lastState = State;
// Build the AgentUpdate packet and send it
AgentUpdatePacket update = new AgentUpdatePacket();
update.Header.Reliable = reliable;
update.AgentData.AgentID = Client.Self.AgentID;
update.AgentData.SessionID = Client.Self.SessionID;
update.AgentData.HeadRotation = HeadRotation;
update.AgentData.BodyRotation = BodyRotation;
update.AgentData.CameraAtAxis = xAxis;
update.AgentData.CameraCenter = origin;
update.AgentData.CameraLeftAxis = yAxis;
update.AgentData.CameraUpAxis = zAxis;
update.AgentData.Far = Camera.Far;
update.AgentData.State = (byte)State;
update.AgentData.ControlFlags = agentControls;
update.AgentData.Flags = (byte)Flags;
Client.Network.SendPacket(update, simulator);
if (autoResetControls) {
ResetControlFlags();
}
}
}
/// <summary>
/// Builds an AgentUpdate packet entirely from parameters. This
/// will not touch the state of Self.Movement or
/// Self.Movement.Camera in any way
/// </summary>
/// <param name="controlFlags"></param>
/// <param name="position"></param>
/// <param name="forwardAxis"></param>
/// <param name="leftAxis"></param>
/// <param name="upAxis"></param>
/// <param name="bodyRotation"></param>
/// <param name="headRotation"></param>
/// <param name="farClip"></param>
/// <param name="reliable"></param>
/// <param name="flags"></param>
/// <param name="state"></param>
public void SendManualUpdate(AgentManager.ControlFlags controlFlags, Vector3 position, Vector3 forwardAxis,
Vector3 leftAxis, Vector3 upAxis, Quaternion bodyRotation, Quaternion headRotation, float farClip,
AgentFlags flags, AgentState state, bool reliable)
{
// Since version 1.40.4 of the Linden simulator, sending this update
// causes corruption of the agent position in the simulator
if (Client.Network.CurrentSim != null && (!Client.Network.CurrentSim.HandshakeComplete))
return;
AgentUpdatePacket update = new AgentUpdatePacket();
update.AgentData.AgentID = Client.Self.AgentID;
update.AgentData.SessionID = Client.Self.SessionID;
update.AgentData.BodyRotation = bodyRotation;
update.AgentData.HeadRotation = headRotation;
update.AgentData.CameraCenter = position;
update.AgentData.CameraAtAxis = forwardAxis;
update.AgentData.CameraLeftAxis = leftAxis;
update.AgentData.CameraUpAxis = upAxis;
update.AgentData.Far = farClip;
update.AgentData.ControlFlags = (uint)controlFlags;
update.AgentData.Flags = (byte)flags;
update.AgentData.State = (byte)state;
update.Header.Reliable = reliable;
Client.Network.SendPacket(update);
}
private bool GetControlFlag(ControlFlags flag)
{
return (agentControls & (uint)flag) != 0;
}
private void SetControlFlag(ControlFlags flag, bool value)
{
if (value) agentControls |= (uint)flag;
else agentControls &= ~((uint)flag);
}
public void ResetControlFlags()
{
// Reset all of the flags except for persistent settings like
// away, fly, mouselook, and crouching
agentControls &=
(uint)(ControlFlags.AGENT_CONTROL_AWAY |
ControlFlags.AGENT_CONTROL_FLY |
ControlFlags.AGENT_CONTROL_MOUSELOOK |
ControlFlags.AGENT_CONTROL_UP_NEG);
}
/// <summary>
/// Sends update of Field of Vision vertical angle to the simulator
/// </summary>
/// <param name="angle">Angle in radians</param>
public void SetFOVVerticalAngle(float angle)
{
OpenMetaverse.Packets.AgentFOVPacket msg = new OpenMetaverse.Packets.AgentFOVPacket();
msg.AgentData.AgentID = Client.Self.AgentID;
msg.AgentData.SessionID = Client.Self.SessionID;
msg.AgentData.CircuitCode = Client.Network.CircuitCode;
msg.FOVBlock.GenCounter = 0;
msg.FOVBlock.VerticalAngle = angle;
Client.Network.SendPacket(msg);
}
private void UpdateTimer_Elapsed(object obj)
{
if (Client.Network.Connected && Client.Settings.SEND_AGENT_UPDATES)
{
//Send an AgentUpdate packet
SendUpdate(false, Client.Network.CurrentSim);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Cache;
using System.Net.Http;
using System.Net.Test.Common;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Tests
{
public partial class HttpWebRequestTest : RemoteExecutorTestBase
{
private const string RequestBody = "This is data to POST.";
private readonly byte[] _requestBodyBytes = Encoding.UTF8.GetBytes(RequestBody);
private readonly NetworkCredential _explicitCredential = new NetworkCredential("user", "password", "domain");
private readonly ITestOutputHelper _output;
public static readonly object[][] EchoServers = System.Net.Test.Common.Configuration.Http.EchoServers;
public HttpWebRequestTest(ITestOutputHelper output)
{
_output = output;
}
[Theory, MemberData(nameof(EchoServers))]
public void Ctor_VerifyDefaults_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Null(request.Accept);
Assert.True(request.AllowAutoRedirect);
Assert.False(request.AllowReadStreamBuffering);
Assert.True(request.AllowWriteStreamBuffering);
Assert.Null(request.ContentType);
Assert.Equal(350, request.ContinueTimeout);
Assert.NotNull(request.ClientCertificates);
Assert.Null(request.CookieContainer);
Assert.Null(request.Credentials);
Assert.False(request.HaveResponse);
Assert.NotNull(request.Headers);
Assert.True(request.KeepAlive);
Assert.Equal(0, request.Headers.Count);
Assert.Equal(HttpVersion.Version11, request.ProtocolVersion);
Assert.Equal("GET", request.Method);
Assert.Equal(HttpWebRequest.DefaultMaximumResponseHeadersLength, 64);
Assert.NotNull(HttpWebRequest.DefaultCachePolicy);
Assert.Equal(HttpWebRequest.DefaultCachePolicy.Level, RequestCacheLevel.BypassCache);
Assert.Equal(PlatformDetection.IsFullFramework ? 64 : 0, HttpWebRequest.DefaultMaximumErrorResponseLength);
Assert.NotNull(request.Proxy);
Assert.Equal(remoteServer, request.RequestUri);
Assert.True(request.SupportsCookieContainer);
Assert.Equal(100000, request.Timeout);
Assert.False(request.UseDefaultCredentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void Ctor_CreateHttpWithString_ExpectNotNull(Uri remoteServer)
{
string remoteServerString = remoteServer.ToString();
HttpWebRequest request = WebRequest.CreateHttp(remoteServerString);
Assert.NotNull(request);
}
[Theory, MemberData(nameof(EchoServers))]
public void Ctor_CreateHttpWithUri_ExpectNotNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.NotNull(request);
}
[Theory, MemberData(nameof(EchoServers))]
public void Accept_SetThenGetValidValue_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
string acceptType = "*/*";
request.Accept = acceptType;
Assert.Equal(acceptType, request.Accept);
}
[Theory, MemberData(nameof(EchoServers))]
public void Accept_SetThenGetEmptyValue_ExpectNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Accept = string.Empty;
Assert.Null(request.Accept);
}
[Theory, MemberData(nameof(EchoServers))]
public void Accept_SetThenGetNullValue_ExpectNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Accept = null;
Assert.Null(request.Accept);
}
[Theory, MemberData(nameof(EchoServers))]
public void AllowReadStreamBuffering_SetFalseThenGet_ExpectFalse(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AllowReadStreamBuffering = false;
Assert.False(request.AllowReadStreamBuffering);
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "not supported on .NET Framework")]
[Theory, MemberData(nameof(EchoServers))]
public void AllowReadStreamBuffering_SetTrueThenGet_ExpectTrue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AllowReadStreamBuffering = true;
Assert.True(request.AllowReadStreamBuffering);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task ContentLength_Get_ExpectSameAsGetResponseStream(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
using (WebResponse response = await request.GetResponseAsync())
using (Stream myStream = response.GetResponseStream())
using (StreamReader sr = new StreamReader(myStream))
{
string strContent = sr.ReadToEnd();
long length = response.ContentLength;
Assert.Equal(strContent.Length, length);
}
}
[Theory, MemberData(nameof(EchoServers))]
public void ContentLength_SetNegativeOne_ThrowsArgumentOutOfRangeException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.ContentLength = -1);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContentLength_SetThenGetOne_Success(Uri remoteServer)
{
const int ContentLength = 1;
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContentLength = ContentLength;
Assert.Equal(ContentLength, request.ContentLength);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContentType_SetThenGet_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
string myContent = "application/x-www-form-urlencoded";
request.ContentType = myContent;
Assert.Equal(myContent, request.ContentType);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContentType_SetThenGetEmptyValue_ExpectNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContentType = string.Empty;
Assert.Null(request.ContentType);
}
[Fact]
public async Task Headers_SetAfterRequestSubmitted_ThrowsInvalidOperationException()
{
await LoopbackServer.CreateServerAsync(async (server, uri) =>
{
HttpWebRequest request = WebRequest.CreateHttp(uri);
Task<WebResponse> getResponse = request.GetResponseAsync();
await LoopbackServer.ReadRequestAndSendResponseAsync(server);
using (WebResponse response = await getResponse)
{
Assert.Throws<InvalidOperationException>(() => request.AutomaticDecompression = DecompressionMethods.Deflate);
Assert.Throws<InvalidOperationException>(() => request.ContentLength = 255);
Assert.Throws<InvalidOperationException>(() => request.ContinueTimeout = 255);
Assert.Throws<InvalidOperationException>(() => request.Host = "localhost");
Assert.Throws<InvalidOperationException>(() => request.MaximumResponseHeadersLength = 255);
Assert.Throws<InvalidOperationException>(() => request.SendChunked = true);
Assert.Throws<InvalidOperationException>(() => request.Proxy = WebRequest.DefaultWebProxy);
Assert.Throws<InvalidOperationException>(() => request.Headers = null);
}
});
}
[Theory, MemberData(nameof(EchoServers))]
public void MaximumResponseHeadersLength_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.MaximumResponseHeadersLength = -2);
}
[Theory, MemberData(nameof(EchoServers))]
public void MaximumResponseHeadersLength_SetThenGetNegativeOne_Success(Uri remoteServer)
{
const int MaximumResponseHeaderLength = -1;
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.MaximumResponseHeadersLength = MaximumResponseHeaderLength;
Assert.Equal(MaximumResponseHeaderLength, request.MaximumResponseHeadersLength);
}
[Theory, MemberData(nameof(EchoServers))]
public void MaximumAutomaticRedirections_SetZeroOrNegative_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.MaximumAutomaticRedirections = 0);
AssertExtensions.Throws<ArgumentException>("value", () => request.MaximumAutomaticRedirections = -1);
}
[Theory, MemberData(nameof(EchoServers))]
public void MaximumAutomaticRedirections_SetThenGetOne_Success(Uri remoteServer)
{
const int MaximumAutomaticRedirections = 1;
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.MaximumAutomaticRedirections = MaximumAutomaticRedirections;
Assert.Equal(MaximumAutomaticRedirections, request.MaximumAutomaticRedirections);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueTimeout_SetThenGetZero_ExpectZero(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContinueTimeout = 0;
Assert.Equal(0, request.ContinueTimeout);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueTimeout_SetNegativeOne_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContinueTimeout = -1;
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueTimeout_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.ContinueTimeout = -2);
}
[Theory, MemberData(nameof(EchoServers))]
public void Timeout_SetThenGetZero_ExpectZero(Uri remoteServer)
{
const int Timeout = 0;
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Timeout = Timeout;
Assert.Equal(Timeout, request.Timeout);
}
[Theory, MemberData(nameof(EchoServers))]
public void Timeout_SetNegativeOne_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Timeout = -1;
}
[Theory, MemberData(nameof(EchoServers))]
public void Timeout_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.Timeout = -2);
}
[Theory, MemberData(nameof(EchoServers))]
public void TimeOut_SetThenGet_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Timeout = 100;
Assert.Equal(100, request.Timeout);
request.Timeout = Threading.Timeout.Infinite;
Assert.Equal(Threading.Timeout.Infinite, request.Timeout);
request.Timeout = int.MaxValue;
Assert.Equal(int.MaxValue, request.Timeout);
}
[ActiveIssue(22627)]
[Fact]
public async Task Timeout_SetTenMillisecondsOnLoopback_ThrowsWebException()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Timeout = 10; // ms.
var sw = Stopwatch.StartNew();
WebException exception = Assert.Throws<WebException>(() => request.GetResponse());
sw.Stop();
Assert.InRange(sw.ElapsedMilliseconds, 1, 15 * 1000);
Assert.Equal(WebExceptionStatus.Timeout, exception.Status);
Assert.Equal(null, exception.InnerException);
Assert.Equal(null, exception.Response);
return Task.FromResult<object>(null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void Address_CtorAddress_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Equal(remoteServer, request.Address);
}
[Theory, MemberData(nameof(EchoServers))]
public void UserAgent_SetThenGetWindows_ValuesMatch(Uri remoteServer)
{
const string UserAgent = "Windows";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.UserAgent = UserAgent;
Assert.Equal(UserAgent, request.UserAgent);
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_SetNullValue_ThrowsArgumentNullException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentNullException>("value", null, () => request.Host = null);
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_SetSlash_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", null, () => request.Host = "/localhost");
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_SetInvalidUri_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", null, () => request.Host = "NoUri+-*");
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_SetThenGetCustomUri_ValuesMatch(Uri remoteServer)
{
const string Host = "localhost";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Host = Host;
Assert.Equal(Host, request.Host);
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_SetThenGetCustomUriWithPort_ValuesMatch(Uri remoteServer)
{
const string Host = "localhost:8080";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Host = Host;
Assert.Equal(Host, request.Host);
}
[Theory, MemberData(nameof(EchoServers))]
public void Host_GetDefaultHostSameAsAddress_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Equal(remoteServer.Host, request.Host);
}
[Theory]
[InlineData("https://microsoft.com:8080")]
public void Host_GetDefaultHostWithCustomPortSameAsAddress_ValuesMatch(string endpoint)
{
Uri endpointUri = new Uri(endpoint);
HttpWebRequest request = WebRequest.CreateHttp(endpointUri);
Assert.Equal(endpointUri.Host + ":" + endpointUri.Port, request.Host);
}
[Theory, MemberData(nameof(EchoServers))]
public void Pipelined_SetThenGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Pipelined = true;
Assert.True(request.Pipelined);
request.Pipelined = false;
Assert.False(request.Pipelined);
}
[Theory, MemberData(nameof(EchoServers))]
public void Referer_SetThenGetReferer_ValuesMatch(Uri remoteServer)
{
const string Referer = "Referer";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Referer = Referer;
Assert.Equal(Referer, request.Referer);
}
[Theory, MemberData(nameof(EchoServers))]
public void TransferEncoding_NullOrWhiteSpace_ValuesMatch(Uri remoteServer)
{
const string TransferEncoding = "xml";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.SendChunked = true;
request.TransferEncoding = TransferEncoding;
Assert.Equal(TransferEncoding, request.TransferEncoding);
request.TransferEncoding = null;
Assert.Equal(null, request.TransferEncoding);
}
[Theory, MemberData(nameof(EchoServers))]
public void TransferEncoding_SetChunked_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.TransferEncoding = "chunked");
}
[Theory, MemberData(nameof(EchoServers))]
public void TransferEncoding_SetWithSendChunkedFalse_ThrowsInvalidOperationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Throws<InvalidOperationException>(() => request.TransferEncoding = "xml");
}
[Theory, MemberData(nameof(EchoServers))]
public void KeepAlive_SetThenGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.KeepAlive = true;
Assert.True(request.KeepAlive);
request.KeepAlive = false;
Assert.False(request.KeepAlive);
}
[Theory]
[InlineData(null)]
[InlineData(false)]
[InlineData(true)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #19225")]
public void KeepAlive_CorrectConnectionHeaderSent(bool? keepAlive)
{
HttpWebRequest request = WebRequest.CreateHttp(Test.Common.Configuration.Http.RemoteEchoServer);
if (keepAlive.HasValue)
{
request.KeepAlive = keepAlive.Value;
}
using (var response = (HttpWebResponse)request.GetResponse())
using (var body = new StreamReader(response.GetResponseStream()))
{
string content = body.ReadToEnd();
if (!keepAlive.HasValue || keepAlive.Value)
{
// Validate that the request doesn't contain Connection: "close", but we can't validate
// that it does contain Connection: "keep-alive", as that's optional as of HTTP 1.1.
Assert.DoesNotContain("\"Connection\": \"close\"", content, StringComparison.OrdinalIgnoreCase);
}
else
{
Assert.Contains("\"Connection\": \"close\"", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("\"Keep-Alive\"", content, StringComparison.OrdinalIgnoreCase);
}
}
}
[Theory, MemberData(nameof(EchoServers))]
public void AutomaticDecompression_SetAndGetDeflate_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AutomaticDecompression = DecompressionMethods.Deflate;
Assert.Equal(DecompressionMethods.Deflate, request.AutomaticDecompression);
}
[Theory, MemberData(nameof(EchoServers))]
public void AllowWriteStreamBuffering_SetAndGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AllowWriteStreamBuffering = true;
Assert.True(request.AllowWriteStreamBuffering);
request.AllowWriteStreamBuffering = false;
Assert.False(request.AllowWriteStreamBuffering);
}
[Theory, MemberData(nameof(EchoServers))]
public void AllowAutoRedirect_SetAndGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AllowAutoRedirect = true;
Assert.True(request.AllowAutoRedirect);
request.AllowAutoRedirect = false;
Assert.False(request.AllowAutoRedirect);
}
[Fact]
public void ConnectionGroupName_SetAndGetGroup_ValuesMatch()
{
// Note: In CoreFX changing this value will not have any effect on HTTP stack's behavior.
// For app-compat reasons we allow applications to alter and read the property.
HttpWebRequest request = WebRequest.CreateHttp("http://test");
Assert.Null(request.ConnectionGroupName);
request.ConnectionGroupName = "Group";
Assert.Equal("Group", request.ConnectionGroupName);
}
[Theory, MemberData(nameof(EchoServers))]
public void PreAuthenticate_SetAndGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.PreAuthenticate = true;
Assert.True(request.PreAuthenticate);
request.PreAuthenticate = false;
Assert.False(request.PreAuthenticate);
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #19225")]
[Theory, MemberData(nameof(EchoServers))]
public void PreAuthenticate_SetAndGetBooleanResponse_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.PreAuthenticate = true;
using (var response = (HttpWebResponse)request.GetResponse())
{
Assert.True(request.PreAuthenticate);
}
}
[Theory, MemberData(nameof(EchoServers))]
public void Connection_NullOrWhiteSpace_ValuesMatch(Uri remoteServer)
{
const string Connection = "connect";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Connection = Connection;
Assert.Equal(Connection, request.Connection);
request.Connection = null;
Assert.Equal(null, request.Connection);
}
[Theory, MemberData(nameof(EchoServers))]
public void Connection_SetKeepAliveAndClose_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.Connection = "keep-alive");
AssertExtensions.Throws<ArgumentException>("value", () => request.Connection = "close");
}
[Theory, MemberData(nameof(EchoServers))]
public void Expect_SetNullOrWhiteSpace_ValuesMatch(Uri remoteServer)
{
const string Expect = "101-go";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Expect = Expect;
Assert.Equal(Expect, request.Expect);
request.Expect = null;
Assert.Equal(null, request.Expect);
}
[Theory, MemberData(nameof(EchoServers))]
public void Expect_Set100Continue_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.Expect = "100-continue");
}
[Fact]
public void DefaultMaximumResponseHeadersLength_SetAndGetLength_ValuesMatch()
{
RemoteInvoke(() =>
{
int defaultMaximumResponseHeadersLength = HttpWebRequest.DefaultMaximumResponseHeadersLength;
const int NewDefaultMaximumResponseHeadersLength = 255;
try
{
HttpWebRequest.DefaultMaximumResponseHeadersLength = NewDefaultMaximumResponseHeadersLength;
Assert.Equal(NewDefaultMaximumResponseHeadersLength, HttpWebRequest.DefaultMaximumResponseHeadersLength);
}
finally
{
HttpWebRequest.DefaultMaximumResponseHeadersLength = defaultMaximumResponseHeadersLength;
}
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void DefaultMaximumErrorResponseLength_SetAndGetLength_ValuesMatch()
{
RemoteInvoke(() =>
{
int defaultMaximumErrorsResponseLength = HttpWebRequest.DefaultMaximumErrorResponseLength;
const int NewDefaultMaximumErrorsResponseLength = 255;
try
{
HttpWebRequest.DefaultMaximumErrorResponseLength = NewDefaultMaximumErrorsResponseLength;
Assert.Equal(NewDefaultMaximumErrorsResponseLength, HttpWebRequest.DefaultMaximumErrorResponseLength);
}
finally
{
HttpWebRequest.DefaultMaximumErrorResponseLength = defaultMaximumErrorsResponseLength;
}
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void DefaultCachePolicy_SetAndGetPolicyReload_ValuesMatch()
{
RemoteInvoke(() =>
{
RequestCachePolicy requestCachePolicy = HttpWebRequest.DefaultCachePolicy;
try
{
RequestCachePolicy newRequestCachePolicy = new RequestCachePolicy(RequestCacheLevel.Reload);
HttpWebRequest.DefaultCachePolicy = newRequestCachePolicy;
Assert.Equal(newRequestCachePolicy.Level, HttpWebRequest.DefaultCachePolicy.Level);
}
finally
{
HttpWebRequest.DefaultCachePolicy = requestCachePolicy;
}
return SuccessExitCode;
}).Dispose();
}
[Theory, MemberData(nameof(EchoServers))]
public void IfModifiedSince_SetMinDateAfterValidDate_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
DateTime newIfModifiedSince = new DateTime(2000, 1, 1);
request.IfModifiedSince = newIfModifiedSince;
Assert.Equal(newIfModifiedSince, request.IfModifiedSince);
DateTime ifModifiedSince = DateTime.MinValue;
request.IfModifiedSince = ifModifiedSince;
Assert.Equal(ifModifiedSince, request.IfModifiedSince);
}
[Theory, MemberData(nameof(EchoServers))]
public void Date_SetMinDateAfterValidDate_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
DateTime newDate = new DateTime(2000, 1, 1);
request.Date = newDate;
Assert.Equal(newDate, request.Date);
DateTime date = DateTime.MinValue;
request.Date = date;
Assert.Equal(date, request.Date);
}
[Theory, MemberData(nameof(EchoServers))]
public void SendChunked_SetAndGetBoolean_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.SendChunked = true;
Assert.True(request.SendChunked);
request.SendChunked = false;
Assert.False(request.SendChunked);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueDelegate_SetNullDelegate_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContinueDelegate = null;
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueDelegate_SetDelegateThenGet_ValuesSame(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
HttpContinueDelegate continueDelegate = new HttpContinueDelegate((a, b) => { });
request.ContinueDelegate = continueDelegate;
Assert.Same(continueDelegate, request.ContinueDelegate);
}
[Theory, MemberData(nameof(EchoServers))]
public void ServicePoint_GetValue_ExpectedResult(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
if (PlatformDetection.IsFullFramework)
{
Assert.NotNull(request.ServicePoint);
}
else
{
Assert.Throws<PlatformNotSupportedException>(() => request.ServicePoint);
}
}
[Theory, MemberData(nameof(EchoServers))]
public void ServerCertificateValidationCallback_SetCallbackThenGet_ValuesSame(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
var serverCertificateVallidationCallback = new Security.RemoteCertificateValidationCallback((a, b, c, d) => true);
request.ServerCertificateValidationCallback = serverCertificateVallidationCallback;
Assert.Same(serverCertificateVallidationCallback, request.ServerCertificateValidationCallback);
}
[Theory, MemberData(nameof(EchoServers))]
public void ClientCertificates_SetNullX509_ThrowsArgumentNullException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentNullException>("value", () => request.ClientCertificates = null);
}
[Theory, MemberData(nameof(EchoServers))]
public void ClientCertificates_SetThenGetX509_ValuesSame(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
var certificateCollection = new System.Security.Cryptography.X509Certificates.X509CertificateCollection();
request.ClientCertificates = certificateCollection;
Assert.Same(certificateCollection, request.ClientCertificates);
}
[Theory, MemberData(nameof(EchoServers))]
public void ProtocolVersion_SetInvalidHttpVersion_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.ProtocolVersion = new Version());
}
[Theory, MemberData(nameof(EchoServers))]
public void ProtocolVersion_SetThenGetHttpVersions_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ProtocolVersion = HttpVersion.Version10;
Assert.Equal(HttpVersion.Version10, request.ProtocolVersion);
request.ProtocolVersion = HttpVersion.Version11;
Assert.Equal(HttpVersion.Version11, request.ProtocolVersion);
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP does not allow HTTP/1.0 requests.")]
[OuterLoop]
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task ProtocolVersion_SetThenSendRequest_CorrectHttpRequestVersionSent(bool isVersion10)
{
Version requestVersion = isVersion10 ? HttpVersion.Version10 : HttpVersion.Version11;
Version receivedRequestVersion = null;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.ProtocolVersion = requestVersion;
Task<WebResponse> getResponse = request.GetResponseAsync();
Task<List<string>> serverTask = LoopbackServer.ReadRequestAndSendResponseAsync(server);
using (HttpWebResponse response = (HttpWebResponse) await getResponse)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
List<string> receivedRequest = await serverTask;
string statusLine = receivedRequest[0];
if (statusLine.Contains("/1.0"))
{
receivedRequestVersion = HttpVersion.Version10;
}
else if (statusLine.Contains("/1.1"))
{
receivedRequestVersion = HttpVersion.Version11;
}
});
Assert.Equal(requestVersion, receivedRequestVersion);
}
[Fact]
public void ReadWriteTimeout_SetThenGet_ValuesMatch()
{
// Note: In CoreFX changing this value will not have any effect on HTTP stack's behavior.
// For app-compat reasons we allow applications to alter and read the property.
HttpWebRequest request = WebRequest.CreateHttp("http://test");
request.ReadWriteTimeout = 5;
Assert.Equal(5, request.ReadWriteTimeout);
}
[Fact]
public void ReadWriteTimeout_InfiniteValue_Ok()
{
HttpWebRequest request = WebRequest.CreateHttp("http://test");
request.ReadWriteTimeout = Timeout.Infinite;
}
[Fact]
public void ReadWriteTimeout_NegativeOrZeroValue_Fail()
{
HttpWebRequest request = WebRequest.CreateHttp("http://test");
Assert.Throws<ArgumentOutOfRangeException>(() => { request.ReadWriteTimeout = 0; });
Assert.Throws<ArgumentOutOfRangeException>(() => { request.ReadWriteTimeout = -10; });
}
[Theory, MemberData(nameof(EchoServers))]
public void CookieContainer_SetThenGetContainer_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.CookieContainer = null;
var cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
Assert.Same(cookieContainer, request.CookieContainer);
}
[Theory, MemberData(nameof(EchoServers))]
public void Credentials_SetDefaultCredentialsThenGet_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = CredentialCache.DefaultCredentials;
Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void Credentials_SetExplicitCredentialsThenGet_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = _explicitCredential;
Assert.Equal(_explicitCredential, request.Credentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void UseDefaultCredentials_SetTrue_CredentialsEqualsDefaultCredentials(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = _explicitCredential;
request.UseDefaultCredentials = true;
Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void UseDefaultCredentials_SetFalse_CredentialsNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = _explicitCredential;
request.UseDefaultCredentials = false;
Assert.Equal(null, request.Credentials);
}
[OuterLoop]
[Theory]
[MemberData(nameof(EchoServers))]
public void UseDefaultCredentials_SetGetResponse_ExpectSuccess(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.UseDefaultCredentials = true;
WebResponse response = request.GetResponse();
response.Dispose();
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_UseGETVerb_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_UseHEADVerb_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Head.Method;
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_UseCONNECTVerb_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = "CONNECT";
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
request.Abort();
WebException ex = Assert.Throws<WebException>(() => request.BeginGetRequestStream(null, null));
Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status);
}
[Theory, MemberData(nameof(EchoServers))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "no exception thrown on netfx")]
public void BeginGetRequestStream_CreatePostRequestThenCallTwice_ThrowsInvalidOperationException(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.Method = "POST";
IAsyncResult asyncResult = request.BeginGetRequestStream(null, null);
Assert.Throws<InvalidOperationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_CreateRequestThenBeginGetResponsePrior_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
IAsyncResult asyncResult = request.BeginGetResponse(null, null);
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
public async Task BeginGetResponse_CreateRequestThenCallTwice_ThrowsInvalidOperationException()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
IAsyncResult asyncResult = request.BeginGetResponse(null, null);
Assert.Throws<InvalidOperationException>(() => request.BeginGetResponse(null, null));
return Task.FromResult<object>(null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetResponse_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
request.Abort();
WebException ex = Assert.Throws<WebException>(() => request.BeginGetResponse(null, null));
Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status);
}
public async Task GetRequestStreamAsync_WriteAndDisposeRequestStreamThenOpenRequestStream_ThrowsArgumentException()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = HttpMethod.Post.Method;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length);
AssertExtensions.Throws<ArgumentException>(null, () => new StreamReader(requestStream));
}
});
}
public async Task GetRequestStreamAsync_SetPOSTThenGet_ExpectNotNull()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = HttpMethod.Post.Method;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
Assert.NotNull(requestStream);
}
});
}
public async Task GetResponseAsync_GetResponseStream_ExpectNotNull()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
using (WebResponse response = await request.GetResponseAsync())
{
Assert.NotNull(response.GetResponseStream());
}
});
}
[Theory, MemberData(nameof(EchoServers))]
public async Task GetResponseAsync_GetResponseStream_ContainsHost(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Get.Method;
using (WebResponse response = await request.GetResponseAsync())
using (Stream myStream = response.GetResponseStream())
{
Assert.NotNull(myStream);
using (var sr = new StreamReader(myStream))
{
string strContent = sr.ReadToEnd();
Assert.True(strContent.Contains("\"Host\": \"" + System.Net.Test.Common.Configuration.Http.Host + "\""));
}
}
}
[OuterLoop]
[Theory, MemberData(nameof(EchoServers))]
public void CookieContainer_Count_Add(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
DateTime now = DateTime.UtcNow;
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(remoteServer, new Cookie("1", "cookie1"));
request.CookieContainer.Add(remoteServer, new Cookie("2", "cookie2"));
Assert.True(request.SupportsCookieContainer);
Assert.Equal(request.CookieContainer.GetCookies(remoteServer).Count, 2);
}
[Theory, MemberData(nameof(EchoServers))]
public void Range_Add_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AddRange(1, 5);
Assert.Equal(request.Headers["Range"], "bytes=1-5");
}
[Theory, MemberData(nameof(EchoServers))]
public async Task GetResponseAsync_PostRequestStream_ContainsData(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length);
}
using (WebResponse response = await request.GetResponseAsync())
using (Stream myStream = response.GetResponseStream())
using (var sr = new StreamReader(myStream))
{
string strContent = sr.ReadToEnd();
Assert.True(strContent.Contains(RequestBody));
}
}
[Theory]
[MemberData(nameof(EchoServers))]
public async Task GetResponseAsync_UseDefaultCredentials_ExpectSuccess(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.UseDefaultCredentials = true;
var response = await request.GetResponseAsync();
response.Dispose();
}
[OuterLoop] // fails on networks with DNS servers that provide a dummy page for invalid addresses
[Fact]
public async Task GetResponseAsync_ServerNameNotInDns_ThrowsWebException()
{
string serverUrl = string.Format("http://www.{0}.com/", Guid.NewGuid().ToString());
HttpWebRequest request = WebRequest.CreateHttp(serverUrl);
WebException ex = await Assert.ThrowsAsync<WebException>(() => request.GetResponseAsync());
Assert.Equal(WebExceptionStatus.NameResolutionFailure, ex.Status);
}
public static object[][] StatusCodeServers = {
new object[] { System.Net.Test.Common.Configuration.Http.StatusCodeUri(false, 404) },
new object[] { System.Net.Test.Common.Configuration.Http.StatusCodeUri(true, 404) },
};
[Theory, MemberData(nameof(StatusCodeServers))]
public async Task GetResponseAsync_ResourceNotFound_ThrowsWebException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
WebException ex = await Assert.ThrowsAsync<WebException>(() => request.GetResponseAsync());
Assert.Equal(WebExceptionStatus.ProtocolError, ex.Status);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task HaveResponse_GetResponseAsync_ExpectTrue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
using (WebResponse response = await request.GetResponseAsync())
{
Assert.True(request.HaveResponse);
}
}
[Theory]
[MemberData(nameof(EchoServers))]
public async Task Headers_GetResponseHeaders_ContainsExpectedValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
{
string headersString = response.Headers.ToString();
string headersPartialContent = "Content-Type: application/json";
Assert.True(headersString.Contains(headersPartialContent));
}
}
[Theory, MemberData(nameof(EchoServers))]
public void Method_SetThenGetToGET_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Get.Method;
Assert.Equal(HttpMethod.Get.Method, request.Method);
}
[Theory, MemberData(nameof(EchoServers))]
public void Method_SetThenGetToPOST_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
Assert.Equal(HttpMethod.Post.Method, request.Method);
}
[Theory, MemberData(nameof(EchoServers))]
public void Method_SetInvalidString_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
AssertExtensions.Throws<ArgumentException>("value", () => request.Method = null);
AssertExtensions.Throws<ArgumentException>("value", () => request.Method = string.Empty);
AssertExtensions.Throws<ArgumentException>("value", () => request.Method = "Method(2");
}
[Theory, MemberData(nameof(EchoServers))]
public void Proxy_GetDefault_ExpectNotNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.NotNull(request.Proxy);
}
[Theory, MemberData(nameof(EchoServers))]
public void RequestUri_CreateHttpThenGet_ExpectSameUri(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Equal(remoteServer, request.RequestUri);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task ResponseUri_GetResponseAsync_ExpectSameUri(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
using (WebResponse response = await request.GetResponseAsync())
{
Assert.Equal(remoteServer, response.ResponseUri);
}
}
[Theory, MemberData(nameof(EchoServers))]
public void SupportsCookieContainer_GetDefault_ExpectTrue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.True(request.SupportsCookieContainer);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task SimpleScenario_UseGETVerb_Success(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using (Stream responseStream = response.GetResponseStream())
using (var sr = new StreamReader(responseStream))
{
string responseBody = sr.ReadToEnd();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[Theory, MemberData(nameof(EchoServers))]
public async Task SimpleScenario_UsePOSTVerb_Success(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using (Stream responseStream = response.GetResponseStream())
using (var sr = new StreamReader(responseStream))
{
string responseBody = sr.ReadToEnd();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[Theory, MemberData(nameof(EchoServers))]
public async Task ContentType_AddHeaderWithNoContent_SendRequest_HeaderGetsSent(Uri remoteServer)
{
const string ContentType = "text/plain; charset=utf-8";
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.ContentType = ContentType;
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using (Stream responseStream = response.GetResponseStream())
using (var sr = new StreamReader(responseStream))
{
string responseBody = sr.ReadToEnd();
_output.WriteLine(responseBody);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(responseBody.Contains($"\"Content-Type\": \"{ContentType}\""));
}
}
[Theory, MemberData(nameof(EchoServers))]
public void MediaType_SetThenGet_ValuesMatch(Uri remoteServer)
{
const string MediaType = "text/plain";
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.MediaType = MediaType;
Assert.Equal(MediaType, request.MediaType);
}
public async Task HttpWebRequest_EndGetRequestStreamContext_ExpectedValue()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
System.Net.TransportContext context;
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.Method = "POST";
using (request.EndGetRequestStream(request.BeginGetRequestStream(null, null), out context))
{
if (PlatformDetection.IsFullFramework)
{
Assert.NotNull(context);
}
else
{
Assert.Null(context);
}
}
return Task.FromResult<object>(null);
});
}
[ActiveIssue(19083)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #19083")]
[Fact]
public async Task Abort_BeginGetRequestStreamThenAbort_EndGetRequestStreamThrowsWebException()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = "POST";
RequestState state = new RequestState();
state.Request = request;
request.BeginGetResponse(new AsyncCallback(RequestStreamCallback), state);
request.Abort();
Assert.Equal(1, state.RequestStreamCallbackCallCount);
WebException wex = state.SavedRequestStreamException as WebException;
Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status);
return Task.FromResult<object>(null);
});
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "ResponseCallback not called after Abort on netfx")]
[Fact]
public async Task Abort_BeginGetResponseThenAbort_ResponseCallbackCalledBeforeAbortReturns()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
RequestState state = new RequestState();
state.Request = request;
request.BeginGetResponse(new AsyncCallback(ResponseCallback), state);
request.Abort();
Assert.Equal(1, state.ResponseCallbackCallCount);
return Task.FromResult<object>(null);
});
}
[ActiveIssue(18800)]
[Fact]
public async Task Abort_BeginGetResponseThenAbort_EndGetResponseThrowsWebException()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
RequestState state = new RequestState();
state.Request = request;
request.BeginGetResponse(new AsyncCallback(ResponseCallback), state);
request.Abort();
WebException wex = state.SavedResponseException as WebException;
Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status);
return Task.FromResult<object>(null);
});
}
[Fact]
public async Task Abort_BeginGetResponseUsingNoCallbackThenAbort_Success()
{
await LoopbackServer.CreateServerAsync((server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.BeginGetResponse(null, null);
request.Abort();
return Task.FromResult<object>(null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void Abort_CreateRequestThenAbort_Success(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.Abort();
}
private void RequestStreamCallback(IAsyncResult asynchronousResult)
{
RequestState state = (RequestState)asynchronousResult.AsyncState;
state.RequestStreamCallbackCallCount++;
try
{
HttpWebRequest request = state.Request;
state.Response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream stream = request.EndGetRequestStream(asynchronousResult);
stream.Dispose();
}
catch (Exception ex)
{
state.SavedRequestStreamException = ex;
}
}
private void ResponseCallback(IAsyncResult asynchronousResult)
{
RequestState state = (RequestState)asynchronousResult.AsyncState;
state.ResponseCallbackCallCount++;
try
{
using (HttpWebResponse response = (HttpWebResponse)state.Request.EndGetResponse(asynchronousResult))
{
state.SavedResponseHeaders = response.Headers;
}
}
catch (Exception ex)
{
state.SavedResponseException = ex;
}
}
[Fact]
public void HttpWebRequest_Serialize_Fails()
{
using (MemoryStream fs = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
var hwr = HttpWebRequest.CreateHttp("http://localhost");
// .NET Framework throws
// System.Runtime.Serialization.SerializationException:
// Type 'System.Net.WebRequest+WebProxyWrapper' in Assembly 'System, Version=4.0.0.
// 0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
// While .NET Core throws
// System.Runtime.Serialization.SerializationException:
// Type 'System.Net.HttpWebRequest' in Assembly 'System.Net.Requests, Version=4.0.0.
// 0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
Assert.Throws<System.Runtime.Serialization.SerializationException>(() => formatter.Serialize(fs, hwr));
}
}
}
public class RequestState
{
public HttpWebRequest Request;
public HttpWebResponse Response;
public WebHeaderCollection SavedResponseHeaders;
public int RequestStreamCallbackCallCount;
public int ResponseCallbackCallCount;
public Exception SavedRequestStreamException;
public Exception SavedResponseException;
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
using Microsoft.VisualStudioTools;
namespace Microsoft.PythonTools.Debugger.DebugEngine {
// Represents a logical stack frame on the thread stack.
// Also implements the IDebugExpressionContext interface, which allows expression evaluation and watch windows.
class AD7StackFrame : IDebugStackFrame2, IDebugExpressionContext2, IDebugProperty2 {
private readonly AD7Engine _engine;
private readonly AD7Thread _thread;
private readonly PythonStackFrame _stackFrame;
// An array of this frame's parameters
private PythonEvaluationResult[] _parameters;
// An array of this frame's locals
private PythonEvaluationResult[] _locals;
public AD7StackFrame(AD7Engine engine, AD7Thread thread, PythonStackFrame threadContext) {
_engine = engine;
_thread = thread;
_stackFrame = threadContext;
_parameters = threadContext.Parameters.ToArray();
_locals = threadContext.Locals.ToArray();
}
public PythonStackFrame StackFrame {
get {
return _stackFrame;
}
}
public AD7Engine Engine {
get {
return _engine;
}
}
public AD7Thread Thread {
get {
return _thread;
}
}
#region Non-interface methods
// Construct a FRAMEINFO for this stack frame with the requested information.
public void SetFrameInfo(enum_FRAMEINFO_FLAGS dwFieldSpec, out FRAMEINFO frameInfo) {
frameInfo = new FRAMEINFO();
// The debugger is asking for the formatted name of the function which is displayed in the callstack window.
// There are several optional parts to this name including the module, argument types and values, and line numbers.
// The optional information is requested by setting flags in the dwFieldSpec parameter.
if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME) != 0) {
string funcName = _stackFrame.GetQualifiedFunctionName();
if (funcName == "<module>") {
if (CommonUtils.IsValidPath(_stackFrame.FileName)) {
funcName = Path.GetFileNameWithoutExtension(_stackFrame.FileName) + " module";
} else if (_stackFrame.FileName.EndsWith("<string>")) {
funcName = "<exec or eval>";
} else if (_stackFrame.FileName.EndsWith("<stdin>")) {
funcName = "<REPL input>";
} else {
funcName = _stackFrame.FileName + " unknown code";
}
} else if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_MODULE) != 0) {
if (CommonUtils.IsValidPath(_stackFrame.FileName)) {
funcName += " in " + Path.GetFileNameWithoutExtension(_stackFrame.FileName);
} else {
funcName += " in " + _stackFrame.FileName;
}
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_MODULE;
}
frameInfo.m_bstrFuncName = funcName;
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_FUNCNAME;
if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_LINES) != 0) {
frameInfo.m_bstrFuncName = funcName + " line " + _stackFrame.LineNo;
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_LINES;
}
}
if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_LANGUAGE) != 0) {
switch (_stackFrame.Kind) {
case FrameKind.Python:
frameInfo.m_bstrLanguage = "Python";
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_LANGUAGE;
break;
case FrameKind.Django:
frameInfo.m_bstrLanguage = "Django Templates";
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_LANGUAGE;
break;
}
}
// The debugger is requesting the name of the module for this stack frame.
if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_MODULE) != 0) {
if (CommonUtils.IsValidPath(_stackFrame.FileName)) {
frameInfo.m_bstrModule = Path.GetFileNameWithoutExtension(this._stackFrame.FileName);
} else if (_stackFrame.FileName.EndsWith("<string>")) {
frameInfo.m_bstrModule = "<exec/eval>";
} else if (_stackFrame.FileName.EndsWith("<stdin>")) {
frameInfo.m_bstrModule = "<REPL>";
} else {
frameInfo.m_bstrModule = "<unknown>";
}
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_MODULE;
}
// The debugger is requesting the IDebugStackFrame2 value for this frame info.
if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FRAME) != 0) {
frameInfo.m_pFrame = this;
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_FRAME;
}
// Does this stack frame of symbols loaded?
if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_DEBUGINFO) != 0) {
frameInfo.m_fHasDebugInfo = 1;
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_DEBUGINFO;
}
// Is this frame stale?
if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_STALECODE) != 0) {
frameInfo.m_fStaleCode = 0;
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_STALECODE;
}
// The debugger would like a pointer to the IDebugModule2 that contains this stack frame.
if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_DEBUG_MODULEP) != 0) {
// TODO: Module
/*
if (module != null)
{
AD7Module ad7Module = (AD7Module)module.Client;
Debug.Assert(ad7Module != null);
frameInfo.m_pModule = ad7Module;
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_DEBUG_MODULEP;
}*/
}
}
// Construct an instance of IEnumDebugPropertyInfo2 for the combined locals and parameters.
private void CreateLocalsPlusArgsProperties(uint radix, out uint elementsReturned, out IEnumDebugPropertyInfo2 enumObject) {
elementsReturned = 0;
int localsLength = 0;
if (_locals != null) {
localsLength = _locals.Length;
elementsReturned += (uint)localsLength;
}
if (_parameters != null) {
elementsReturned += (uint)_parameters.Length;
}
DEBUG_PROPERTY_INFO[] propInfo = new DEBUG_PROPERTY_INFO[elementsReturned];
if (_locals != null) {
for (int i = 0; i < _locals.Length; i++) {
AD7Property property = new AD7Property(this, _locals[i], true);
propInfo[i] = property.ConstructDebugPropertyInfo(radix, enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_STANDARD);
}
}
if (_parameters != null) {
for (int i = 0; i < _parameters.Length; i++) {
AD7Property property = new AD7Property(this, _parameters[i], true);
propInfo[localsLength + i] = property.ConstructDebugPropertyInfo(radix, enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_STANDARD);
}
}
enumObject = new AD7PropertyInfoEnum(propInfo);
}
// Construct an instance of IEnumDebugPropertyInfo2 for the locals collection only.
private void CreateLocalProperties(uint radix, out uint elementsReturned, out IEnumDebugPropertyInfo2 enumObject) {
elementsReturned = (uint)_locals.Length;
DEBUG_PROPERTY_INFO[] propInfo = new DEBUG_PROPERTY_INFO[_locals.Length];
for (int i = 0; i < propInfo.Length; i++) {
AD7Property property = new AD7Property(this, _locals[i], true);
propInfo[i] = property.ConstructDebugPropertyInfo(radix, enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_STANDARD);
}
enumObject = new AD7PropertyInfoEnum(propInfo);
}
// Construct an instance of IEnumDebugPropertyInfo2 for the parameters collection only.
private void CreateParameterProperties(uint radix, out uint elementsReturned, out IEnumDebugPropertyInfo2 enumObject) {
elementsReturned = (uint)_parameters.Length;
DEBUG_PROPERTY_INFO[] propInfo = new DEBUG_PROPERTY_INFO[_parameters.Length];
for (int i = 0; i < propInfo.Length; i++) {
AD7Property property = new AD7Property(this, _parameters[i], true);
propInfo[i] = property.ConstructDebugPropertyInfo(radix, enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_STANDARD);
}
enumObject = new AD7PropertyInfoEnum(propInfo);
}
#endregion
#region IDebugStackFrame2 Members
// Creates an enumerator for properties associated with the stack frame, such as local variables.
// The sample engine only supports returning locals and parameters. Other possible values include
// class fields (this pointer), registers, exceptions...
int IDebugStackFrame2.EnumProperties(enum_DEBUGPROP_INFO_FLAGS dwFields, uint nRadix, ref Guid guidFilter, uint dwTimeout, out uint elementsReturned, out IEnumDebugPropertyInfo2 enumObject) {
int hr;
elementsReturned = 0;
enumObject = null;
if (guidFilter == DebuggerConstants.guidFilterLocalsPlusArgs ||
guidFilter == DebuggerConstants.guidFilterAllLocalsPlusArgs ||
guidFilter == DebuggerConstants.guidFilterAllLocals) {
CreateLocalsPlusArgsProperties(nRadix, out elementsReturned, out enumObject);
hr = VSConstants.S_OK;
} else if (guidFilter == DebuggerConstants.guidFilterLocals) {
CreateLocalProperties(nRadix, out elementsReturned, out enumObject);
hr = VSConstants.S_OK;
} else if (guidFilter == DebuggerConstants.guidFilterArgs) {
CreateParameterProperties(nRadix, out elementsReturned, out enumObject);
hr = VSConstants.S_OK;
} else {
hr = VSConstants.E_NOTIMPL;
}
return hr;
}
// Gets the code context for this stack frame. The code context represents the current instruction pointer in this stack frame.
int IDebugStackFrame2.GetCodeContext(out IDebugCodeContext2 memoryAddress) {
memoryAddress = new AD7MemoryAddress(_engine, _stackFrame.FileName, (uint)_stackFrame.LineNo, _stackFrame);
return VSConstants.S_OK;
}
// Gets a description of the properties of a stack frame.
// Calling the IDebugProperty2::EnumChildren method with appropriate filters can retrieve the local variables, method parameters, registers, and "this"
// pointer associated with the stack frame. The debugger calls EnumProperties to obtain these values in the sample.
int IDebugStackFrame2.GetDebugProperty(out IDebugProperty2 property) {
property = this;
return VSConstants.S_OK;
}
// Gets the document context for this stack frame. The debugger will call this when the current stack frame is changed
// and will use it to open the correct source document for this stack frame.
int IDebugStackFrame2.GetDocumentContext(out IDebugDocumentContext2 docContext) {
docContext = null;
// Assume all lines begin and end at the beginning of the line.
TEXT_POSITION begTp = new TEXT_POSITION();
begTp.dwColumn = 0;
begTp.dwLine = (uint)_stackFrame.LineNo - 1;
TEXT_POSITION endTp = new TEXT_POSITION();
endTp.dwColumn = 0;
endTp.dwLine = (uint)_stackFrame.LineNo - 1;
docContext = new AD7DocumentContext(_stackFrame.FileName, begTp, endTp, null, _stackFrame.Kind);
return VSConstants.S_OK;
}
// Gets an evaluation context for expression evaluation within the current context of a stack frame and thread.
// Generally, an expression evaluation context can be thought of as a scope for performing expression evaluation.
// Call the IDebugExpressionContext2::ParseText method to parse an expression and then call the resulting IDebugExpression2::EvaluateSync
// or IDebugExpression2::EvaluateAsync methods to evaluate the parsed expression.
int IDebugStackFrame2.GetExpressionContext(out IDebugExpressionContext2 ppExprCxt) {
ppExprCxt = (IDebugExpressionContext2)this;
return VSConstants.S_OK;
}
// Gets a description of the stack frame.
int IDebugStackFrame2.GetInfo(enum_FRAMEINFO_FLAGS dwFieldSpec, uint nRadix, FRAMEINFO[] pFrameInfo) {
SetFrameInfo(dwFieldSpec, out pFrameInfo[0]);
return VSConstants.S_OK;
}
// Gets the language associated with this stack frame.
// In this sample, all the supported stack frames are C++
int IDebugStackFrame2.GetLanguageInfo(ref string pbstrLanguage, ref Guid pguidLanguage) {
_stackFrame.Kind.GetLanguageInfo(ref pbstrLanguage, ref pguidLanguage);
return VSConstants.S_OK;
}
// Gets the name of the stack frame.
// The name of a stack frame is typically the name of the method being executed.
int IDebugStackFrame2.GetName(out string name) {
name = this._stackFrame.FunctionName;
return 0;
}
// Gets a machine-dependent representation of the range of physical addresses associated with a stack frame.
int IDebugStackFrame2.GetPhysicalStackRange(out ulong addrMin, out ulong addrMax) {
addrMin = 0;
addrMax = 0;
return VSConstants.S_OK;
}
// Gets the thread associated with a stack frame.
int IDebugStackFrame2.GetThread(out IDebugThread2 thread) {
thread = _thread;
return VSConstants.S_OK;
}
#endregion
#region IDebugExpressionContext2 Members
// Retrieves the name of the evaluation context.
// The name is the description of this evaluation context. It is typically something that can be parsed by an expression evaluator
// that refers to this exact evaluation context. For example, in C++ the name is as follows:
// "{ function-name, source-file-name, module-file-name }"
int IDebugExpressionContext2.GetName(out string pbstrName) {
pbstrName = String.Format("{{ {0} {1} }}", this._stackFrame.FunctionName, this._stackFrame.FileName);
return VSConstants.S_OK;
}
// Parses a text-based expression for evaluation.
// The engine sample only supports locals and parameters so the only task here is to check the names in those collections.
int IDebugExpressionContext2.ParseText(string pszCode,
enum_PARSEFLAGS dwFlags,
uint nRadix,
out IDebugExpression2 ppExpr,
out string pbstrError,
out uint pichError) {
pbstrError = "";
pichError = 0;
ppExpr = null;
if (_parameters != null) {
foreach (var currVariable in _parameters) {
if (String.CompareOrdinal(currVariable.Expression, pszCode) == 0) {
ppExpr = new UncalculatedAD7Expression(this, currVariable.Expression, true);
return VSConstants.S_OK;
}
}
}
if (_locals != null) {
foreach (var currVariable in _locals) {
if (String.CompareOrdinal(currVariable.Expression, pszCode) == 0) {
ppExpr = new UncalculatedAD7Expression(this, currVariable.Expression, true);
return VSConstants.S_OK;
}
}
}
string errorMsg;
if (!_stackFrame.TryParseText(pszCode, out errorMsg)) {
pbstrError = "Error: " + errorMsg;
pichError = (uint)pbstrError.Length;
}
ppExpr = new UncalculatedAD7Expression(this, pszCode);
return VSConstants.S_OK;
}
#endregion
int IDebugProperty2.EnumChildren(enum_DEBUGPROP_INFO_FLAGS dwFields, uint dwRadix, ref Guid guidFilter, enum_DBG_ATTRIB_FLAGS dwAttribFilter, string pszNameFilter, uint dwTimeout, out IEnumDebugPropertyInfo2 ppEnum) {
int hr;
uint elementsReturned = 0;
ppEnum = null;
if (guidFilter == DebuggerConstants.guidFilterLocalsPlusArgs ||
guidFilter == DebuggerConstants.guidFilterAllLocalsPlusArgs ||
guidFilter == DebuggerConstants.guidFilterAllLocals) {
CreateLocalsPlusArgsProperties(dwRadix, out elementsReturned, out ppEnum);
hr = VSConstants.S_OK;
} else if (guidFilter == DebuggerConstants.guidFilterLocals) {
CreateLocalProperties(dwRadix, out elementsReturned, out ppEnum);
hr = VSConstants.S_OK;
} else if (guidFilter == DebuggerConstants.guidFilterArgs) {
CreateParameterProperties(dwRadix, out elementsReturned, out ppEnum);
hr = VSConstants.S_OK;
} else {
hr = VSConstants.E_NOTIMPL;
}
return hr;
}
int IDebugProperty2.GetDerivedMostProperty(out IDebugProperty2 ppDerivedMost) {
ppDerivedMost = null;
return VSConstants.E_NOTIMPL;
}
int IDebugProperty2.GetExtendedInfo(ref Guid guidExtendedInfo, out object pExtendedInfo) {
pExtendedInfo = null;
return VSConstants.E_NOTIMPL;
}
int IDebugProperty2.GetMemoryBytes(out IDebugMemoryBytes2 ppMemoryBytes) {
ppMemoryBytes = null;
return VSConstants.E_NOTIMPL;
}
int IDebugProperty2.GetMemoryContext(out IDebugMemoryContext2 ppMemory) {
ppMemory = null;
return VSConstants.E_NOTIMPL;
}
int IDebugProperty2.GetParent(out IDebugProperty2 ppParent) {
ppParent = null;
return VSConstants.E_NOTIMPL;
}
int IDebugProperty2.GetPropertyInfo(enum_DEBUGPROP_INFO_FLAGS dwFields, uint dwRadix, uint dwTimeout, IDebugReference2[] rgpArgs, uint dwArgCount, DEBUG_PROPERTY_INFO[] pPropertyInfo) {
return VSConstants.E_NOTIMPL;
}
int IDebugProperty2.GetReference(out IDebugReference2 ppReference) {
ppReference = null;
return VSConstants.E_NOTIMPL;
}
int IDebugProperty2.GetSize(out uint pdwSize) {
pdwSize = 0;
return VSConstants.E_NOTIMPL;
}
int IDebugProperty2.SetValueAsReference(IDebugReference2[] rgpArgs, uint dwArgCount, IDebugReference2 pValue, uint dwTimeout) {
return VSConstants.E_NOTIMPL;
}
int IDebugProperty2.SetValueAsString(string pszValue, uint dwRadix, uint dwTimeout) {
return VSConstants.E_NOTIMPL;
}
}
}
| |
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------
// <copyright file="EventSource.cs">(c) 2017 Mike Fourie and Contributors (https://github.com/mikefourie/MSBuildExtensionPack) under MIT License. See https://opensource.org/licenses/MIT </copyright>
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------
namespace MSBuild.ExtensionPack.Computer
{
using System;
using System.Diagnostics;
using System.Globalization;
using Microsoft.Build.Framework;
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>CheckExists</i> (<b>Required: </b>Source <b>Optional: </b>MachineName <b>Output: </b>Exists)</para>
/// <para><i>Create</i> (<b>Required: </b>Source, LogName <b>Optional: </b>Force, MachineName, CategoryCount, MessageResourceFile, CategoryResourceFile, ParameterResourceFile)</para>
/// <para><i>Delete</i> (<b>Required: </b>Source <b>Optional: </b>MachineName)</para>
/// <para><i>Log</i> (<b>Required: </b> Source, Description, LogType, EventId, LogName<b>Optional: </b>MachineName)</para>
/// <para><b>Remote Execution Support:</b> Yes</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <Target Name="Default">
/// <!-- Delete an event source -->
/// <MSBuild.ExtensionPack.Computer.EventSource TaskAction="Delete" Source="MyEventSource" LogName="Application"/>
/// <!-- Check an event source exists -->
/// <MSBuild.ExtensionPack.Computer.EventSource TaskAction="CheckExists" Source="MyEventSource" LogName="Application">
/// <Output TaskParameter="Exists" PropertyName="DoesExist"/>
/// </MSBuild.ExtensionPack.Computer.EventSource>
/// <Message Text="Exists: $(DoesExist)"/>
/// <!-- Create an event source -->
/// <MSBuild.ExtensionPack.Computer.EventSource TaskAction="Create" Source="MyEventSource" LogName="Application"/>
/// <MSBuild.ExtensionPack.Computer.EventSource TaskAction="CheckExists" Source="MyEventSource" LogName="Application">
/// <Output TaskParameter="Exists" PropertyName="DoesExist"/>
/// </MSBuild.ExtensionPack.Computer.EventSource>
/// <Message Text="Exists: $(DoesExist)"/>
/// <!-- Log an event -->
/// <MSBuild.ExtensionPack.Computer.EventSource TaskAction="Log" Source="MyEventSource" Description="Hello" LogType="Information" EventId="222"/>
/// </Target>
/// </Project>
/// ]]></code>
/// </example>
public class EventSource : BaseTask
{
private System.Diagnostics.EventLogEntryType logType = System.Diagnostics.EventLogEntryType.Error;
/// <summary>
/// Sets the event id.
/// </summary>
public string EventId { get; set; }
/// <summary>
/// Sets the Event Log Entry Type. Possible values are: Error, FailureAudit, Information, SuccessAudit, Warning.
/// </summary>
public string LogType
{
get => this.logType.ToString();
set => this.logType = (System.Diagnostics.EventLogEntryType)Enum.Parse(typeof(System.Diagnostics.EventLogEntryType), value);
}
/// <summary>
/// Sets the description for the logentry
/// </summary>
public string Description { get; set; }
/// <summary>
/// Sets the source name
/// </summary>
[Required]
public string Source { get; set; }
/// <summary>
/// Sets the name of the log the source's entries are written to, e.g Application, Security, System, YOUREVENTLOG.
/// </summary>
public string LogName { get; set; }
/// <summary>
/// Set to true to delete any existing matching eventsource when creating
/// </summary>
public bool Force { get; set; }
/// <summary>
/// Sets the number of categories in the category resource file
/// </summary>
public int CategoryCount { get; set; }
/// <summary>
/// Sets the path of the message resource file to configure an event log source to write localized event messages
/// </summary>
public string MessageResourceFile { get; set; }
/// <summary>
/// Sets the path of the category resource file to write events with localized category strings
/// </summary>
public string CategoryResourceFile { get; set; }
/// <summary>
/// Sets the path of the parameter resource file to configure an event log source to write localized event messages with inserted parameter strings
/// </summary>
public string ParameterResourceFile { get; set; }
/// <summary>
/// Gets a value indicating whether the EventSource exists.
/// </summary>
[Output]
public bool Exists { get; set; }
/// <summary>
/// Performs the action of this task.
/// </summary>
protected override void InternalExecute()
{
switch (this.TaskAction)
{
case "Create":
this.Create();
break;
case "CheckExists":
this.CheckExists();
break;
case "Delete":
this.Delete();
break;
case "Log":
this.LogEvent();
break;
default:
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
return;
}
}
private void Delete()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Deleting EventSource: {0}", this.Source));
if (System.Diagnostics.EventLog.SourceExists(this.Source, this.MachineName))
{
System.Diagnostics.EventLog.DeleteEventSource(this.Source, this.MachineName);
}
}
private void LogEvent()
{
// Validation
if (string.IsNullOrEmpty(this.EventId))
{
this.Log.LogError("EventId must be specified");
return;
}
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Logging to EventSource: {0}", this.Source));
if (!System.Diagnostics.EventLog.SourceExists(this.Source, this.MachineName))
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "The EventSource does not exist: {0} on {1}", this.Source, this.MachineName));
}
else
{
string logName = this.LogName ?? "Application";
using (System.Diagnostics.EventLog log = new System.Diagnostics.EventLog(logName, this.MachineName, this.Source))
{
log.WriteEntry(this.Description, this.logType, int.Parse(this.EventId, CultureInfo.CurrentCulture));
}
}
}
private void CheckExists()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Checking EventSource exists: {0}", this.Source));
this.Exists = System.Diagnostics.EventLog.SourceExists(this.Source, this.MachineName);
}
private void Create()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Creating EventSource: {0}", this.Source));
EventSourceCreationData data = new EventSourceCreationData(this.Source, this.LogName)
{
MachineName = this.MachineName,
CategoryCount = this.CategoryCount,
MessageResourceFile = this.MessageResourceFile ?? string.Empty,
CategoryResourceFile = this.CategoryResourceFile ?? string.Empty,
ParameterResourceFile = this.ParameterResourceFile ?? string.Empty
};
if (!System.Diagnostics.EventLog.SourceExists(this.Source, this.MachineName))
{
System.Diagnostics.EventLog.CreateEventSource(data);
}
else
{
if (this.Force)
{
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "The event source already exists. Force is true, attempting to delete: {0}", this.Source));
System.Diagnostics.EventLog.DeleteEventSource(this.Source, this.MachineName);
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Creating EventSource: {0}", this.Source));
System.Diagnostics.EventLog.CreateEventSource(data);
}
else
{
this.Log.LogError("The event source already exists. Use Force to delete and create.");
}
}
}
}
}
| |
// 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.AssuredWorkloads.V1.Snippets
{
using Google.Api.Gax;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedAssuredWorkloadsServiceClientSnippets
{
/// <summary>Snippet for CreateWorkload</summary>
public void CreateWorkloadRequestObject()
{
// Snippet: CreateWorkload(CreateWorkloadRequest, CallSettings)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = AssuredWorkloadsServiceClient.Create();
// Initialize request argument(s)
CreateWorkloadRequest request = new CreateWorkloadRequest
{
ParentAsLocationName = LocationName.FromOrganizationLocation("[ORGANIZATION]", "[LOCATION]"),
Workload = new Workload(),
ExternalId = "",
};
// Make the request
Operation<Workload, CreateWorkloadOperationMetadata> response = assuredWorkloadsServiceClient.CreateWorkload(request);
// Poll until the returned long-running operation is complete
Operation<Workload, CreateWorkloadOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Workload result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Workload, CreateWorkloadOperationMetadata> retrievedResponse = assuredWorkloadsServiceClient.PollOnceCreateWorkload(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Workload retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateWorkloadAsync</summary>
public async Task CreateWorkloadRequestObjectAsync()
{
// Snippet: CreateWorkloadAsync(CreateWorkloadRequest, CallSettings)
// Additional: CreateWorkloadAsync(CreateWorkloadRequest, CancellationToken)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = await AssuredWorkloadsServiceClient.CreateAsync();
// Initialize request argument(s)
CreateWorkloadRequest request = new CreateWorkloadRequest
{
ParentAsLocationName = LocationName.FromOrganizationLocation("[ORGANIZATION]", "[LOCATION]"),
Workload = new Workload(),
ExternalId = "",
};
// Make the request
Operation<Workload, CreateWorkloadOperationMetadata> response = await assuredWorkloadsServiceClient.CreateWorkloadAsync(request);
// Poll until the returned long-running operation is complete
Operation<Workload, CreateWorkloadOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Workload result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Workload, CreateWorkloadOperationMetadata> retrievedResponse = await assuredWorkloadsServiceClient.PollOnceCreateWorkloadAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Workload retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateWorkload</summary>
public void CreateWorkload()
{
// Snippet: CreateWorkload(string, Workload, CallSettings)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = AssuredWorkloadsServiceClient.Create();
// Initialize request argument(s)
string parent = "organizations/[ORGANIZATION]/locations/[LOCATION]";
Workload workload = new Workload();
// Make the request
Operation<Workload, CreateWorkloadOperationMetadata> response = assuredWorkloadsServiceClient.CreateWorkload(parent, workload);
// Poll until the returned long-running operation is complete
Operation<Workload, CreateWorkloadOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Workload result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Workload, CreateWorkloadOperationMetadata> retrievedResponse = assuredWorkloadsServiceClient.PollOnceCreateWorkload(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Workload retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateWorkloadAsync</summary>
public async Task CreateWorkloadAsync()
{
// Snippet: CreateWorkloadAsync(string, Workload, CallSettings)
// Additional: CreateWorkloadAsync(string, Workload, CancellationToken)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = await AssuredWorkloadsServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "organizations/[ORGANIZATION]/locations/[LOCATION]";
Workload workload = new Workload();
// Make the request
Operation<Workload, CreateWorkloadOperationMetadata> response = await assuredWorkloadsServiceClient.CreateWorkloadAsync(parent, workload);
// Poll until the returned long-running operation is complete
Operation<Workload, CreateWorkloadOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Workload result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Workload, CreateWorkloadOperationMetadata> retrievedResponse = await assuredWorkloadsServiceClient.PollOnceCreateWorkloadAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Workload retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateWorkload</summary>
public void CreateWorkloadResourceNames()
{
// Snippet: CreateWorkload(LocationName, Workload, CallSettings)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = AssuredWorkloadsServiceClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromOrganizationLocation("[ORGANIZATION]", "[LOCATION]");
Workload workload = new Workload();
// Make the request
Operation<Workload, CreateWorkloadOperationMetadata> response = assuredWorkloadsServiceClient.CreateWorkload(parent, workload);
// Poll until the returned long-running operation is complete
Operation<Workload, CreateWorkloadOperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Workload result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Workload, CreateWorkloadOperationMetadata> retrievedResponse = assuredWorkloadsServiceClient.PollOnceCreateWorkload(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Workload retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateWorkloadAsync</summary>
public async Task CreateWorkloadResourceNamesAsync()
{
// Snippet: CreateWorkloadAsync(LocationName, Workload, CallSettings)
// Additional: CreateWorkloadAsync(LocationName, Workload, CancellationToken)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = await AssuredWorkloadsServiceClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromOrganizationLocation("[ORGANIZATION]", "[LOCATION]");
Workload workload = new Workload();
// Make the request
Operation<Workload, CreateWorkloadOperationMetadata> response = await assuredWorkloadsServiceClient.CreateWorkloadAsync(parent, workload);
// Poll until the returned long-running operation is complete
Operation<Workload, CreateWorkloadOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Workload result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Workload, CreateWorkloadOperationMetadata> retrievedResponse = await assuredWorkloadsServiceClient.PollOnceCreateWorkloadAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Workload retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateWorkload</summary>
public void UpdateWorkloadRequestObject()
{
// Snippet: UpdateWorkload(UpdateWorkloadRequest, CallSettings)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = AssuredWorkloadsServiceClient.Create();
// Initialize request argument(s)
UpdateWorkloadRequest request = new UpdateWorkloadRequest
{
Workload = new Workload(),
UpdateMask = new FieldMask(),
};
// Make the request
Workload response = assuredWorkloadsServiceClient.UpdateWorkload(request);
// End snippet
}
/// <summary>Snippet for UpdateWorkloadAsync</summary>
public async Task UpdateWorkloadRequestObjectAsync()
{
// Snippet: UpdateWorkloadAsync(UpdateWorkloadRequest, CallSettings)
// Additional: UpdateWorkloadAsync(UpdateWorkloadRequest, CancellationToken)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = await AssuredWorkloadsServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateWorkloadRequest request = new UpdateWorkloadRequest
{
Workload = new Workload(),
UpdateMask = new FieldMask(),
};
// Make the request
Workload response = await assuredWorkloadsServiceClient.UpdateWorkloadAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateWorkload</summary>
public void UpdateWorkload()
{
// Snippet: UpdateWorkload(Workload, FieldMask, CallSettings)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = AssuredWorkloadsServiceClient.Create();
// Initialize request argument(s)
Workload workload = new Workload();
FieldMask updateMask = new FieldMask();
// Make the request
Workload response = assuredWorkloadsServiceClient.UpdateWorkload(workload, updateMask);
// End snippet
}
/// <summary>Snippet for UpdateWorkloadAsync</summary>
public async Task UpdateWorkloadAsync()
{
// Snippet: UpdateWorkloadAsync(Workload, FieldMask, CallSettings)
// Additional: UpdateWorkloadAsync(Workload, FieldMask, CancellationToken)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = await AssuredWorkloadsServiceClient.CreateAsync();
// Initialize request argument(s)
Workload workload = new Workload();
FieldMask updateMask = new FieldMask();
// Make the request
Workload response = await assuredWorkloadsServiceClient.UpdateWorkloadAsync(workload, updateMask);
// End snippet
}
/// <summary>Snippet for DeleteWorkload</summary>
public void DeleteWorkloadRequestObject()
{
// Snippet: DeleteWorkload(DeleteWorkloadRequest, CallSettings)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = AssuredWorkloadsServiceClient.Create();
// Initialize request argument(s)
DeleteWorkloadRequest request = new DeleteWorkloadRequest
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
Etag = "",
};
// Make the request
assuredWorkloadsServiceClient.DeleteWorkload(request);
// End snippet
}
/// <summary>Snippet for DeleteWorkloadAsync</summary>
public async Task DeleteWorkloadRequestObjectAsync()
{
// Snippet: DeleteWorkloadAsync(DeleteWorkloadRequest, CallSettings)
// Additional: DeleteWorkloadAsync(DeleteWorkloadRequest, CancellationToken)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = await AssuredWorkloadsServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteWorkloadRequest request = new DeleteWorkloadRequest
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
Etag = "",
};
// Make the request
await assuredWorkloadsServiceClient.DeleteWorkloadAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteWorkload</summary>
public void DeleteWorkload()
{
// Snippet: DeleteWorkload(string, CallSettings)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = AssuredWorkloadsServiceClient.Create();
// Initialize request argument(s)
string name = "organizations/[ORGANIZATION]/locations/[LOCATION]/workloads/[WORKLOAD]";
// Make the request
assuredWorkloadsServiceClient.DeleteWorkload(name);
// End snippet
}
/// <summary>Snippet for DeleteWorkloadAsync</summary>
public async Task DeleteWorkloadAsync()
{
// Snippet: DeleteWorkloadAsync(string, CallSettings)
// Additional: DeleteWorkloadAsync(string, CancellationToken)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = await AssuredWorkloadsServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "organizations/[ORGANIZATION]/locations/[LOCATION]/workloads/[WORKLOAD]";
// Make the request
await assuredWorkloadsServiceClient.DeleteWorkloadAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteWorkload</summary>
public void DeleteWorkloadResourceNames()
{
// Snippet: DeleteWorkload(WorkloadName, CallSettings)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = AssuredWorkloadsServiceClient.Create();
// Initialize request argument(s)
WorkloadName name = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]");
// Make the request
assuredWorkloadsServiceClient.DeleteWorkload(name);
// End snippet
}
/// <summary>Snippet for DeleteWorkloadAsync</summary>
public async Task DeleteWorkloadResourceNamesAsync()
{
// Snippet: DeleteWorkloadAsync(WorkloadName, CallSettings)
// Additional: DeleteWorkloadAsync(WorkloadName, CancellationToken)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = await AssuredWorkloadsServiceClient.CreateAsync();
// Initialize request argument(s)
WorkloadName name = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]");
// Make the request
await assuredWorkloadsServiceClient.DeleteWorkloadAsync(name);
// End snippet
}
/// <summary>Snippet for GetWorkload</summary>
public void GetWorkloadRequestObject()
{
// Snippet: GetWorkload(GetWorkloadRequest, CallSettings)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = AssuredWorkloadsServiceClient.Create();
// Initialize request argument(s)
GetWorkloadRequest request = new GetWorkloadRequest
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
};
// Make the request
Workload response = assuredWorkloadsServiceClient.GetWorkload(request);
// End snippet
}
/// <summary>Snippet for GetWorkloadAsync</summary>
public async Task GetWorkloadRequestObjectAsync()
{
// Snippet: GetWorkloadAsync(GetWorkloadRequest, CallSettings)
// Additional: GetWorkloadAsync(GetWorkloadRequest, CancellationToken)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = await AssuredWorkloadsServiceClient.CreateAsync();
// Initialize request argument(s)
GetWorkloadRequest request = new GetWorkloadRequest
{
WorkloadName = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]"),
};
// Make the request
Workload response = await assuredWorkloadsServiceClient.GetWorkloadAsync(request);
// End snippet
}
/// <summary>Snippet for GetWorkload</summary>
public void GetWorkload()
{
// Snippet: GetWorkload(string, CallSettings)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = AssuredWorkloadsServiceClient.Create();
// Initialize request argument(s)
string name = "organizations/[ORGANIZATION]/locations/[LOCATION]/workloads/[WORKLOAD]";
// Make the request
Workload response = assuredWorkloadsServiceClient.GetWorkload(name);
// End snippet
}
/// <summary>Snippet for GetWorkloadAsync</summary>
public async Task GetWorkloadAsync()
{
// Snippet: GetWorkloadAsync(string, CallSettings)
// Additional: GetWorkloadAsync(string, CancellationToken)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = await AssuredWorkloadsServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "organizations/[ORGANIZATION]/locations/[LOCATION]/workloads/[WORKLOAD]";
// Make the request
Workload response = await assuredWorkloadsServiceClient.GetWorkloadAsync(name);
// End snippet
}
/// <summary>Snippet for GetWorkload</summary>
public void GetWorkloadResourceNames()
{
// Snippet: GetWorkload(WorkloadName, CallSettings)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = AssuredWorkloadsServiceClient.Create();
// Initialize request argument(s)
WorkloadName name = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]");
// Make the request
Workload response = assuredWorkloadsServiceClient.GetWorkload(name);
// End snippet
}
/// <summary>Snippet for GetWorkloadAsync</summary>
public async Task GetWorkloadResourceNamesAsync()
{
// Snippet: GetWorkloadAsync(WorkloadName, CallSettings)
// Additional: GetWorkloadAsync(WorkloadName, CancellationToken)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = await AssuredWorkloadsServiceClient.CreateAsync();
// Initialize request argument(s)
WorkloadName name = WorkloadName.FromOrganizationLocationWorkload("[ORGANIZATION]", "[LOCATION]", "[WORKLOAD]");
// Make the request
Workload response = await assuredWorkloadsServiceClient.GetWorkloadAsync(name);
// End snippet
}
/// <summary>Snippet for ListWorkloads</summary>
public void ListWorkloadsRequestObject()
{
// Snippet: ListWorkloads(ListWorkloadsRequest, CallSettings)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = AssuredWorkloadsServiceClient.Create();
// Initialize request argument(s)
ListWorkloadsRequest request = new ListWorkloadsRequest
{
ParentAsLocationName = LocationName.FromOrganizationLocation("[ORGANIZATION]", "[LOCATION]"),
Filter = "",
};
// Make the request
PagedEnumerable<ListWorkloadsResponse, Workload> response = assuredWorkloadsServiceClient.ListWorkloads(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Workload 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 (ListWorkloadsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Workload 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<Workload> 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 (Workload 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 ListWorkloadsAsync</summary>
public async Task ListWorkloadsRequestObjectAsync()
{
// Snippet: ListWorkloadsAsync(ListWorkloadsRequest, CallSettings)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = await AssuredWorkloadsServiceClient.CreateAsync();
// Initialize request argument(s)
ListWorkloadsRequest request = new ListWorkloadsRequest
{
ParentAsLocationName = LocationName.FromOrganizationLocation("[ORGANIZATION]", "[LOCATION]"),
Filter = "",
};
// Make the request
PagedAsyncEnumerable<ListWorkloadsResponse, Workload> response = assuredWorkloadsServiceClient.ListWorkloadsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Workload 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((ListWorkloadsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Workload 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<Workload> 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 (Workload 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 ListWorkloads</summary>
public void ListWorkloads()
{
// Snippet: ListWorkloads(string, string, int?, CallSettings)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = AssuredWorkloadsServiceClient.Create();
// Initialize request argument(s)
string parent = "organizations/[ORGANIZATION]/locations/[LOCATION]";
// Make the request
PagedEnumerable<ListWorkloadsResponse, Workload> response = assuredWorkloadsServiceClient.ListWorkloads(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Workload 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 (ListWorkloadsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Workload 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<Workload> 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 (Workload 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 ListWorkloadsAsync</summary>
public async Task ListWorkloadsAsync()
{
// Snippet: ListWorkloadsAsync(string, string, int?, CallSettings)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = await AssuredWorkloadsServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "organizations/[ORGANIZATION]/locations/[LOCATION]";
// Make the request
PagedAsyncEnumerable<ListWorkloadsResponse, Workload> response = assuredWorkloadsServiceClient.ListWorkloadsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Workload 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((ListWorkloadsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Workload 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<Workload> 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 (Workload 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 ListWorkloads</summary>
public void ListWorkloadsResourceNames()
{
// Snippet: ListWorkloads(LocationName, string, int?, CallSettings)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = AssuredWorkloadsServiceClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromOrganizationLocation("[ORGANIZATION]", "[LOCATION]");
// Make the request
PagedEnumerable<ListWorkloadsResponse, Workload> response = assuredWorkloadsServiceClient.ListWorkloads(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Workload 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 (ListWorkloadsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Workload 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<Workload> 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 (Workload 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 ListWorkloadsAsync</summary>
public async Task ListWorkloadsResourceNamesAsync()
{
// Snippet: ListWorkloadsAsync(LocationName, string, int?, CallSettings)
// Create client
AssuredWorkloadsServiceClient assuredWorkloadsServiceClient = await AssuredWorkloadsServiceClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromOrganizationLocation("[ORGANIZATION]", "[LOCATION]");
// Make the request
PagedAsyncEnumerable<ListWorkloadsResponse, Workload> response = assuredWorkloadsServiceClient.ListWorkloadsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Workload 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((ListWorkloadsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Workload 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<Workload> 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 (Workload 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
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Tests.TestObjects;
using NUnit.Framework;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.IO;
using System.Collections;
using System.Collections.Specialized;
#if !PocketPC && !SILVERLIGHT
using System.Web.UI;
#endif
namespace Newtonsoft.Json.Tests.Linq
{
public class JObjectTests : TestFixtureBase
{
[Test]
public void TryGetValue()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
JToken t;
Assert.AreEqual(false, o.TryGetValue("sdf", out t));
Assert.AreEqual(null, t);
Assert.AreEqual(false, o.TryGetValue(null, out t));
Assert.AreEqual(null, t);
Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t));
}
[Test]
public void DictionaryItemShouldSet()
{
JObject o = new JObject();
o["PropertyNameValue"] = new JValue(1);
Assert.AreEqual(1, o.Children().Count());
JToken t;
Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t));
o["PropertyNameValue"] = new JValue(2);
Assert.AreEqual(1, o.Children().Count());
Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
Assert.AreEqual(true, JToken.DeepEquals(new JValue(2), t));
o["PropertyNameValue"] = null;
Assert.AreEqual(1, o.Children().Count());
Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
Assert.AreEqual(true, JToken.DeepEquals(new JValue((object)null), t));
}
[Test]
public void Remove()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
Assert.AreEqual(false, o.Remove("sdf"));
Assert.AreEqual(false, o.Remove(null));
Assert.AreEqual(true, o.Remove("PropertyNameValue"));
Assert.AreEqual(0, o.Children().Count());
}
[Test]
public void GenericCollectionRemove()
{
JValue v = new JValue(1);
JObject o = new JObject();
o.Add("PropertyNameValue", v);
Assert.AreEqual(1, o.Children().Count());
Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1))));
Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2))));
Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))));
Assert.AreEqual(true, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", v)));
Assert.AreEqual(0, o.Children().Count());
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")]
public void DuplicatePropertyNameShouldThrow()
{
JObject o = new JObject();
o.Add("PropertyNameValue", null);
o.Add("PropertyNameValue", null);
}
[Test]
public void GenericDictionaryAdd()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, (int)o["PropertyNameValue"]);
o.Add("PropertyNameValue1", null);
Assert.AreEqual(null, ((JValue)o["PropertyNameValue1"]).Value);
Assert.AreEqual(2, o.Children().Count());
}
[Test]
public void GenericCollectionAdd()
{
JObject o = new JObject();
((ICollection<KeyValuePair<string,JToken>>)o).Add(new KeyValuePair<string,JToken>("PropertyNameValue", new JValue(1)));
Assert.AreEqual(1, (int)o["PropertyNameValue"]);
Assert.AreEqual(1, o.Children().Count());
}
[Test]
public void GenericCollectionClear()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
JProperty p = (JProperty)o.Children().ElementAt(0);
((ICollection<KeyValuePair<string, JToken>>)o).Clear();
Assert.AreEqual(0, o.Children().Count());
Assert.AreEqual(null, p.Parent);
}
[Test]
public void GenericCollectionContains()
{
JValue v = new JValue(1);
JObject o = new JObject();
o.Add("PropertyNameValue", v);
Assert.AreEqual(1, o.Children().Count());
bool contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1)));
Assert.AreEqual(false, contains);
contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", v));
Assert.AreEqual(true, contains);
contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2)));
Assert.AreEqual(false, contains);
contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1)));
Assert.AreEqual(false, contains);
contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(default(KeyValuePair<string, JToken>));
Assert.AreEqual(false, contains);
}
[Test]
public void GenericDictionaryContains()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
bool contains = ((IDictionary<string, JToken>)o).ContainsKey("PropertyNameValue");
Assert.AreEqual(true, contains);
}
[Test]
public void GenericCollectionCopyTo()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
o.Add("PropertyNameValue3", new JValue(3));
Assert.AreEqual(3, o.Children().Count());
KeyValuePair<string, JToken>[] a = new KeyValuePair<string,JToken>[5];
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(a, 1);
Assert.AreEqual(default(KeyValuePair<string,JToken>), a[0]);
Assert.AreEqual("PropertyNameValue", a[1].Key);
Assert.AreEqual(1, (int)a[1].Value);
Assert.AreEqual("PropertyNameValue2", a[2].Key);
Assert.AreEqual(2, (int)a[2].Value);
Assert.AreEqual("PropertyNameValue3", a[3].Key);
Assert.AreEqual(3, (int)a[3].Value);
Assert.AreEqual(default(KeyValuePair<string, JToken>), a[4]);
}
[Test]
[ExpectedException(typeof(ArgumentNullException), ExpectedMessage = @"Value cannot be null.
Parameter name: array")]
public void GenericCollectionCopyToNullArrayShouldThrow()
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(null, 0);
}
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException), ExpectedMessage = @"arrayIndex is less than 0.
Parameter name: arrayIndex")]
public void GenericCollectionCopyToNegativeArrayIndexShouldThrow()
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], -1);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = @"arrayIndex is equal to or greater than the length of array.")]
public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow()
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], 1);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.")]
public void GenericCollectionCopyToInsufficientArrayCapacity()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
o.Add("PropertyNameValue3", new JValue(3));
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[3], 1);
}
[Test]
public void FromObjectRaw()
{
PersonRaw raw = new PersonRaw
{
FirstName = "FirstNameValue",
RawContent = new JRaw("[1,2,3,4,5]"),
LastName = "LastNameValue"
};
JObject o = JObject.FromObject(raw);
Assert.AreEqual("FirstNameValue", (string)o["first_name"]);
Assert.AreEqual(JTokenType.Raw, ((JValue)o["RawContent"]).Type);
Assert.AreEqual("[1,2,3,4,5]", (string)o["RawContent"]);
Assert.AreEqual("LastNameValue", (string)o["last_name"]);
}
[Test]
public void JTokenReader()
{
PersonRaw raw = new PersonRaw
{
FirstName = "FirstNameValue",
RawContent = new JRaw("[1,2,3,4,5]"),
LastName = "LastNameValue"
};
JObject o = JObject.FromObject(raw);
JsonReader reader = new JTokenReader(o);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.Raw, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.EndObject, reader.TokenType);
Assert.IsFalse(reader.Read());
}
[Test]
public void DeserializeFromRaw()
{
PersonRaw raw = new PersonRaw
{
FirstName = "FirstNameValue",
RawContent = new JRaw("[1,2,3,4,5]"),
LastName = "LastNameValue"
};
JObject o = JObject.FromObject(raw);
JsonReader reader = new JTokenReader(o);
JsonSerializer serializer = new JsonSerializer();
raw = (PersonRaw)serializer.Deserialize(reader, typeof(PersonRaw));
Assert.AreEqual("FirstNameValue", raw.FirstName);
Assert.AreEqual("LastNameValue", raw.LastName);
Assert.AreEqual("[1,2,3,4,5]", raw.RawContent.Value);
}
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage = "Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray")]
public void Parse_ShouldThrowOnUnexpectedToken()
{
string json = @"[""prop""]";
JObject.Parse(json);
}
[Test]
public void ParseJavaScriptDate()
{
string json = @"[new Date(1207285200000)]";
JArray a = (JArray)JsonConvert.DeserializeObject(json, null);
JValue v = (JValue)a[0];
Assert.AreEqual(JsonConvert.ConvertJavaScriptTicksToDateTime(1207285200000), (DateTime)v);
}
[Test]
public void GenericValueCast()
{
string json = @"{""foo"":true}";
JObject o = (JObject)JsonConvert.DeserializeObject(json);
bool? value = o.Value<bool?>("foo");
Assert.AreEqual(true, value);
json = @"{""foo"":null}";
o = (JObject)JsonConvert.DeserializeObject(json);
value = o.Value<bool?>("foo");
Assert.AreEqual(null, value);
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Invalid property identifier character: ]. Line 3, position 9.")]
public void Blog()
{
JObject person = JObject.Parse(@"{
""name"": ""James"",
]!#$THIS IS: BAD JSON![{}}}}]
}");
// Invalid property identifier character: ]. Line 3, position 9.
}
[Test]
public void RawChildValues()
{
JObject o = new JObject();
o["val1"] = new JRaw("1");
o["val2"] = new JRaw("1");
string json = o.ToString();
Assert.AreEqual(@"{
""val1"": 1,
""val2"": 1
}", json);
}
[Test]
public void Iterate()
{
JObject o = new JObject();
o.Add("PropertyNameValue1", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
JToken t = o;
int i = 1;
foreach (JProperty property in t)
{
Assert.AreEqual("PropertyNameValue" + i, property.Name);
Assert.AreEqual(i, (int)property.Value);
i++;
}
}
[Test]
public void KeyValuePairIterate()
{
JObject o = new JObject();
o.Add("PropertyNameValue1", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
int i = 1;
foreach (KeyValuePair<string, JToken> pair in o)
{
Assert.AreEqual("PropertyNameValue" + i, pair.Key);
Assert.AreEqual(i, (int)pair.Value);
i++;
}
}
[Test]
public void WriteObjectNullStringValue()
{
string s = null;
JValue v = new JValue(s);
Assert.AreEqual(null, v.Value);
Assert.AreEqual(JTokenType.String, v.Type);
JObject o = new JObject();
o["title"] = v;
string output = o.ToString();
Assert.AreEqual(@"{
""title"": null
}", output);
}
[Test]
public void Example()
{
string json = @"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
""Sizes"": [
""Small"",
""Medium"",
""Large""
]
}";
JObject o = JObject.Parse(json);
string name = (string)o["Name"];
// Apple
JArray sizes = (JArray)o["Sizes"];
string smallest = (string)sizes[0];
// Small
Console.WriteLine(name);
Console.WriteLine(smallest);
}
[Test]
public void DeserializeClassManually()
{
string jsonText = @"{
""short"":{
""original"":""http://www.foo.com/"",
""short"":""krehqk"",
""error"":{
""code"":0,
""msg"":""No action taken""}
}";
JObject json = JObject.Parse(jsonText);
Shortie shortie = new Shortie
{
Original = (string)json["short"]["original"],
Short = (string)json["short"]["short"],
Error = new ShortieException
{
Code = (int)json["short"]["error"]["code"],
ErrorMessage = (string)json["short"]["error"]["msg"]
}
};
Console.WriteLine(shortie.Original);
// http://www.foo.com/
Console.WriteLine(shortie.Error.ErrorMessage);
// No action taken
Assert.AreEqual("http://www.foo.com/", shortie.Original);
Assert.AreEqual("krehqk", shortie.Short);
Assert.AreEqual(null, shortie.Shortened);
Assert.AreEqual(0, shortie.Error.Code);
Assert.AreEqual("No action taken", shortie.Error.ErrorMessage);
}
[Test]
public void JObjectContainingHtml()
{
JObject o = new JObject();
o["rc"] = new JValue(200);
o["m"] = new JValue("");
o["o"] = new JValue(@"<div class='s1'>
<div class='avatar'>
<a href='asdf'>asdf</a><br />
<strong>0</strong>
</div>
<div class='sl'>
<p>
444444444
</p>
</div>
<div class='clear'>
</div>
</div>");
Assert.AreEqual(@"{
""rc"": 200,
""m"": """",
""o"": ""<div class='s1'>\r\n <div class='avatar'> \r\n <a href='asdf'>asdf</a><br />\r\n <strong>0</strong>\r\n </div>\r\n <div class='sl'>\r\n <p>\r\n 444444444\r\n </p>\r\n </div>\r\n <div class='clear'>\r\n </div> \r\n</div>""
}", o.ToString());
}
[Test]
public void ImplicitValueConversions()
{
JObject moss = new JObject();
moss["FirstName"] = new JValue("Maurice");
moss["LastName"] = new JValue("Moss");
moss["BirthDate"] = new JValue(new DateTime(1977, 12, 30));
moss["Department"] = new JValue("IT");
moss["JobTitle"] = new JValue("Support");
Console.WriteLine(moss.ToString());
//{
// "FirstName": "Maurice",
// "LastName": "Moss",
// "BirthDate": "\/Date(252241200000+1300)\/",
// "Department": "IT",
// "JobTitle": "Support"
//}
JObject jen = new JObject();
jen["FirstName"] = "Jen";
jen["LastName"] = "Barber";
jen["BirthDate"] = new DateTime(1978, 3, 15);
jen["Department"] = "IT";
jen["JobTitle"] = "Manager";
Console.WriteLine(jen.ToString());
//{
// "FirstName": "Jen",
// "LastName": "Barber",
// "BirthDate": "\/Date(258721200000+1300)\/",
// "Department": "IT",
// "JobTitle": "Manager"
//}
}
[Test]
public void ReplaceJPropertyWithJPropertyWithSameName()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
JObject o = new JObject(p1, p2);
IList l = o;
Assert.AreEqual(p1, l[0]);
Assert.AreEqual(p2, l[1]);
JProperty p3 = new JProperty("Test1", "III");
p1.Replace(p3);
Assert.AreEqual(null, p1.Parent);
Assert.AreEqual(l, p3.Parent);
Assert.AreEqual(p3, l[0]);
Assert.AreEqual(p2, l[1]);
Assert.AreEqual(2, l.Count);
Assert.AreEqual(2, o.Properties().Count());
JProperty p4 = new JProperty("Test4", "IV");
p2.Replace(p4);
Assert.AreEqual(null, p2.Parent);
Assert.AreEqual(l, p4.Parent);
Assert.AreEqual(p3, l[0]);
Assert.AreEqual(p4, l[1]);
}
#if !PocketPC && !SILVERLIGHT && !NET20
[Test]
public void PropertyChanging()
{
object changing = null;
object changed = null;
int changingCount = 0;
int changedCount = 0;
JObject o = new JObject();
o.PropertyChanging += (sender, args) =>
{
JObject s = (JObject) sender;
changing = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
changingCount++;
};
o.PropertyChanged += (sender, args) =>
{
JObject s = (JObject)sender;
changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
changedCount++;
};
o["StringValue"] = "value1";
Assert.AreEqual(null, changing);
Assert.AreEqual("value1", changed);
Assert.AreEqual("value1", (string)o["StringValue"]);
Assert.AreEqual(1, changingCount);
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value1";
Assert.AreEqual(1, changingCount);
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value2";
Assert.AreEqual("value1", changing);
Assert.AreEqual("value2", changed);
Assert.AreEqual("value2", (string)o["StringValue"]);
Assert.AreEqual(2, changingCount);
Assert.AreEqual(2, changedCount);
o["StringValue"] = null;
Assert.AreEqual("value2", changing);
Assert.AreEqual(null, changed);
Assert.AreEqual(null, (string)o["StringValue"]);
Assert.AreEqual(3, changingCount);
Assert.AreEqual(3, changedCount);
o["NullValue"] = null;
Assert.AreEqual(null, changing);
Assert.AreEqual(null, changed);
Assert.AreEqual(new JValue((object)null), o["NullValue"]);
Assert.AreEqual(4, changingCount);
Assert.AreEqual(4, changedCount);
o["NullValue"] = null;
Assert.AreEqual(4, changingCount);
Assert.AreEqual(4, changedCount);
}
#endif
[Test]
public void PropertyChanged()
{
object changed = null;
int changedCount = 0;
JObject o = new JObject();
o.PropertyChanged += (sender, args) =>
{
JObject s = (JObject)sender;
changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
changedCount++;
};
o["StringValue"] = "value1";
Assert.AreEqual("value1", changed);
Assert.AreEqual("value1", (string)o["StringValue"]);
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value1";
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value2";
Assert.AreEqual("value2", changed);
Assert.AreEqual("value2", (string)o["StringValue"]);
Assert.AreEqual(2, changedCount);
o["StringValue"] = null;
Assert.AreEqual(null, changed);
Assert.AreEqual(null, (string)o["StringValue"]);
Assert.AreEqual(3, changedCount);
o["NullValue"] = null;
Assert.AreEqual(null, changed);
Assert.AreEqual(new JValue((object)null), o["NullValue"]);
Assert.AreEqual(4, changedCount);
o["NullValue"] = null;
Assert.AreEqual(4, changedCount);
}
[Test]
public void IListContains()
{
JProperty p = new JProperty("Test", 1);
IList l = new JObject(p);
Assert.IsTrue(l.Contains(p));
Assert.IsFalse(l.Contains(new JProperty("Test", 1)));
}
[Test]
public void IListIndexOf()
{
JProperty p = new JProperty("Test", 1);
IList l = new JObject(p);
Assert.AreEqual(0, l.IndexOf(p));
Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1)));
}
[Test]
public void IListClear()
{
JProperty p = new JProperty("Test", 1);
IList l = new JObject(p);
Assert.AreEqual(1, l.Count);
l.Clear();
Assert.AreEqual(0, l.Count);
}
[Test]
public void IListCopyTo()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
object[] a = new object[l.Count];
l.CopyTo(a, 0);
Assert.AreEqual(p1, a[0]);
Assert.AreEqual(p2, a[1]);
}
[Test]
public void IListAdd()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l.Add(p3);
Assert.AreEqual(3, l.Count);
Assert.AreEqual(p3, l[2]);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")]
public void IListAddBadToken()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
l.Add(new JValue("Bad!"));
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Argument is not a JToken.")]
public void IListAddBadValue()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
l.Add("Bad!");
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")]
public void IListAddPropertyWithExistingName()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test2", "II");
l.Add(p3);
}
[Test]
public void IListRemove()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
// won't do anything
l.Remove(p3);
Assert.AreEqual(2, l.Count);
l.Remove(p1);
Assert.AreEqual(1, l.Count);
Assert.IsFalse(l.Contains(p1));
Assert.IsTrue(l.Contains(p2));
l.Remove(p2);
Assert.AreEqual(0, l.Count);
Assert.IsFalse(l.Contains(p2));
Assert.AreEqual(null, p2.Parent);
}
[Test]
public void IListRemoveAt()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
// won't do anything
l.RemoveAt(0);
l.Remove(p1);
Assert.AreEqual(1, l.Count);
l.Remove(p2);
Assert.AreEqual(0, l.Count);
}
[Test]
public void IListInsert()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l.Insert(1, p3);
Assert.AreEqual(l, p3.Parent);
Assert.AreEqual(p1, l[0]);
Assert.AreEqual(p3, l[1]);
Assert.AreEqual(p2, l[2]);
}
[Test]
public void IListIsReadOnly()
{
IList l = new JObject();
Assert.IsFalse(l.IsReadOnly);
}
[Test]
public void IListIsFixedSize()
{
IList l = new JObject();
Assert.IsFalse(l.IsFixedSize);
}
[Test]
public void IListSetItem()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
Assert.AreEqual(p3, l[0]);
Assert.AreEqual(p2, l[1]);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")]
public void IListSetItemAlreadyExists()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
l[1] = p3;
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = @"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")]
public void IListSetItemInvalid()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
l[0] = new JValue(true);
}
[Test]
public void IListSyncRoot()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
Assert.IsNotNull(l.SyncRoot);
}
[Test]
public void IListIsSynchronized()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
Assert.IsFalse(l.IsSynchronized);
}
[Test]
public void GenericListJTokenContains()
{
JProperty p = new JProperty("Test", 1);
IList<JToken> l = new JObject(p);
Assert.IsTrue(l.Contains(p));
Assert.IsFalse(l.Contains(new JProperty("Test", 1)));
}
[Test]
public void GenericListJTokenIndexOf()
{
JProperty p = new JProperty("Test", 1);
IList<JToken> l = new JObject(p);
Assert.AreEqual(0, l.IndexOf(p));
Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1)));
}
[Test]
public void GenericListJTokenClear()
{
JProperty p = new JProperty("Test", 1);
IList<JToken> l = new JObject(p);
Assert.AreEqual(1, l.Count);
l.Clear();
Assert.AreEqual(0, l.Count);
}
[Test]
public void GenericListJTokenCopyTo()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JToken[] a = new JToken[l.Count];
l.CopyTo(a, 0);
Assert.AreEqual(p1, a[0]);
Assert.AreEqual(p2, a[1]);
}
[Test]
public void GenericListJTokenAdd()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l.Add(p3);
Assert.AreEqual(3, l.Count);
Assert.AreEqual(p3, l[2]);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")]
public void GenericListJTokenAddBadToken()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
l.Add(new JValue("Bad!"));
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.")]
public void GenericListJTokenAddBadValue()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
// string is implicitly converted to JValue
l.Add("Bad!");
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")]
public void GenericListJTokenAddPropertyWithExistingName()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test2", "II");
l.Add(p3);
}
[Test]
public void GenericListJTokenRemove()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
// won't do anything
Assert.IsFalse(l.Remove(p3));
Assert.AreEqual(2, l.Count);
Assert.IsTrue(l.Remove(p1));
Assert.AreEqual(1, l.Count);
Assert.IsFalse(l.Contains(p1));
Assert.IsTrue(l.Contains(p2));
Assert.IsTrue(l.Remove(p2));
Assert.AreEqual(0, l.Count);
Assert.IsFalse(l.Contains(p2));
Assert.AreEqual(null, p2.Parent);
}
[Test]
public void GenericListJTokenRemoveAt()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
// won't do anything
l.RemoveAt(0);
l.Remove(p1);
Assert.AreEqual(1, l.Count);
l.Remove(p2);
Assert.AreEqual(0, l.Count);
}
[Test]
public void GenericListJTokenInsert()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l.Insert(1, p3);
Assert.AreEqual(l, p3.Parent);
Assert.AreEqual(p1, l[0]);
Assert.AreEqual(p3, l[1]);
Assert.AreEqual(p2, l[2]);
}
[Test]
public void GenericListJTokenIsReadOnly()
{
IList<JToken> l = new JObject();
Assert.IsFalse(l.IsReadOnly);
}
[Test]
public void GenericListJTokenSetItem()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
Assert.AreEqual(p3, l[0]);
Assert.AreEqual(p2, l[1]);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.")]
public void GenericListJTokenSetItemAlreadyExists()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
l[1] = p3;
}
#if !SILVERLIGHT
[Test]
public void IBindingListSortDirection()
{
IBindingList l = new JObject();
Assert.AreEqual(ListSortDirection.Ascending, l.SortDirection);
}
[Test]
public void IBindingListSortProperty()
{
IBindingList l = new JObject();
Assert.AreEqual(null, l.SortProperty);
}
[Test]
public void IBindingListSupportsChangeNotification()
{
IBindingList l = new JObject();
Assert.AreEqual(true, l.SupportsChangeNotification);
}
[Test]
public void IBindingListSupportsSearching()
{
IBindingList l = new JObject();
Assert.AreEqual(false, l.SupportsSearching);
}
[Test]
public void IBindingListSupportsSorting()
{
IBindingList l = new JObject();
Assert.AreEqual(false, l.SupportsSorting);
}
[Test]
public void IBindingListAllowEdit()
{
IBindingList l = new JObject();
Assert.AreEqual(true, l.AllowEdit);
}
[Test]
public void IBindingListAllowNew()
{
IBindingList l = new JObject();
Assert.AreEqual(true, l.AllowNew);
}
[Test]
public void IBindingListAllowRemove()
{
IBindingList l = new JObject();
Assert.AreEqual(true, l.AllowRemove);
}
[Test]
public void IBindingListAddIndex()
{
IBindingList l = new JObject();
// do nothing
l.AddIndex(null);
}
[Test]
[ExpectedException(typeof(NotSupportedException))]
public void IBindingListApplySort()
{
IBindingList l = new JObject();
l.ApplySort(null, ListSortDirection.Ascending);
}
[Test]
[ExpectedException(typeof(NotSupportedException))]
public void IBindingListRemoveSort()
{
IBindingList l = new JObject();
l.RemoveSort();
}
[Test]
public void IBindingListRemoveIndex()
{
IBindingList l = new JObject();
// do nothing
l.RemoveIndex(null);
}
[Test]
[ExpectedException(typeof(NotSupportedException))]
public void IBindingListFind()
{
IBindingList l = new JObject();
l.Find(null, null);
}
[Test]
public void IBindingListIsSorted()
{
IBindingList l = new JObject();
Assert.AreEqual(false, l.IsSorted);
}
[Test]
[ExpectedException(typeof(Exception), ExpectedMessage = "Could not determine new value to add to 'Newtonsoft.Json.Linq.JObject'.")]
public void IBindingListAddNew()
{
IBindingList l = new JObject();
l.AddNew();
}
[Test]
public void IBindingListAddNewWithEvent()
{
JObject o = new JObject();
o.AddingNew += (s, e) => e.NewObject = new JProperty("Property!");
IBindingList l = o;
object newObject = l.AddNew();
Assert.IsNotNull(newObject);
JProperty p = (JProperty) newObject;
Assert.AreEqual("Property!", p.Name);
Assert.AreEqual(o, p.Parent);
}
[Test]
public void ITypedListGetListName()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
ITypedList l = new JObject(p1, p2);
Assert.AreEqual(string.Empty, l.GetListName(null));
}
[Test]
public void ITypedListGetItemProperties()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
ITypedList l = new JObject(p1, p2);
PropertyDescriptorCollection propertyDescriptors = l.GetItemProperties(null);
Assert.IsNull(propertyDescriptors);
}
[Test]
public void ListChanged()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
JObject o = new JObject(p1, p2);
ListChangedType? changedType = null;
int? index = null;
o.ListChanged += (s, a) =>
{
changedType = a.ListChangedType;
index = a.NewIndex;
};
JProperty p3 = new JProperty("Test3", "III");
o.Add(p3);
Assert.AreEqual(changedType, ListChangedType.ItemAdded);
Assert.AreEqual(index, 2);
Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]);
JProperty p4 = new JProperty("Test4", "IV");
((IList<JToken>) o)[index.Value] = p4;
Assert.AreEqual(changedType, ListChangedType.ItemChanged);
Assert.AreEqual(index, 2);
Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]);
Assert.IsFalse(((IList<JToken>)o).Contains(p3));
Assert.IsTrue(((IList<JToken>)o).Contains(p4));
o["Test1"] = 2;
Assert.AreEqual(changedType, ListChangedType.ItemChanged);
Assert.AreEqual(index, 0);
Assert.AreEqual(2, (int)o["Test1"]);
}
#else
[Test]
public void ListChanged()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
JObject o = new JObject(p1, p2);
NotifyCollectionChangedAction? changedType = null;
int? index = null;
o.CollectionChanged += (s, a) =>
{
changedType = a.Action;
index = a.NewStartingIndex;
};
JProperty p3 = new JProperty("Test3", "III");
o.Add(p3);
Assert.AreEqual(changedType, NotifyCollectionChangedAction.Add);
Assert.AreEqual(index, 2);
Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]);
JProperty p4 = new JProperty("Test4", "IV");
((IList<JToken>)o)[index.Value] = p4;
Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace);
Assert.AreEqual(index, 2);
Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]);
Assert.IsFalse(((IList<JToken>)o).Contains(p3));
Assert.IsTrue(((IList<JToken>)o).Contains(p4));
o["Test1"] = 2;
Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace);
Assert.AreEqual(index, 0);
Assert.AreEqual(2, (int)o["Test1"]);
}
#endif
[Test]
public void GetGeocodeAddress()
{
string json = @"{
""name"": ""Address: 435 North Mulford Road Rockford, IL 61107"",
""Status"": {
""code"": 200,
""request"": ""geocode""
},
""Placemark"": [ {
""id"": ""p1"",
""address"": ""435 N Mulford Rd, Rockford, IL 61107, USA"",
""AddressDetails"": {
""Accuracy"" : 8,
""Country"" : {
""AdministrativeArea"" : {
""AdministrativeAreaName"" : ""IL"",
""SubAdministrativeArea"" : {
""Locality"" : {
""LocalityName"" : ""Rockford"",
""PostalCode"" : {
""PostalCodeNumber"" : ""61107""
},
""Thoroughfare"" : {
""ThoroughfareName"" : ""435 N Mulford Rd""
}
},
""SubAdministrativeAreaName"" : ""Winnebago""
}
},
""CountryName"" : ""USA"",
""CountryNameCode"" : ""US""
}
},
""ExtendedData"": {
""LatLonBox"": {
""north"": 42.2753076,
""south"": 42.2690124,
""east"": -88.9964645,
""west"": -89.0027597
}
},
""Point"": {
""coordinates"": [ -88.9995886, 42.2721596, 0 ]
}
} ]
}";
JObject o = JObject.Parse(json);
string searchAddress = (string)o["Placemark"][0]["AddressDetails"]["Country"]["AdministrativeArea"]["SubAdministrativeArea"]["Locality"]["Thoroughfare"]["ThoroughfareName"];
Assert.AreEqual("435 N Mulford Rd", searchAddress);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Set JObject values with invalid key value: 0. Object property name expected.")]
public void SetValueWithInvalidPropertyName()
{
JObject o = new JObject();
o[0] = new JValue(3);
}
[Test]
public void SetValue()
{
object key = "TestKey";
JObject o = new JObject();
o[key] = new JValue(3);
Assert.AreEqual(3, (int)o[key]);
}
[Test]
public void ParseMultipleProperties()
{
string json = @"{
""Name"": ""Name1"",
""Name"": ""Name2""
}";
JObject o = JObject.Parse(json);
string value = (string)o["Name"];
Assert.AreEqual("Name2", value);
}
[Test]
public void WriteObjectNullDBNullValue()
{
DBNull dbNull = DBNull.Value;
JValue v = new JValue(dbNull);
Assert.AreEqual(DBNull.Value, v.Value);
Assert.AreEqual(JTokenType.Null, v.Type);
JObject o = new JObject();
o["title"] = v;
string output = o.ToString();
Assert.AreEqual(@"{
""title"": null
}", output);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not convert Object to String.")]
public void InvalidValueCastExceptionMessage()
{
string json = @"{
""responseData"": {},
""responseDetails"": null,
""responseStatus"": 200
}";
JObject o = JObject.Parse(json);
string name = (string)o["responseData"];
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Can not convert Object to String.")]
public void InvalidPropertyValueCastExceptionMessage()
{
string json = @"{
""responseData"": {},
""responseDetails"": null,
""responseStatus"": 200
}";
JObject o = JObject.Parse(json);
string name = (string)o.Property("responseData");
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "JSON integer 307953220000517141511 is too large or small for an Int64.")]
public void NumberTooBigForInt64()
{
string json = @"{""code"": 307953220000517141511}";
JObject.Parse(json);
}
}
}
| |
//
// UUEncoder.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2012 Jeffrey Stedfast
//
// 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;
namespace MimeKit.Encodings {
/// <summary>
/// Incrementally encodes content using the Unix-to-Unix encoding.
/// </summary>
/// <remarks>
/// <para>The UUEncoding is an encoding that predates MIME and was used to encode
/// binary content such as images and other types of multi-media to ensure
/// that the data remained intact when sent via 7bit transports such as SMTP.</para>
/// <para>These days, the UUEncoding has largely been deprecated in favour of
/// the base64 encoding, however, some older mail clients still use it.</para>
/// </remarks>
public class UUEncoder : IMimeEncoder
{
const int MaxInputPerLine = 45;
const int MaxOutputPerLine = ((MaxInputPerLine / 3) * 4) + 2;
readonly byte[] uubuf = new byte[60];
uint saved;
byte nsaved;
byte uulen;
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Encodings.UUEncoder"/> class.
/// </summary>
public UUEncoder ()
{
Reset ();
}
/// <summary>
/// Clone the <see cref="UUEncoder"/> with its current state.
/// </summary>
/// <returns>A new <see cref="UUEncoder"/> with identical state.</returns>
public IMimeEncoder Clone ()
{
var encoder = new UUEncoder ();
Array.Copy (uubuf, encoder.uubuf, uubuf.Length);
encoder.nsaved = nsaved;
encoder.saved = saved;
encoder.uulen = uulen;
return encoder;
}
/// <summary>
/// Gets the encoding.
/// </summary>
/// <value>The encoding.</value>
public ContentEncoding Encoding
{
get { return ContentEncoding.UUEncode; }
}
/// <summary>
/// Estimates the length of the output.
/// </summary>
/// <returns>The estimated output length.</returns>
/// <param name='inputLength'>The input length.</param>
public int EstimateOutputLength (int inputLength)
{
return (((inputLength + 2) / MaxInputPerLine) * MaxOutputPerLine) + MaxOutputPerLine + 2;
}
void ValidateArguments (byte[] input, int startIndex, int length, byte[] output)
{
if (input == null)
throw new ArgumentNullException ("input");
if (startIndex < 0 || startIndex > input.Length)
throw new ArgumentOutOfRangeException ("startIndex");
if (length < 0 || startIndex + length > input.Length)
throw new ArgumentOutOfRangeException ("length");
if (output == null)
throw new ArgumentNullException ("output");
if (output.Length < EstimateOutputLength (length))
throw new ArgumentException ("The output buffer is not large enough to contain the encoded input.", "output");
}
static byte Encode (int c)
{
return c != 0 ? (byte) (c + 0x20) : (byte) '`';
}
unsafe int Encode (byte* input, int length, byte[] outbuf, byte* output, byte *uuptr)
{
if (length == 0)
return 0;
byte* inend = input + length;
byte* outptr = output;
byte* inptr = input;
byte* bufptr;
byte b0, b1, b2;
if ((length + uulen) < 45) {
// not enough input to write a full uuencoded line
bufptr = uuptr + ((uulen / 3) * 4);
} else {
bufptr = outptr + 1;
if (uulen > 0) {
// copy the previous call's uubuf to output
Array.Copy (uubuf, 0, outbuf, (int) (bufptr - outptr), ((uulen / 3) * 4));
bufptr += ((uulen / 3) * 4);
}
}
if (nsaved == 2) {
b0 = (byte) ((saved >> 8) & 0xFF);
b1 = (byte) (saved & 0xFF);
b2 = *inptr++;
nsaved = 0;
saved = 0;
// convert 3 input bytes into 4 uuencoded bytes
*bufptr++ = Encode ((b0 >> 2) & 0x3F);
*bufptr++ = Encode (((b0 << 4) | ((b1 >> 4) & 0x0F)) & 0x3F);
*bufptr++ = Encode (((b1 << 2) | ((b2 >> 6) & 0x03)) & 0x3F);
*bufptr++ = Encode (b2 & 0x3F);
uulen += 3;
} else if (nsaved == 1) {
if ((inptr + 2) < inend) {
b0 = (byte) (saved & 0xFF);
b1 = *inptr++;
b2 = *inptr++;
nsaved = 0;
saved = 0;
// convert 3 input bytes into 4 uuencoded bytes
*bufptr++ = Encode ((b0 >> 2) & 0x3F);
*bufptr++ = Encode (((b0 << 4) | ((b1 >> 4) & 0x0F)) & 0x3F);
*bufptr++ = Encode (((b1 << 2) | ((b2 >> 6) & 0x03)) & 0x3F);
*bufptr++ = Encode (b2 & 0x3F);
uulen += 3;
} else {
while (inptr < inend) {
saved = (saved << 8) | *inptr++;
nsaved++;
}
}
}
while (inptr < inend) {
while (uulen < 45 && (inptr + 3) <= inend) {
b0 = *inptr++;
b1 = *inptr++;
b2 = *inptr++;
// convert 3 input bytes into 4 uuencoded bytes
*bufptr++ = Encode ((b0 >> 2) & 0x3F);
*bufptr++ = Encode (((b0 << 4) | ((b1 >> 4) & 0x0F)) & 0x3F);
*bufptr++ = Encode (((b1 << 2) | ((b2 >> 6) & 0x03)) & 0x3F);
*bufptr++ = Encode (b2 & 0x3F);
uulen += 3;
}
if (uulen >= 45) {
// output the uu line length
*outptr = Encode (uulen);
outptr += ((uulen / 3) * 4) + 1;
*outptr++ = (byte) '\n';
uulen = 0;
if ((inptr + 45) <= inend) {
// we have enough input to output another full line
bufptr = outptr + 1;
} else {
bufptr = uuptr;
}
} else {
// not enough input to continue...
for (nsaved = 0, saved = 0; inptr < inend; nsaved++)
saved = (saved << 8) | *inptr++;
}
}
return (int) (outptr - output);
}
/// <summary>
/// Encodes the specified input into the output buffer.
/// </summary>
/// <returns>The number of bytes written to the output buffer.</returns>
/// <param name='input'>The input buffer.</param>
/// <param name='startIndex'>The starting index of the input buffer.</param>
/// <param name='length'>The length of the input buffer.</param>
/// <param name='output'>The output buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="input"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="output"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the <paramref name="input"/> byte array.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <para><paramref name="output"/> is not large enough to contain the encoded content.</para>
/// <para>Use the <see cref="EstimateOutputLength"/> method to properly determine the
/// necessary length of the <paramref name="output"/> byte array.</para>
/// </exception>
public int Encode (byte[] input, int startIndex, int length, byte[] output)
{
ValidateArguments (input, startIndex, length, output);
unsafe {
fixed (byte* inptr = input, outptr = output, uuptr = uubuf) {
return Encode (inptr + startIndex, length, output, outptr, uuptr);
}
}
}
unsafe int Flush (byte* input, int length, byte[] outbuf, byte* output, byte* uuptr)
{
byte* outptr = output;
if (length > 0)
outptr += Encode (input, length, outbuf, output, uuptr);
byte* bufptr = uuptr + ((uulen / 3) * 4);
byte uufill = 0;
if (nsaved > 0) {
while (nsaved < 3) {
saved <<= 8;
uufill++;
nsaved++;
}
if (nsaved == 3) {
// convert 3 input bytes into 4 uuencoded bytes
byte b0, b1, b2;
b0 = (byte) ((saved >> 16) & 0xFF);
b1 = (byte) ((saved >> 8) & 0xFF);
b2 = (byte) (saved & 0xFF);
*bufptr++ = Encode ((b0 >> 2) & 0x3F);
*bufptr++ = Encode (((b0 << 4) | ((b1 >> 4) & 0x0F)) & 0x3F);
*bufptr++ = Encode (((b1 << 2) | ((b2 >> 6) & 0x03)) & 0x3F);
*bufptr++ = Encode (b2 & 0x3F);
uulen += 3;
nsaved = 0;
saved = 0;
}
}
if (uulen > 0) {
int copylen = ((uulen / 3) * 4);
*outptr++ = Encode ((uulen - uufill) & 0xFF);
Array.Copy (uubuf, 0, outbuf, (int) (outptr - output), copylen);
outptr += copylen;
*outptr++ = (byte) '\n';
uulen = 0;
}
*outptr++ = Encode (uulen & 0xff);
*outptr++ = (byte) '\n';
Reset ();
return (int) (outptr - output);
}
/// <summary>
/// Encodes the specified input into the output buffer, flushing any internal buffer state as well.
/// </summary>
/// <returns>The number of bytes written to the output buffer.</returns>
/// <param name='input'>The input buffer.</param>
/// <param name='startIndex'>The starting index of the input buffer.</param>
/// <param name='length'>The length of the input buffer.</param>
/// <param name='output'>The output buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="input"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="output"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the <paramref name="input"/> byte array.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <para><paramref name="output"/> is not large enough to contain the encoded content.</para>
/// <para>Use the <see cref="EstimateOutputLength"/> method to properly determine the
/// necessary length of the <paramref name="output"/> byte array.</para>
/// </exception>
public int Flush (byte[] input, int startIndex, int length, byte[] output)
{
ValidateArguments (input, startIndex, length, output);
unsafe {
fixed (byte* inptr = input, outptr = output, uuptr = uubuf) {
return Flush (inptr + startIndex, length, output, outptr, uuptr);
}
}
}
/// <summary>
/// Resets the encoder.
/// </summary>
public void Reset ()
{
nsaved = 0;
saved = 0;
uulen = 0;
}
}
}
| |
// Copyright 2003 Eric Marchesin - <eric.marchesin@laposte.net>
//
// This source file(s) may be redistributed by any means PROVIDING they
// are not sold for profit without the authors expressed written consent,
// and providing that this notice and the authors name and all copyright
// notices remain intact.
// THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED. USE IT AT YOUR OWN RISK. THE AUTHOR ACCEPTS NO
// LIABILITY FOR ANY DATA DAMAGE/LOSS THAT THIS PRODUCT MAY CAUSE.
//-----------------------------------------------------------------------
using System;
using System.Collections;
namespace EMK.LightGeometry
{
/// <summary>
/// Basic geometry class : easy to replace
/// Written so as to be generalized
/// </summary>
public class Vector3D
{
double[] _Coordinates = new double[3];
/// <summary>
/// Vector3D constructor.
/// </summary>
/// <exception cref="ArgumentNullException">Argument array must not be null.</exception>
/// <exception cref="ArgumentException">The Coordinates' array must contain exactly 3 elements.</exception>
/// <param name="Coordinates">An array containing the three coordinates' values.</param>
public Vector3D(double[] Coordinates)
{
if (Coordinates == null) throw new ArgumentNullException();
if (Coordinates.Length != 3) throw new ArgumentException("The Coordinates' array must contain exactly 3 elements.");
DX = Coordinates[0]; DY = Coordinates[1]; DZ = Coordinates[2];
}
/// <summary>
/// Vector3D constructor.
/// </summary>
/// <param name="DeltaX">DX coordinate.</param>
/// <param name="DeltaY">DY coordinate.</param>
/// <param name="DeltaZ">DZ coordinate.</param>
public Vector3D(double DeltaX, double DeltaY, double DeltaZ)
{
DX = DeltaX; DY = DeltaY; DZ = DeltaZ;
}
/// <summary>
/// Constructs a Vector3D with two points.
/// </summary>
/// <param name="P1">First point of the vector.</param>
/// <param name="P2">Second point of the vector.</param>
public Vector3D(Point3D P1, Point3D P2)
{
DX = P2.X - P1.X; DY = P2.Y - P1.Y; DZ = P2.Z - P1.Z;
}
/// <summary>
/// Accede to coordinates by indexes.
/// </summary>
/// <exception cref="IndexOutOfRangeException">Illegal value for CoordinateIndex.</exception>
public double this[int CoordinateIndex]
{
get { return _Coordinates[CoordinateIndex]; }
set { _Coordinates[CoordinateIndex] = value; }
}
/// <summary>
/// Gets/Sets delta X value.
/// </summary>
public double DX { set { _Coordinates[0] = value; } get { return _Coordinates[0]; } }
/// <summary>
/// Gets/Sets delta Y value.
/// </summary>
public double DY { set { _Coordinates[1] = value; } get { return _Coordinates[1]; } }
/// <summary>
/// Gets/Sets delta Z value.
/// </summary>
public double DZ { set { _Coordinates[2] = value; } get { return _Coordinates[2]; } }
/// <summary>
/// Multiplication of a vector by a scalar value.
/// </summary>
/// <param name="V">Vector to operate.</param>
/// <param name="Factor">Factor value.</param>
/// <returns>New vector resulting from the multiplication.</returns>
public static Vector3D operator *(Vector3D V, double Factor)
{
double[] New = new double[3];
for (int i = 0; i < 3; i++) New[i] = V[i] * Factor;
return new Vector3D(New);
}
/// <summary>
/// Division of a vector by a scalar value.
/// </summary>
/// <exception cref="ArgumentException">Divider cannot be 0.</exception>
/// <param name="V">Vector to operate.</param>
/// <param name="Divider">Divider value.</param>
/// <returns>New vector resulting from the division.</returns>
public static Vector3D operator /(Vector3D V, double Divider)
{
if (Divider == 0) throw new ArgumentException("Divider cannot be 0 !\n");
double[] New = new double[3];
for (int i = 0; i < 3; i++) New[i] = V[i] / Divider;
return new Vector3D(New);
}
/// <summary>
/// Gets the square norm of the vector.
/// </summary>
public double SquareNorm
{
get
{
double Sum = 0;
for (int i = 0; i < 3; i++) Sum += _Coordinates[i] * _Coordinates[i];
return Sum;
}
}
/// <summary>
/// Gets the norm of the vector.
/// </summary>
/// <exception cref="InvalidOperationException">Vector's norm cannot be changed if it is 0.</exception>
public double Norm
{
get { return Math.Sqrt(SquareNorm); }
set
{
double N = Norm;
if (N == 0) throw new InvalidOperationException("Cannot set norm for a nul vector !");
if (N != value)
{
double Facteur = value / N;
for (int i = 0; i < 3; i++) this[i] *= Facteur;
}
}
}
/// <summary>
/// Scalar product between two vectors.
/// </summary>
/// <param name="V1">First vector.</param>
/// <param name="V2">Second vector.</param>
/// <returns>Value resulting from the scalar product.</returns>
public static double operator |(Vector3D V1, Vector3D V2)
{
double ScalarProduct = 0;
for (int i = 0; i < 3; i++) ScalarProduct += V1[i] * V2[i];
return ScalarProduct;
}
/// <summary>
/// Returns a point resulting from the translation of a specified point.
/// </summary>
/// <param name="P">Point to translate.</param>
/// <param name="V">Vector to apply for the translation.</param>
/// <returns>Point resulting from the translation.</returns>
public static Point3D operator +(Point3D P, Vector3D V)
{
double[] New = new double[3];
for (int i = 0; i < 3; i++) New[i] = P[i] + V[i];
return new Point3D(New);
}
}
public struct Vector3
{
public float X;
public float Y;
public float Z;
public Vector3(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
public float LengthSquared
{
get
{
return X * X + Y * Y + Z * Z;
}
}
public static Vector3 operator +(Vector3 a, Vector3 b)
{
return new Vector3 { X = a.X + b.X, Y = a.Y + b.Y, Z = a.Z + b.Z };
}
public static Vector3 operator -(Vector3 a, Vector3 b)
{
return new Vector3 { X = a.X - b.X, Y = a.Y - b.Y, Z = a.Z - b.Z };
}
}
}
| |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Cloud.Workflows.Common.V1Beta
{
/// <summary>Resource name for the <c>Workflow</c> resource.</summary>
public sealed partial class WorkflowName : gax::IResourceName, sys::IEquatable<WorkflowName>
{
/// <summary>The possible contents of <see cref="WorkflowName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/workflows/{workflow}</c>.
/// </summary>
ProjectLocationWorkflow = 1,
}
private static gax::PathTemplate s_projectLocationWorkflow = new gax::PathTemplate("projects/{project}/locations/{location}/workflows/{workflow}");
/// <summary>Creates a <see cref="WorkflowName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="WorkflowName"/> containing the provided <paramref name="unparsedResourceName"/>
/// .
/// </returns>
public static WorkflowName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new WorkflowName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="WorkflowName"/> with the pattern
/// <c>projects/{project}/locations/{location}/workflows/{workflow}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="workflowId">The <c>Workflow</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="WorkflowName"/> constructed from the provided ids.</returns>
public static WorkflowName FromProjectLocationWorkflow(string projectId, string locationId, string workflowId) =>
new WorkflowName(ResourceNameType.ProjectLocationWorkflow, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), workflowId: gax::GaxPreconditions.CheckNotNullOrEmpty(workflowId, nameof(workflowId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="WorkflowName"/> with pattern
/// <c>projects/{project}/locations/{location}/workflows/{workflow}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="workflowId">The <c>Workflow</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="WorkflowName"/> with pattern
/// <c>projects/{project}/locations/{location}/workflows/{workflow}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string workflowId) =>
FormatProjectLocationWorkflow(projectId, locationId, workflowId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="WorkflowName"/> with pattern
/// <c>projects/{project}/locations/{location}/workflows/{workflow}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="workflowId">The <c>Workflow</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="WorkflowName"/> with pattern
/// <c>projects/{project}/locations/{location}/workflows/{workflow}</c>.
/// </returns>
public static string FormatProjectLocationWorkflow(string projectId, string locationId, string workflowId) =>
s_projectLocationWorkflow.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(workflowId, nameof(workflowId)));
/// <summary>Parses the given resource name string into a new <see cref="WorkflowName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/workflows/{workflow}</c></description></item>
/// </list>
/// </remarks>
/// <param name="workflowName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="WorkflowName"/> if successful.</returns>
public static WorkflowName Parse(string workflowName) => Parse(workflowName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="WorkflowName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/workflows/{workflow}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="workflowName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="WorkflowName"/> if successful.</returns>
public static WorkflowName Parse(string workflowName, bool allowUnparsed) =>
TryParse(workflowName, allowUnparsed, out WorkflowName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="WorkflowName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/workflows/{workflow}</c></description></item>
/// </list>
/// </remarks>
/// <param name="workflowName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="WorkflowName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string workflowName, out WorkflowName result) => TryParse(workflowName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="WorkflowName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/workflows/{workflow}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="workflowName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="WorkflowName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string workflowName, bool allowUnparsed, out WorkflowName result)
{
gax::GaxPreconditions.CheckNotNull(workflowName, nameof(workflowName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationWorkflow.TryParseName(workflowName, out resourceName))
{
result = FromProjectLocationWorkflow(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(workflowName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private WorkflowName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string workflowId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
ProjectId = projectId;
WorkflowId = workflowId;
}
/// <summary>
/// Constructs a new instance of a <see cref="WorkflowName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/workflows/{workflow}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="workflowId">The <c>Workflow</c> ID. Must not be <c>null</c> or empty.</param>
public WorkflowName(string projectId, string locationId, string workflowId) : this(ResourceNameType.ProjectLocationWorkflow, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), workflowId: gax::GaxPreconditions.CheckNotNullOrEmpty(workflowId, nameof(workflowId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Workflow</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string WorkflowId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationWorkflow: return s_projectLocationWorkflow.Expand(ProjectId, LocationId, WorkflowId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as WorkflowName);
/// <inheritdoc/>
public bool Equals(WorkflowName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(WorkflowName a, WorkflowName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(WorkflowName a, WorkflowName b) => !(a == b);
}
}
| |
namespace Nancy.Authentication.Forms
{
using System;
using Bootstrapper;
using Cookies;
using Cryptography;
using Helpers;
using Nancy.Extensions;
using Nancy.Security;
/// <summary>
/// Nancy forms authentication implementation
/// </summary>
public static class FormsAuthentication
{
private static string formsAuthenticationCookieName = "_ncfa";
// TODO - would prefer not to hold this here, but the redirect response needs it
private static FormsAuthenticationConfiguration currentConfiguration;
/// <summary>
/// Gets or sets the forms authentication cookie name
/// </summary>
public static string FormsAuthenticationCookieName
{
get
{
return formsAuthenticationCookieName;
}
set
{
formsAuthenticationCookieName = value;
}
}
/// <summary>
/// Enables forms authentication for the application
/// </summary>
/// <param name="pipelines">Pipelines to add handlers to (usually "this")</param>
/// <param name="configuration">Forms authentication configuration</param>
public static void Enable(IPipelines pipelines, FormsAuthenticationConfiguration configuration)
{
if (pipelines == null)
{
throw new ArgumentNullException("pipelines");
}
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}
if (!configuration.IsValid)
{
throw new ArgumentException("Configuration is invalid", "configuration");
}
currentConfiguration = configuration;
pipelines.BeforeRequest.AddItemToStartOfPipeline(GetLoadAuthenticationHook(configuration));
if (!configuration.DisableRedirect)
{
pipelines.AfterRequest.AddItemToEndOfPipeline(GetRedirectToLoginHook(configuration));
}
}
/// <summary>
/// Enables forms authentication for a module
/// </summary>
/// <param name="module">Module to add handlers to (usually "this")</param>
/// <param name="configuration">Forms authentication configuration</param>
public static void Enable(INancyModule module, FormsAuthenticationConfiguration configuration)
{
if (module == null)
{
throw new ArgumentNullException("module");
}
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}
if (!configuration.IsValid)
{
throw new ArgumentException("Configuration is invalid", "configuration");
}
module.RequiresAuthentication();
currentConfiguration = configuration;
module.Before.AddItemToStartOfPipeline(GetLoadAuthenticationHook(configuration));
if (!configuration.DisableRedirect)
{
module.After.AddItemToEndOfPipeline(GetRedirectToLoginHook(configuration));
}
}
/// <summary>
/// Creates a response that sets the authentication cookie and redirects
/// the user back to where they came from.
/// </summary>
/// <param name="context">Current context</param>
/// <param name="userIdentifier">User identifier guid</param>
/// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param>
/// <param name="fallbackRedirectUrl">Url to redirect to if none in the querystring</param>
/// <returns>Nancy response with redirect.</returns>
public static Response UserLoggedInRedirectResponse(NancyContext context, Guid userIdentifier, DateTime? cookieExpiry = null, string fallbackRedirectUrl = null)
{
var redirectUrl = fallbackRedirectUrl;
if (string.IsNullOrEmpty(redirectUrl))
{
redirectUrl = context.Request.Url.BasePath;
}
if (string.IsNullOrEmpty(redirectUrl))
{
redirectUrl = "/";
}
string redirectQuerystringKey = GetRedirectQuerystringKey(currentConfiguration);
if (context.Request.Query[redirectQuerystringKey].HasValue)
{
var queryUrl = (string)context.Request.Query[redirectQuerystringKey];
if (context.IsLocalUrl(queryUrl))
{
redirectUrl = queryUrl;
}
}
var response = context.GetRedirect(redirectUrl);
var authenticationCookie = BuildCookie(userIdentifier, cookieExpiry, currentConfiguration);
response.AddCookie(authenticationCookie);
return response;
}
/// <summary>
/// Logs the user in.
/// </summary>
/// <param name="userIdentifier">User identifier guid</param>
/// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param>
/// <returns>Nancy response with status <see cref="HttpStatusCode.OK"/></returns>
public static Response UserLoggedInResponse(Guid userIdentifier, DateTime? cookieExpiry = null)
{
var response =
(Response)HttpStatusCode.OK;
var authenticationCookie =
BuildCookie(userIdentifier, cookieExpiry, currentConfiguration);
response.AddCookie(authenticationCookie);
return response;
}
/// <summary>
/// Logs the user out and redirects them to a URL
/// </summary>
/// <param name="context">Current context</param>
/// <param name="redirectUrl">URL to redirect to</param>
/// <returns>Nancy response</returns>
public static Response LogOutAndRedirectResponse(NancyContext context, string redirectUrl)
{
var response = context.GetRedirect(redirectUrl);
var authenticationCookie = BuildLogoutCookie(currentConfiguration);
response.AddCookie(authenticationCookie);
return response;
}
/// <summary>
/// Logs the user out.
/// </summary>
/// <returns>Nancy response</returns>
public static Response LogOutResponse()
{
var response =
(Response)HttpStatusCode.OK;
var authenticationCookie =
BuildLogoutCookie(currentConfiguration);
response.AddCookie(authenticationCookie);
return response;
}
/// <summary>
/// Gets the pre request hook for loading the authenticated user's details
/// from the cookie.
/// </summary>
/// <param name="configuration">Forms authentication configuration to use</param>
/// <returns>Pre request hook delegate</returns>
private static Func<NancyContext, Response> GetLoadAuthenticationHook(FormsAuthenticationConfiguration configuration)
{
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}
return context =>
{
var userGuid = GetAuthenticatedUserFromCookie(context, configuration);
if (userGuid != Guid.Empty)
{
context.CurrentUser = configuration.UserMapper.GetUserFromIdentifier(userGuid, context);
}
return null;
};
}
/// <summary>
/// Gets the post request hook for redirecting to the login page
/// </summary>
/// <param name="configuration">Forms authentication configuration to use</param>
/// <returns>Post request hook delegate</returns>
private static Action<NancyContext> GetRedirectToLoginHook(FormsAuthenticationConfiguration configuration)
{
return context =>
{
if (context.Response.StatusCode == HttpStatusCode.Unauthorized)
{
string redirectQuerystringKey = GetRedirectQuerystringKey(configuration);
context.Response = context.GetRedirect(
string.Format("{0}?{1}={2}",
configuration.RedirectUrl,
redirectQuerystringKey,
context.ToFullPath("~" + context.Request.Path + HttpUtility.UrlEncode(context.Request.Url.Query))));
}
};
}
/// <summary>
/// Gets the authenticated user GUID from the incoming request cookie if it exists
/// and is valid.
/// </summary>
/// <param name="context">Current context</param>
/// <param name="configuration">Current configuration</param>
/// <returns>Returns user guid, or Guid.Empty if not present or invalid</returns>
private static Guid GetAuthenticatedUserFromCookie(NancyContext context, FormsAuthenticationConfiguration configuration)
{
if (!context.Request.Cookies.ContainsKey(formsAuthenticationCookieName))
{
return Guid.Empty;
}
var cookieValueEncrypted = context.Request.Cookies[formsAuthenticationCookieName];
if (string.IsNullOrEmpty(cookieValueEncrypted))
{
return Guid.Empty;
}
var cookieValue = DecryptAndValidateAuthenticationCookie(cookieValueEncrypted, configuration);
Guid returnGuid;
if (String.IsNullOrEmpty(cookieValue) || !Guid.TryParse(cookieValue, out returnGuid))
{
return Guid.Empty;
}
return returnGuid;
}
/// <summary>
/// Build the forms authentication cookie
/// </summary>
/// <param name="userIdentifier">Authenticated user identifier</param>
/// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param>
/// <param name="configuration">Current configuration</param>
/// <returns>Nancy cookie instance</returns>
private static INancyCookie BuildCookie(Guid userIdentifier, DateTime? cookieExpiry, FormsAuthenticationConfiguration configuration)
{
var cookieContents = EncryptAndSignCookie(userIdentifier.ToString(), configuration);
var cookie = new NancyCookie(formsAuthenticationCookieName, cookieContents, true, configuration.RequiresSSL, cookieExpiry);
if(!string.IsNullOrEmpty(configuration.Domain))
{
cookie.Domain = configuration.Domain;
}
if(!string.IsNullOrEmpty(configuration.Path))
{
cookie.Path = configuration.Path;
}
return cookie;
}
/// <summary>
/// Builds a cookie for logging a user out
/// </summary>
/// <param name="configuration">Current configuration</param>
/// <returns>Nancy cookie instance</returns>
private static INancyCookie BuildLogoutCookie(FormsAuthenticationConfiguration configuration)
{
var cookie = new NancyCookie(formsAuthenticationCookieName, String.Empty, true, configuration.RequiresSSL, DateTime.Now.AddDays(-1));
if(!string.IsNullOrEmpty(configuration.Domain))
{
cookie.Domain = configuration.Domain;
}
if(!string.IsNullOrEmpty(configuration.Path))
{
cookie.Path = configuration.Path;
}
return cookie;
}
/// <summary>
/// Encrypt and sign the cookie contents
/// </summary>
/// <param name="cookieValue">Plain text cookie value</param>
/// <param name="configuration">Current configuration</param>
/// <returns>Encrypted and signed string</returns>
private static string EncryptAndSignCookie(string cookieValue, FormsAuthenticationConfiguration configuration)
{
var encryptedCookie = configuration.CryptographyConfiguration.EncryptionProvider.Encrypt(cookieValue);
var hmacBytes = GenerateHmac(encryptedCookie, configuration);
var hmacString = Convert.ToBase64String(hmacBytes);
return String.Format("{1}{0}", encryptedCookie, hmacString);
}
/// <summary>
/// Generate a hmac for the encrypted cookie string
/// </summary>
/// <param name="encryptedCookie">Encrypted cookie string</param>
/// <param name="configuration">Current configuration</param>
/// <returns>Hmac byte array</returns>
private static byte[] GenerateHmac(string encryptedCookie, FormsAuthenticationConfiguration configuration)
{
return configuration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedCookie);
}
/// <summary>
/// Decrypt and validate an encrypted and signed cookie value
/// </summary>
/// <param name="cookieValue">Encrypted and signed cookie value</param>
/// <param name="configuration">Current configuration</param>
/// <returns>Decrypted value, or empty on error or if failed validation</returns>
public static string DecryptAndValidateAuthenticationCookie(string cookieValue, FormsAuthenticationConfiguration configuration)
{
// TODO - shouldn't this be automatically decoded by nancy cookie when that change is made?
var decodedCookie = Helpers.HttpUtility.UrlDecode(cookieValue);
var hmacStringLength = Base64Helpers.GetBase64Length(configuration.CryptographyConfiguration.HmacProvider.HmacLength);
var encryptedCookie = decodedCookie.Substring(hmacStringLength);
var hmacString = decodedCookie.Substring(0, hmacStringLength);
var encryptionProvider = configuration.CryptographyConfiguration.EncryptionProvider;
// Check the hmacs, but don't early exit if they don't match
var hmacBytes = Convert.FromBase64String(hmacString);
var newHmac = GenerateHmac(encryptedCookie, configuration);
var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, configuration.CryptographyConfiguration.HmacProvider.HmacLength);
var decrypted = encryptionProvider.Decrypt(encryptedCookie);
// Only return the decrypted result if the hmac was ok
return hmacValid ? decrypted : string.Empty;
}
/// <summary>
/// Gets the redirect query string key from <see cref="FormsAuthenticationConfiguration"/>
/// </summary>
/// <param name="configuration">The forms authentication configuration.</param>
/// <returns>Redirect Querystring key</returns>
private static string GetRedirectQuerystringKey(FormsAuthenticationConfiguration configuration)
{
string redirectQuerystringKey = null;
if (configuration != null)
{
redirectQuerystringKey = configuration.RedirectQuerystringKey;
}
if(string.IsNullOrWhiteSpace(redirectQuerystringKey))
{
redirectQuerystringKey = FormsAuthenticationConfiguration.DefaultRedirectQuerystringKey;
}
return redirectQuerystringKey;
}
}
}
| |
namespace PTWisej
{
partial class MainPage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Wisej 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(MainPage));
this.toolStrip1 = new Wisej.Web.ToolBar();
this.ProjectsStripDropDownButton1 = new Wisej.Web.ToolBarButton();
this.projectsMenu = new Wisej.Web.ContextMenu();
this.NewProjectToolStripMenuItem = new Wisej.Web.MenuItem();
this.EditProjectToolStripMenuItem = new Wisej.Web.MenuItem();
this.DeleteProjectToolStripMenuItem = new Wisej.Web.MenuItem();
this.ResourcesToolStripDropDownButton = new Wisej.Web.ToolBarButton();
this.resourcesMenu = new Wisej.Web.ContextMenu();
this.NewResourceToolStripMenuItem = new Wisej.Web.MenuItem();
this.EditResourceToolStripMenuItem = new Wisej.Web.MenuItem();
this.DeleteResourceToolStripMenuItem = new Wisej.Web.MenuItem();
this.AdminToolStripDropDownButton = new Wisej.Web.ToolBarButton();
this.adminMenu = new Wisej.Web.ContextMenu();
this.EditRolesToolStripMenuItem = new Wisej.Web.MenuItem();
this.LoginToolStripLabel = new Wisej.Web.ToolBarButton();
this.LoginToolStripButton = new Wisej.Web.ToolBarButton();
this.DocumentsToolStripDropDownButton = new Wisej.Web.ToolBarButton();
this.documentsMenu = new Wisej.Web.ContextMenu();
this.Panel1 = new Wisej.Web.Panel();
this.StatusStrip1 = new Wisej.Web.StatusBar();
this.StatusLabel = new Wisej.Web.StatusBarPanel();
this.SuspendLayout();
//
// toolStrip1
//
this.toolStrip1.Buttons.AddRange(new Wisej.Web.ToolBarButton[] {
this.ProjectsStripDropDownButton1,
this.ResourcesToolStripDropDownButton,
this.AdminToolStripDropDownButton,
this.LoginToolStripLabel,
this.LoginToolStripButton,
this.DocumentsToolStripDropDownButton});
this.toolStrip1.Location = new System.Drawing.Point(0, 0);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(946, 26);
this.toolStrip1.TabIndex = 1;
this.toolStrip1.TabStop = false;
this.toolStrip1.TextAlign = Wisej.Web.ToolBarTextAlign.Right;
this.toolStrip1.ButtonDropDown += new Wisej.Web.ToolBarButtonClickEventHandler(this.DocumentsToolStripDropDownButton_DropDownOpening);
//
// ProjectsStripDropDownButton1
//
this.ProjectsStripDropDownButton1.DropDownMenu = this.projectsMenu;
this.ProjectsStripDropDownButton1.Image = ((System.Drawing.Image)(resources.GetObject("ProjectsStripDropDownButton1.Image")));
this.ProjectsStripDropDownButton1.Name = "ProjectsStripDropDownButton1";
this.ProjectsStripDropDownButton1.Style = Wisej.Web.ToolBarButtonStyle.DropDownButton;
this.ProjectsStripDropDownButton1.Text = "Projects";
//
// projectsMenu
//
this.projectsMenu.MenuItems.AddRange(new Wisej.Web.MenuItem[] {
this.NewProjectToolStripMenuItem,
this.EditProjectToolStripMenuItem,
this.DeleteProjectToolStripMenuItem});
this.projectsMenu.Name = "projectsMenu";
//
// NewProjectToolStripMenuItem
//
this.NewProjectToolStripMenuItem.Index = 0;
this.NewProjectToolStripMenuItem.Name = "NewProjectToolStripMenuItem";
this.NewProjectToolStripMenuItem.Text = "New project";
this.NewProjectToolStripMenuItem.Click += new System.EventHandler(this.NewProjectToolStripMenuItem_Click);
//
// EditProjectToolStripMenuItem
//
this.EditProjectToolStripMenuItem.Index = 1;
this.EditProjectToolStripMenuItem.Name = "EditProjectToolStripMenuItem";
this.EditProjectToolStripMenuItem.Text = "Edit project";
this.EditProjectToolStripMenuItem.Click += new System.EventHandler(this.EditProjectToolStripMenuItem_Click);
//
// DeleteProjectToolStripMenuItem
//
this.DeleteProjectToolStripMenuItem.Index = 2;
this.DeleteProjectToolStripMenuItem.Name = "DeleteProjectToolStripMenuItem";
this.DeleteProjectToolStripMenuItem.Text = "Delete project";
this.DeleteProjectToolStripMenuItem.Click += new System.EventHandler(this.DeleteProjectToolStripMenuItem_Click);
//
// ResourcesToolStripDropDownButton
//
this.ResourcesToolStripDropDownButton.DropDownMenu = this.resourcesMenu;
this.ResourcesToolStripDropDownButton.Image = ((System.Drawing.Image)(resources.GetObject("ResourcesToolStripDropDownButton.Image")));
this.ResourcesToolStripDropDownButton.Name = "ResourcesToolStripDropDownButton";
this.ResourcesToolStripDropDownButton.Style = Wisej.Web.ToolBarButtonStyle.DropDownButton;
this.ResourcesToolStripDropDownButton.Text = "Resources";
//
// resourcesMenu
//
this.resourcesMenu.MenuItems.AddRange(new Wisej.Web.MenuItem[] {
this.NewResourceToolStripMenuItem,
this.EditResourceToolStripMenuItem,
this.DeleteResourceToolStripMenuItem});
this.resourcesMenu.Name = "resourcesMenu";
//
// NewResourceToolStripMenuItem
//
this.NewResourceToolStripMenuItem.Index = 0;
this.NewResourceToolStripMenuItem.Name = "NewResourceToolStripMenuItem";
this.NewResourceToolStripMenuItem.Text = "New resource";
this.NewResourceToolStripMenuItem.Click += new System.EventHandler(this.NewResourceToolStripMenuItem_Click);
//
// EditResourceToolStripMenuItem
//
this.EditResourceToolStripMenuItem.Index = 1;
this.EditResourceToolStripMenuItem.Name = "EditResourceToolStripMenuItem";
this.EditResourceToolStripMenuItem.Text = "Edit resource";
this.EditResourceToolStripMenuItem.Click += new System.EventHandler(this.EditResourceToolStripMenuItem_Click);
//
// DeleteResourceToolStripMenuItem
//
this.DeleteResourceToolStripMenuItem.Index = 2;
this.DeleteResourceToolStripMenuItem.Name = "DeleteResourceToolStripMenuItem";
this.DeleteResourceToolStripMenuItem.Text = "Delete resource";
this.DeleteResourceToolStripMenuItem.Click += new System.EventHandler(this.DeleteResourceToolStripMenuItem_Click);
//
// AdminToolStripDropDownButton
//
this.AdminToolStripDropDownButton.DropDownMenu = this.adminMenu;
this.AdminToolStripDropDownButton.Image = ((System.Drawing.Image)(resources.GetObject("AdminToolStripDropDownButton.Image")));
this.AdminToolStripDropDownButton.Name = "AdminToolStripDropDownButton";
this.AdminToolStripDropDownButton.Style = Wisej.Web.ToolBarButtonStyle.DropDownButton;
this.AdminToolStripDropDownButton.Text = "Admin";
//
// adminMenu
//
this.adminMenu.MenuItems.AddRange(new Wisej.Web.MenuItem[] {
this.EditRolesToolStripMenuItem});
this.adminMenu.Name = "adminMenu";
//
// EditRolesToolStripMenuItem
//
this.EditRolesToolStripMenuItem.Index = 0;
this.EditRolesToolStripMenuItem.Name = "EditRolesToolStripMenuItem";
this.EditRolesToolStripMenuItem.Text = "Edit roles";
this.EditRolesToolStripMenuItem.Click += new System.EventHandler(this.EditRolesToolStripMenuItem_Click);
//
// LoginToolStripLabel
//
this.LoginToolStripLabel.Name = "LoginToolStripLabel";
this.LoginToolStripLabel.Text = "Not logged in";
//
// LoginToolStripButton
//
this.LoginToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("LoginToolStripButton.Image")));
this.LoginToolStripButton.Name = "LoginToolStripButton";
this.LoginToolStripButton.Text = "Login";
this.LoginToolStripButton.Click += new System.EventHandler(this.LoginToolStripButton_Click);
//
// DocumentsToolStripDropDownButton
//
this.DocumentsToolStripDropDownButton.DropDownMenu = this.documentsMenu;
this.DocumentsToolStripDropDownButton.Image = ((System.Drawing.Image)(resources.GetObject("DocumentsToolStripDropDownButton.Image")));
this.DocumentsToolStripDropDownButton.Name = "DocumentsToolStripDropDownButton";
this.DocumentsToolStripDropDownButton.Style = Wisej.Web.ToolBarButtonStyle.DropDownButton;
this.DocumentsToolStripDropDownButton.Text = "Documents";
//
// documentsMenu
//
this.documentsMenu.Name = "documentsMenu";
//
// Panel1
//
this.Panel1.BackColor = System.Drawing.SystemColors.ControlDark;
this.Panel1.Dock = Wisej.Web.DockStyle.Fill;
this.Panel1.Location = new System.Drawing.Point(0, 26);
this.Panel1.Name = "Panel1";
this.Panel1.Size = new System.Drawing.Size(946, 695);
this.Panel1.TabIndex = 2;
//
// StatusStrip1
//
this.StatusStrip1.Location = new System.Drawing.Point(0, 699);
this.StatusStrip1.Name = "StatusStrip1";
this.StatusStrip1.Panels.AddRange(new Wisej.Web.StatusBarPanel[] {
this.StatusLabel});
this.StatusStrip1.Size = new System.Drawing.Size(946, 22);
this.StatusStrip1.TabIndex = 3;
this.StatusStrip1.Text = "26+22";
//
// StatusLabel
//
this.StatusLabel.Name = "StatusLabel";
this.StatusLabel.Text = null;
//
// MainPage
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 14F);
this.AutoScaleMode = Wisej.Web.AutoScaleMode.Font;
this.Controls.Add(this.StatusStrip1);
this.Controls.Add(this.Panel1);
this.Controls.Add(this.toolStrip1);
this.Name = "MainPage";
this.Size = new System.Drawing.Size(946, 721);
this.Text = "Project Tracker";
this.Load += new System.EventHandler(this.MainForm_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
internal Wisej.Web.ToolBar toolStrip1;
internal Wisej.Web.ToolBarButton ProjectsStripDropDownButton1;
internal Wisej.Web.MenuItem NewProjectToolStripMenuItem;
internal Wisej.Web.MenuItem EditProjectToolStripMenuItem;
internal Wisej.Web.MenuItem DeleteProjectToolStripMenuItem;
internal Wisej.Web.ToolBarButton LoginToolStripLabel;
internal Wisej.Web.ToolBarButton LoginToolStripButton;
internal Wisej.Web.ToolBarButton ResourcesToolStripDropDownButton;
internal Wisej.Web.MenuItem NewResourceToolStripMenuItem;
internal Wisej.Web.MenuItem EditResourceToolStripMenuItem;
internal Wisej.Web.MenuItem DeleteResourceToolStripMenuItem;
internal Wisej.Web.ToolBarButton AdminToolStripDropDownButton;
internal Wisej.Web.MenuItem EditRolesToolStripMenuItem;
internal Wisej.Web.ToolBarButton DocumentsToolStripDropDownButton;
internal Wisej.Web.Panel Panel1;
internal Wisej.Web.StatusBar StatusStrip1;
internal Wisej.Web.StatusBarPanel StatusLabel;
private Wisej.Web.ContextMenu projectsMenu;
private Wisej.Web.ContextMenu resourcesMenu;
private Wisej.Web.ContextMenu adminMenu;
private Wisej.Web.ContextMenu documentsMenu;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using GraphQL.StarWars.Types;
using GraphQL.Types;
using GraphQL.Types.Relay;
using Shouldly;
using Xunit;
namespace GraphQL.Tests.Types
{
public class SchemaTests
{
[Fact]
public void registers_interfaces_when_not_used_in_fields()
{
var schema = new AnInterfaceSchema();
var result = schema.AllTypes.SingleOrDefault(x => x.Name == "AnInterfaceType");
result.ShouldNotBeNull("Interface type should be registered");
}
[Fact]
public void recursively_registers_children()
{
var schema = new ARootSchema();
ContainsTypeNames(
schema,
"RootSchemaType",
"ASchemaType",
"BSchemaType",
"CSchemaType",
"DSchemaType");
}
[Fact]
public void registers_argument_input_objects()
{
var schema = new ARootSchema();
ContainsTypeNames(
schema,
"DInputType");
}
[Fact]
public void registers_argument_input_objects_when_argument_resolved_type_is_set()
{
var schema = new ARootSchema();
ContainsTypeNames(
schema,
"DInputType",
"DInputType2");
}
[Fact]
public void registers_type_when_list()
{
var schema = new ARootSchema();
ContainsTypeNames(
schema,
"DListType");
}
[Fact]
public void registers_union_types()
{
var schema = new ARootSchema();
ContainsTypeNames(
schema,
"AUnion",
"WithoutIsTypeOf1Type",
"WithoutIsTypeOf2Type");
}
[Fact]
public void throw_error_on_missing_istypeof()
{
var schema = new InvalidUnionSchema();
Should.Throw<InvalidOperationException>(() => schema.AllTypes["a"]);
}
[Fact]
public void throw_error_on_non_graphtype_with_register_types()
{
var schema = new Schema();
Should.Throw<ArgumentOutOfRangeException>(() => schema.RegisterTypes(typeof(MyDto)));
}
[Fact]
public void throw_error_on_null_with_register_types()
{
var schema = new Schema();
Type[] types = null;
Should.Throw<ArgumentNullException>(() => schema.RegisterTypes(types));
}
[Fact]
public void registers_additional_types()
{
var schema = new AnInterfaceOnlySchemaWithExtraRegisteredType();
ContainsTypeNames(schema, "SomeQuery", "SomeInterface", "SomeObject");
}
[Fact]
public void registers_additional_duplicated_types()
{
var schema = new SchemaWithDuplicates();
ContainsTypeNames(schema, "SomeQuery", "SomeInterface", "SomeObject");
}
[Fact]
public void registers_only_root_types()
{
var schema = new ARootSchema();
DoesNotContainTypeNames(schema, "ASchemaType!");
}
[Fact]
public void handles_cycle_field_type()
{
var schema = new SimpleCycleSchema();
schema.AllTypes["CycleType"].ShouldNotBeNull();
}
[Fact]
public void handles_stackoverflow_exception_for_cycle_field_type()
{
var schema = new ACyclingDerivingSchema(new FuncServiceProvider(t => t == typeof(AbstractGraphType) ? new ConcreteGraphType() : null));
Should.Throw<InvalidOperationException>(() => schema.AllTypes["abcd"]);
}
private void ContainsTypeNames(ISchema schema, params string[] typeNames)
{
foreach (var typeName in typeNames)
{
var type = schema.AllTypes[typeName];
type.ShouldNotBeNull($"Did not find {typeName} in type lookup.");
}
}
private void DoesNotContainTypeNames(Schema schema, params string[] typeNames)
{
foreach (var typeName in typeNames)
{
var type = schema.AllTypes.SingleOrDefault(x => x.Name == typeName);
type.ShouldBe(null, $"Found {typeName} in type lookup.");
}
}
[Fact]
public void middleware_can_reference_SchemaTypes()
{
var schema = new Schema { Query = new SomeQuery() };
schema.FieldMiddleware.Use(next =>
{
schema.AllTypes.Count.ShouldNotBe(0);
return async context =>
{
var res = await next(context);
return "One " + res;
};
});
schema.Initialize();
}
[Fact]
public void disposed_schema_throws_errors()
{
var schema = new Schema();
schema.Initialized.ShouldBeFalse();
schema.Dispose();
schema.Dispose();
schema.Initialized.ShouldBeFalse();
Should.Throw<ObjectDisposedException>(() => schema.Initialize());
Should.Throw<ObjectDisposedException>(() => schema.RegisterType(new ObjectGraphType { Name = "test" }));
Should.Throw<ObjectDisposedException>(() => schema.RegisterTypes(typeof(DroidType)));
Should.Throw<ObjectDisposedException>(() => schema.RegisterType<DroidType>());
}
[Fact]
public void initialized_schema_should_throw_error_when_register_type_or_directive()
{
var schema = new Schema();
schema.Initialized.ShouldBeFalse();
schema.Initialize();
schema.Initialized.ShouldBeTrue();
Should.Throw<InvalidOperationException>(() => schema.RegisterType(new ObjectGraphType { Name = "test" }));
Should.Throw<InvalidOperationException>(() => schema.RegisterTypes(typeof(DroidType)));
Should.Throw<InvalidOperationException>(() => schema.RegisterType<DroidType>());
}
[Fact]
public void generic_types_of_mapped_clr_reference_types_should_resolve()
{
var schema = new Schema();
var query = new ObjectGraphType();
var field = query.Field(typeof(ConnectionType<GraphQLClrOutputTypeReference<MyDto>>), "test");
schema.Query = query;
schema.RegisterTypeMapping<MyDto, MyDtoGraphType>();
schema.Initialize();
field.ResolvedType.ShouldNotBeNull();
field.ResolvedType.ShouldBeOfType<ConnectionType<MyDtoGraphType>>();
}
[Fact]
public void can_have_unknown_input_types_mapped_to_auto_registering_graph()
{
var schema = new CustomTypesSchema();
var query = new ObjectGraphType();
var field = new FieldType()
{
Name = "test",
Type = typeof(IntGraphType),
Arguments = new QueryArguments
{
new QueryArgument(typeof(GraphQLClrInputTypeReference<CustomData>)) { Name = "arg" }
}
};
query.AddField(field);
schema.Query = query;
schema.Initialize();
schema.Query.Fields.Find("test").Arguments[0].ResolvedType.ShouldBeOfType<AutoRegisteringInputObjectGraphType<CustomData>>();
}
}
public class CustomData
{
public string Value { get; set; }
}
public class CustomTypesSchema : Schema
{
protected override SchemaTypes CreateSchemaTypes()
=> new CustomSchemaTypes(this, this);
}
public class CustomSchemaTypes : SchemaTypes
{
public CustomSchemaTypes(ISchema schema, IServiceProvider serviceProvider)
: base(schema, serviceProvider)
{
}
protected override Type GetGraphTypeFromClrType(Type clrType, bool isInputType, List<(Type ClrType, Type GraphType)> typeMappings)
{
var ret = base.GetGraphTypeFromClrType(clrType, isInputType, typeMappings);
if (ret == null && isInputType)
{
return typeof(AutoRegisteringInputObjectGraphType<>).MakeGenericType(clrType);
}
return ret;
}
}
public class MyDtoGraphType : ObjectGraphType<MyDto>
{
public MyDtoGraphType()
{
Field<BooleanGraphType>("dummy");
}
}
public class MyDto
{
}
public class AnInterfaceOnlySchemaWithExtraRegisteredType : Schema
{
public AnInterfaceOnlySchemaWithExtraRegisteredType()
{
Query = new SomeQuery();
this.RegisterType<SomeObject>();
}
}
public class SchemaWithDuplicates : Schema
{
public SchemaWithDuplicates()
{
Query = new SomeQuery();
this.RegisterType<SomeObject>();
this.RegisterType<SomeObject>();
this.RegisterType<SomeQuery>();
this.RegisterType<SomeQuery>();
this.RegisterType<SomeInterface>();
this.RegisterType<SomeInterface>();
this.RegisterType<StringGraphType>();
this.RegisterType<StringGraphType>();
}
}
public class SomeQuery : ObjectGraphType
{
public SomeQuery()
{
Name = "SomeQuery";
Field<SomeInterface>("something");
}
}
public class SomeObject : ObjectGraphType
{
public SomeObject()
{
Name = "SomeObject";
Field<StringGraphType>("name");
Interface<SomeInterface>();
IsTypeOf = t => true;
}
}
public class SomeInterface : InterfaceGraphType
{
public SomeInterface()
{
Name = "SomeInterface";
Field<StringGraphType>("name");
}
}
public class AnInterfaceSchema : Schema
{
public AnInterfaceSchema()
{
Query = new AnObjectType();
}
}
public class AnObjectType : ObjectGraphType
{
public AnObjectType()
{
Name = "AnObjectType";
Field<StringGraphType>("name");
Interface<AnInterfaceType>();
}
}
public class AnInterfaceType : InterfaceGraphType
{
public AnInterfaceType()
{
Name = "AnInterfaceType";
Field<StringGraphType>("name");
ResolveType = value => null;
}
}
public class ARootSchema : Schema
{
public ARootSchema()
{
Query = new RootSchemaType();
}
}
public class RootSchemaType : ObjectGraphType
{
public RootSchemaType()
{
Field<ASchemaType>("a");
Field<NonNullGraphType<ASchemaType>>("nonNullA");
Field<AUnionType>("union");
}
}
public class InvalidUnionSchema : Schema
{
public InvalidUnionSchema()
{
Query = new InvalidUnionSchemaType();
}
}
public class InvalidUnionSchemaType : ObjectGraphType
{
public InvalidUnionSchemaType()
{
Field<AUnionWithoutResolveType>("union");
}
}
public class ASchemaType : ObjectGraphType
{
public ASchemaType()
{
Field<BSchemaType>("b");
}
}
public class BSchemaType : ObjectGraphType
{
public BSchemaType()
{
Field<CSchemaType>("c");
}
}
public class CSchemaType : ObjectGraphType
{
public CSchemaType()
{
Field<DSchemaType>("d");
}
}
public class DSchemaType : ObjectGraphType
{
public DSchemaType()
{
Field<StringGraphType>("id", resolve: ctx => new { id = "id" });
Field<StringGraphType>(
"filter",
arguments: new QueryArguments(new QueryArgument<DInputType> { Name = "input", ResolvedType = new DInputType() }, new QueryArgument<DInputType2> { Name = "input2", ResolvedType = new DInputType2() }),
resolve: ctx => new { id = "id" });
Field<ListGraphType<DListType>>("alist");
}
}
public class DInputType : InputObjectGraphType
{
public DInputType()
{
Name = "DInputType";
Field<StringGraphType>("one");
}
}
public class DInputType2 : InputObjectGraphType
{
public DInputType2()
{
Name = "DInputType2";
Field<StringGraphType>("two");
}
}
public class DListType : ObjectGraphType
{
public DListType()
{
Field<StringGraphType>("list");
}
}
public class AUnionType : UnionGraphType
{
public AUnionType()
{
Name = "AUnion";
Type<WithoutIsTypeOf1Type>();
Type<WithoutIsTypeOf2Type>();
ResolveType = value => null;
}
}
public class AUnionWithoutResolveType : UnionGraphType
{
public AUnionWithoutResolveType()
{
Name = "AUnionWithoutResolve";
Type<WithoutIsTypeOf1Type>();
Type<WithoutIsTypeOf2Type>();
}
}
public class WithoutIsTypeOf1Type : ObjectGraphType
{
public WithoutIsTypeOf1Type()
{
Field<StringGraphType>("unused");
}
}
public class WithoutIsTypeOf2Type : ObjectGraphType
{
public WithoutIsTypeOf2Type()
{
Field<StringGraphType>("unused");
}
}
public class SimpleCycleSchema : Schema
{
public SimpleCycleSchema()
{
Query = new CycleType();
}
}
public class CycleType : ObjectGraphType
{
public CycleType()
{
Field<CycleType>();
}
}
public class ACyclingDerivingSchema : Schema
{
public ACyclingDerivingSchema(IServiceProvider provider) : base(provider)
{
Query = new CyclingQueryType();
}
}
public class CyclingQueryType : ObjectGraphType
{
public CyclingQueryType()
{
Field<AbstractGraphType>();
}
}
public abstract class AbstractGraphType : ObjectGraphType
{
public AbstractGraphType()
{
Field<AbstractGraphType>();
}
}
public class ConcreteGraphType : AbstractGraphType
{
}
}
| |
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace Org.Webrtc {
// Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='GlShader']"
[global::Android.Runtime.Register ("org/webrtc/GlShader", DoNotGenerateAcw=true)]
public partial class GlShader : global::Java.Lang.Object {
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/webrtc/GlShader", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (GlShader); }
}
protected GlShader (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor_Ljava_lang_String_Ljava_lang_String_;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='GlShader']/constructor[@name='GlShader' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String']]"
[Register (".ctor", "(Ljava/lang/String;Ljava/lang/String;)V", "")]
public unsafe GlShader (string p0, string p1)
: base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
IntPtr native_p0 = JNIEnv.NewString (p0);
IntPtr native_p1 = JNIEnv.NewString (p1);
try {
JValue* __args = stackalloc JValue [2];
__args [0] = new JValue (native_p0);
__args [1] = new JValue (native_p1);
if (GetType () != typeof (GlShader)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Ljava/lang/String;Ljava/lang/String;)V", __args),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Ljava/lang/String;Ljava/lang/String;)V", __args);
return;
}
if (id_ctor_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero)
id_ctor_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/lang/String;Ljava/lang/String;)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_lang_String_Ljava_lang_String_, __args),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Ljava_lang_String_Ljava_lang_String_, __args);
} finally {
JNIEnv.DeleteLocalRef (native_p0);
JNIEnv.DeleteLocalRef (native_p1);
}
}
static Delegate cb_getAttribLocation_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetGetAttribLocation_Ljava_lang_String_Handler ()
{
if (cb_getAttribLocation_Ljava_lang_String_ == null)
cb_getAttribLocation_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, int>) n_GetAttribLocation_Ljava_lang_String_);
return cb_getAttribLocation_Ljava_lang_String_;
}
static int n_GetAttribLocation_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Webrtc.GlShader __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.GlShader> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
int __ret = __this.GetAttribLocation (p0);
return __ret;
}
#pragma warning restore 0169
static IntPtr id_getAttribLocation_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='GlShader']/method[@name='getAttribLocation' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register ("getAttribLocation", "(Ljava/lang/String;)I", "GetGetAttribLocation_Ljava_lang_String_Handler")]
public virtual unsafe int GetAttribLocation (string p0)
{
if (id_getAttribLocation_Ljava_lang_String_ == IntPtr.Zero)
id_getAttribLocation_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "getAttribLocation", "(Ljava/lang/String;)I");
IntPtr native_p0 = JNIEnv.NewString (p0);
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (native_p0);
int __ret;
if (GetType () == ThresholdType)
__ret = JNIEnv.CallIntMethod (Handle, id_getAttribLocation_Ljava_lang_String_, __args);
else
__ret = JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getAttribLocation", "(Ljava/lang/String;)I"), __args);
return __ret;
} finally {
JNIEnv.DeleteLocalRef (native_p0);
}
}
static Delegate cb_getUniformLocation_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetGetUniformLocation_Ljava_lang_String_Handler ()
{
if (cb_getUniformLocation_Ljava_lang_String_ == null)
cb_getUniformLocation_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, int>) n_GetUniformLocation_Ljava_lang_String_);
return cb_getUniformLocation_Ljava_lang_String_;
}
static int n_GetUniformLocation_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Webrtc.GlShader __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.GlShader> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
int __ret = __this.GetUniformLocation (p0);
return __ret;
}
#pragma warning restore 0169
static IntPtr id_getUniformLocation_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='GlShader']/method[@name='getUniformLocation' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register ("getUniformLocation", "(Ljava/lang/String;)I", "GetGetUniformLocation_Ljava_lang_String_Handler")]
public virtual unsafe int GetUniformLocation (string p0)
{
if (id_getUniformLocation_Ljava_lang_String_ == IntPtr.Zero)
id_getUniformLocation_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "getUniformLocation", "(Ljava/lang/String;)I");
IntPtr native_p0 = JNIEnv.NewString (p0);
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (native_p0);
int __ret;
if (GetType () == ThresholdType)
__ret = JNIEnv.CallIntMethod (Handle, id_getUniformLocation_Ljava_lang_String_, __args);
else
__ret = JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getUniformLocation", "(Ljava/lang/String;)I"), __args);
return __ret;
} finally {
JNIEnv.DeleteLocalRef (native_p0);
}
}
static Delegate cb_release;
#pragma warning disable 0169
static Delegate GetReleaseHandler ()
{
if (cb_release == null)
cb_release = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_Release);
return cb_release;
}
static void n_Release (IntPtr jnienv, IntPtr native__this)
{
global::Org.Webrtc.GlShader __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.GlShader> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.Release ();
}
#pragma warning restore 0169
static IntPtr id_release;
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='GlShader']/method[@name='release' and count(parameter)=0]"
[Register ("release", "()V", "GetReleaseHandler")]
public virtual unsafe void Release ()
{
if (id_release == IntPtr.Zero)
id_release = JNIEnv.GetMethodID (class_ref, "release", "()V");
try {
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_release);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "release", "()V"));
} finally {
}
}
static Delegate cb_setVertexAttribArray_Ljava_lang_String_ILjava_nio_FloatBuffer_;
#pragma warning disable 0169
static Delegate GetSetVertexAttribArray_Ljava_lang_String_ILjava_nio_FloatBuffer_Handler ()
{
if (cb_setVertexAttribArray_Ljava_lang_String_ILjava_nio_FloatBuffer_ == null)
cb_setVertexAttribArray_Ljava_lang_String_ILjava_nio_FloatBuffer_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, int, IntPtr>) n_SetVertexAttribArray_Ljava_lang_String_ILjava_nio_FloatBuffer_);
return cb_setVertexAttribArray_Ljava_lang_String_ILjava_nio_FloatBuffer_;
}
static void n_SetVertexAttribArray_Ljava_lang_String_ILjava_nio_FloatBuffer_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, int p1, IntPtr native_p2)
{
global::Org.Webrtc.GlShader __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.GlShader> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
global::Java.Nio.FloatBuffer p2 = global::Java.Lang.Object.GetObject<global::Java.Nio.FloatBuffer> (native_p2, JniHandleOwnership.DoNotTransfer);
__this.SetVertexAttribArray (p0, p1, p2);
}
#pragma warning restore 0169
static IntPtr id_setVertexAttribArray_Ljava_lang_String_ILjava_nio_FloatBuffer_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='GlShader']/method[@name='setVertexAttribArray' and count(parameter)=3 and parameter[1][@type='java.lang.String'] and parameter[2][@type='int'] and parameter[3][@type='java.nio.FloatBuffer']]"
[Register ("setVertexAttribArray", "(Ljava/lang/String;ILjava/nio/FloatBuffer;)V", "GetSetVertexAttribArray_Ljava_lang_String_ILjava_nio_FloatBuffer_Handler")]
public virtual unsafe void SetVertexAttribArray (string p0, int p1, global::Java.Nio.FloatBuffer p2)
{
if (id_setVertexAttribArray_Ljava_lang_String_ILjava_nio_FloatBuffer_ == IntPtr.Zero)
id_setVertexAttribArray_Ljava_lang_String_ILjava_nio_FloatBuffer_ = JNIEnv.GetMethodID (class_ref, "setVertexAttribArray", "(Ljava/lang/String;ILjava/nio/FloatBuffer;)V");
IntPtr native_p0 = JNIEnv.NewString (p0);
try {
JValue* __args = stackalloc JValue [3];
__args [0] = new JValue (native_p0);
__args [1] = new JValue (p1);
__args [2] = new JValue (p2);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_setVertexAttribArray_Ljava_lang_String_ILjava_nio_FloatBuffer_, __args);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setVertexAttribArray", "(Ljava/lang/String;ILjava/nio/FloatBuffer;)V"), __args);
} finally {
JNIEnv.DeleteLocalRef (native_p0);
}
}
static Delegate cb_useProgram;
#pragma warning disable 0169
static Delegate GetUseProgramHandler ()
{
if (cb_useProgram == null)
cb_useProgram = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_UseProgram);
return cb_useProgram;
}
static void n_UseProgram (IntPtr jnienv, IntPtr native__this)
{
global::Org.Webrtc.GlShader __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.GlShader> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.UseProgram ();
}
#pragma warning restore 0169
static IntPtr id_useProgram;
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='GlShader']/method[@name='useProgram' and count(parameter)=0]"
[Register ("useProgram", "()V", "GetUseProgramHandler")]
public virtual unsafe void UseProgram ()
{
if (id_useProgram == IntPtr.Zero)
id_useProgram = JNIEnv.GetMethodID (class_ref, "useProgram", "()V");
try {
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_useProgram);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "useProgram", "()V"));
} finally {
}
}
}
}
| |
using System.IO;
using System.Xml.Linq;
using Signum.Engine.Chart;
using Signum.Entities.Basics;
using Signum.Entities.Chart;
using Signum.Entities.Dashboard;
using Signum.Entities.Reflection;
using Signum.Utilities.Reflection;
using Signum.Entities.UserAssets;
using Signum.Entities.UserQueries;
using Signum.Engine.Authorization;
using Signum.Entities.Authorization;
using Signum.Entities.Mailing;
using Signum.Engine.Mailing;
using Signum.Entities.Workflow;
using Signum.Engine.Workflow;
namespace Signum.Engine.UserAssets;
public static class UserAssetsExporter
{
public static Func<XDocument, XDocument>? PreExport = null;
class ToXmlContext : IToXmlContext
{
public Dictionary<Guid, XElement> elements = new Dictionary<Guid, XElement>();
public Guid Include(IUserAssetEntity content)
{
elements.GetOrCreate(content.Guid, () => content.ToXml(this));
return content.Guid;
}
public Guid Include(Lite<IUserAssetEntity> content)
{
return this.Include(content.RetrieveAndRemember());
}
public string TypeToName(Lite<TypeEntity> type)
{
return TypeLogic.GetCleanName(TypeLogic.EntityToType.GetOrThrow(type.RetrieveAndRemember()));
}
public string TypeToName(TypeEntity type)
{
return TypeLogic.GetCleanName(TypeLogic.EntityToType.GetOrThrow(type));
}
public string QueryToName(Lite<QueryEntity> query)
{
return query.RetrieveAndRemember().Key;
}
public string PermissionToName(Lite<PermissionSymbol> symbol)
{
return symbol.RetrieveAndRemember().Key;
}
public XElement GetFullWorkflowElement(WorkflowEntity workflow)
{
var wie = new WorkflowImportExport(workflow);
return wie.ToXml(this);
}
}
public static byte[] ToXml(params IUserAssetEntity[] entities)
{
ToXmlContext ctx = new ToXmlContext();
foreach (var e in entities)
ctx.Include(e);
XDocument doc = new XDocument(
new XDeclaration("1.0", "UTF8", "yes"),
new XElement("Entities",
ctx.elements.Values));
if(PreExport!=null)
doc=PreExport(doc);
return new MemoryStream().Using(s => { doc.Save(s); return s.ToArray(); });
}
}
public static class UserAssetsImporter
{
public static Dictionary<string, Type> UserAssetNames = new Dictionary<string, Type>();
public static Polymorphic<Action<Entity>> SaveEntity = new Polymorphic<Action<Entity>>();
public static Dictionary<string, Type> PartNames = new Dictionary<string, Type>();
public static Func<XDocument, XDocument>? PreImport = null;
class PreviewContext : IFromXmlContext
{
public Dictionary<Guid, IUserAssetEntity> entities = new Dictionary<Guid, IUserAssetEntity>();
public Dictionary<Guid, XElement> elements;
public Dictionary<Guid, ModelEntity?> customResolutionModel = new Dictionary<Guid, ModelEntity?>();
public Dictionary<Guid, UserAssetPreviewLineEmbedded> previews = new Dictionary<Guid, UserAssetPreviewLineEmbedded>();
public bool IsPreview => true;
public PreviewContext(XDocument doc)
{
elements = doc.Element("Entities")!.Elements().ToDictionary(a => Guid.Parse(a.Attribute("Guid")!.Value));
}
public QueryEntity GetQuery(string queryKey)
{
var qn = QueryLogic.ToQueryName(queryKey);
return QueryLogic.GetQueryEntity(qn);
}
QueryEntity? IFromXmlContext.TryGetQuery(string queryKey)
{
var qn = QueryLogic.TryToQueryName(queryKey);
if (qn == null)
return null;
return QueryLogic.GetQueryEntity(qn);
}
public IUserAssetEntity GetEntity(Guid guid)
{
return entities.GetOrCreate(guid, () =>
{
var element = elements.GetOrThrow(guid);
Type type = UserAssetNames.GetOrThrow(element.Name.ToString());
var entity = giRetrieveOrCreate.GetInvoker(type)(guid);
entity.FromXml(element, this);
previews.Add(guid, new UserAssetPreviewLineEmbedded
{
Text = entity.ToString()!,
Type = entity.GetType().ToTypeEntity(),
Guid = guid,
Action = entity.IsNew ? EntityAction.New :
customResolutionModel.ContainsKey(entity.Guid) ? EntityAction.Different :
GraphExplorer.FromRootVirtual((Entity)entity).Any(a => a.Modified != ModifiedState.Clean) ? EntityAction.Different :
EntityAction.Identical,
CustomResolution = customResolutionModel.TryGetCN(entity.Guid),
});
return entity;
});
}
public Lite<TypeEntity> NameToType(string cleanName)
{
return TypeLogic.TypeToEntity.GetOrThrow(TypeLogic.GetType(cleanName)).ToLite();
}
public IPartEntity GetPart(IPartEntity old, XElement element)
{
Type type = PartNames.GetOrThrow(element.Name.ToString());
var part = old != null && old.GetType() == type ? old : (IPartEntity)Activator.CreateInstance(type)!;
part.FromXml(element, this);
return part;
}
public TypeEntity GetType(string cleanName)
{
return TypeLogic.GetType(cleanName).ToTypeEntity();
}
public Lite<TypeEntity> GetTypeLite(string cleanName)
{
return TypeLogic.GetType(cleanName).ToTypeEntity().ToLite();
}
public ChartScriptSymbol ChartScript(string chartScriptName)
{
return ChartScriptLogic.Scripts.Keys.SingleEx(cs => cs.Key == chartScriptName || cs.Key.After(".") == chartScriptName);
}
public QueryDescription GetQueryDescription(QueryEntity Query)
{
return QueryLogic.Queries.QueryDescription(QueryLogic.QueryNames.GetOrThrow(Query.Key));
}
public PermissionSymbol? TryPermission(string permissionKey)
{
return SymbolLogic<PermissionSymbol>.TryToSymbol(permissionKey);
}
public EmailModelEntity GetEmailModel(string fullClassName)
{
return EmailModelLogic.GetEmailModelEntity(fullClassName);
}
public CultureInfoEntity GetCultureInfoEntity(string cultureName)
{
return CultureInfoLogic.GetCultureInfoEntity(cultureName);
}
public void SetFullWorkflowElement(WorkflowEntity workflow, XElement element)
{
var wie = new WorkflowImportExport(workflow);
wie.FromXml(element, this);
if (wie.HasChanges)
{
if (wie.ReplacementModel != null)
{
wie.ReplacementModel.NewTasks = wie.Activities.Select(a => new NewTasksEmbedded
{
BpmnId = a.BpmnElementId,
Name = a.GetName()!,
SubWorkflow = (a as WorkflowActivityEntity)?.SubWorkflow?.Workflow.ToLite(),
}).ToMList();
}
this.customResolutionModel.Add(Guid.Parse(element.Attribute("Guid")!.Value), wie.ReplacementModel);
}
}
}
public static UserAssetPreviewModel Preview(byte[] doc)
{
XDocument document = new MemoryStream(doc).Using(XDocument.Load);
if (PreImport != null)
document = PreImport(document);
PreviewContext ctx = new PreviewContext(document);
foreach (var item in ctx.elements)
ctx.GetEntity(item.Key);
return new UserAssetPreviewModel { Lines = ctx.previews.Values.ToMList() };
}
class ImporterContext : IFromXmlContext
{
Dictionary<Guid, bool> overrideEntity;
Dictionary<Guid, IUserAssetEntity> entities = new Dictionary<Guid, IUserAssetEntity>();
Dictionary<Guid, ModelEntity?> customResolutionModel = new Dictionary<Guid, ModelEntity?>();
public List<IPartEntity> toRemove = new List<IPartEntity>();
public Dictionary<Guid, XElement> elements;
public bool IsPreview => false;
public ImporterContext(XDocument doc, Dictionary<Guid, bool> overrideEntity, Dictionary<Guid, ModelEntity?> customResolution)
{
this.overrideEntity = overrideEntity;
this.customResolutionModel = customResolution;
elements = doc.Element("Entities")!.Elements().ToDictionary(a => Guid.Parse(a.Attribute("Guid")!.Value));
}
public TypeEntity GetType(string cleanName)
{
return TypeLogic.GetType(cleanName).ToTypeEntity();
}
QueryEntity IFromXmlContext.GetQuery(string queryKey)
{
var qn = QueryLogic.ToQueryName(queryKey);
return QueryLogic.GetQueryEntity(qn);
}
QueryEntity? IFromXmlContext.TryGetQuery(string queryKey)
{
var qn = QueryLogic.TryToQueryName(queryKey);
if (qn == null)
return null;
return QueryLogic.GetQueryEntity(qn);
}
public IUserAssetEntity GetEntity(Guid guid)
{
return entities.GetOrCreate(guid, () =>
{
var element = elements.GetOrThrow(guid);
Type type = UserAssetNames.GetOrThrow(element.Name.ToString());
var entity = giRetrieveOrCreate.GetInvoker(type)(guid);
if (entity.IsNew || overrideEntity.ContainsKey(guid))
{
entity.FromXml(element, this);
SaveEntity.Invoke((Entity)entity);
}
return entity;
});
}
public Lite<TypeEntity> NameToType(string cleanName)
{
return TypeLogic.TypeToEntity.GetOrThrow(TypeLogic.GetType(cleanName)).ToLite();
}
public EmailModelEntity GetEmailModel(string fullClassName)
{
return EmailModelLogic.GetEmailModelEntity(fullClassName);
}
public IPartEntity GetPart(IPartEntity old, XElement element)
{
Type type = PartNames.GetOrThrow(element.Name.ToString());
var part = old != null && old.GetType() == type ? old : (IPartEntity)Activator.CreateInstance(type)!;
part.FromXml(element, this);
if (old != null && part != old)
toRemove.Add(old);
return part;
}
public Lite<TypeEntity> GetTypeLite(string cleanName)
{
return TypeLogic.GetType(cleanName).ToTypeEntity().ToLite();
}
public ChartScriptSymbol ChartScript(string chartScriptName)
{
return ChartScriptLogic.Scripts.Keys.SingleEx(cs => cs.Key == chartScriptName || cs.Key.After(".") == chartScriptName);
}
public QueryDescription GetQueryDescription(QueryEntity Query)
{
return QueryLogic.Queries.QueryDescription(QueryLogic.QueryNames.GetOrThrow(Query.Key));
}
public PermissionSymbol? TryPermission(string permissionKey)
{
return SymbolLogic<PermissionSymbol>.TryToSymbol(permissionKey);
}
public CultureInfoEntity GetCultureInfoEntity(string cultureName)
{
return CultureInfoLogic.GetCultureInfoEntity(cultureName);
}
public void SetFullWorkflowElement(WorkflowEntity workflow, XElement element)
{
var model = (WorkflowReplacementModel?)this.customResolutionModel.TryGetCN(Guid.Parse(element.Attribute("Guid")!.Value));
var wie = new WorkflowImportExport(workflow)
{
ReplacementModel = model
};
wie.FromXml(element, this);
}
}
public static void ImportConsole(string filePath)
{
var bytes = File.ReadAllBytes(filePath);
var preview = Preview(bytes);
foreach (var item in preview.Lines)
{
switch (item.Action)
{
case EntityAction.New: SafeConsole.WriteLineColor(ConsoleColor.Green, $"Create {item.Type} {item.Guid} {item.Text}"); break;
case EntityAction.Identical: SafeConsole.WriteLineColor(ConsoleColor.DarkGray, $"Identical {item.Type} {item.Guid} {item.Text}"); break;
case EntityAction.Different: SafeConsole.WriteLineColor(ConsoleColor.Yellow, $"Override {item.Type} {item.Guid} {item.Text}");
item.OverrideEntity = true;
break;
}
}
if (!preview.Lines.Any(a => a.OverrideEntity) || SafeConsole.Ask("Override all?"))
{
Import(bytes, preview);
SafeConsole.WriteLineColor(ConsoleColor.Green, $"Imported Succesfully");
}
}
public static void ImportAll(string filePath) => ImportAll(File.ReadAllBytes(filePath));
public static void ImportAll(byte[] document)
{
Import(document, Preview(document));
}
public static void Import(byte[] document, UserAssetPreviewModel preview)
{
using (var tr = new Transaction())
{
var doc = new MemoryStream(document).Using(XDocument.Load);
if (PreImport != null)
doc = PreImport(doc);
ImporterContext importer = new ImporterContext(doc,
preview.Lines
.Where(a => a.Action == EntityAction.Different)
.ToDictionary(a => a.Guid, a => a.OverrideEntity),
preview.Lines
.Where(a => a.Action == EntityAction.Different)
.ToDictionary(a => a.Guid, a => a.CustomResolution));
foreach (var item in importer.elements)
importer.GetEntity(item.Key);
Database.DeleteList(importer.toRemove);
tr.Commit();
}
}
static readonly GenericInvoker<Func<Guid, IUserAssetEntity>> giRetrieveOrCreate = new(
guid => RetrieveOrCreate<UserQueryEntity>(guid));
static T RetrieveOrCreate<T>(Guid guid) where T : Entity, IUserAssetEntity, new()
{
var result = Database.Query<T>().SingleOrDefaultEx(a => a.Guid == guid);
if (result != null)
return result;
return new T { Guid = guid };
}
public static void Register<T>(string userAssetName, ExecuteSymbol<T> saveOperation) where T : Entity, IUserAssetEntity =>
Register<T>(userAssetName, e => e.Execute(saveOperation));
public static void Register<T>(string userAssetName, Action<T> saveEntity) where T : Entity, IUserAssetEntity
{
PermissionAuthLogic.RegisterPermissions(UserAssetPermission.UserAssetsToXML);
UserAssetNames.Add(userAssetName, typeof(T));
UserAssetsImporter.SaveEntity.Register(saveEntity);
}
}
| |
// 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 MultiplyAddAdjacentInt32()
{
var test = new SimpleBinaryOpTest__MultiplyAddAdjacentInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.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 (Sse2.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();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.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 class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__MultiplyAddAdjacentInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int16> _fld1;
public Vector128<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__MultiplyAddAdjacentInt32 testClass)
{
var result = Sse2.MultiplyAddAdjacent(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__MultiplyAddAdjacentInt32 testClass)
{
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int16>* pFld2 = &_fld2)
{
var result = Sse2.MultiplyAddAdjacent(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector128<Int16> _clsVar1;
private static Vector128<Int16> _clsVar2;
private Vector128<Int16> _fld1;
private Vector128<Int16> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__MultiplyAddAdjacentInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
}
public SimpleBinaryOpTest__MultiplyAddAdjacentInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.MultiplyAddAdjacent(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.MultiplyAddAdjacent(
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.MultiplyAddAdjacent(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.MultiplyAddAdjacent), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.MultiplyAddAdjacent), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.MultiplyAddAdjacent), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.MultiplyAddAdjacent(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int16>* pClsVar2 = &_clsVar2)
{
var result = Sse2.MultiplyAddAdjacent(
Sse2.LoadVector128((Int16*)(pClsVar1)),
Sse2.LoadVector128((Int16*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr);
var result = Sse2.MultiplyAddAdjacent(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse2.MultiplyAddAdjacent(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse2.MultiplyAddAdjacent(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__MultiplyAddAdjacentInt32();
var result = Sse2.MultiplyAddAdjacent(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__MultiplyAddAdjacentInt32();
fixed (Vector128<Int16>* pFld1 = &test._fld1)
fixed (Vector128<Int16>* pFld2 = &test._fld2)
{
var result = Sse2.MultiplyAddAdjacent(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.MultiplyAddAdjacent(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int16>* pFld2 = &_fld2)
{
var result = Sse2.MultiplyAddAdjacent(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.MultiplyAddAdjacent(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.MultiplyAddAdjacent(
Sse2.LoadVector128((Int16*)(&test._fld1)),
Sse2.LoadVector128((Int16*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != Math.Clamp(((right[1] * left[1]) + (right[0] * left[0])), int.MinValue, int.MaxValue))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != Math.Clamp(((right[(i * 2) + 1] * left[(i * 2) + 1]) + (right[i * 2] * left[i * 2])), int.MinValue, int.MaxValue))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.MultiplyAddAdjacent)}<Int32>(Vector128<Int16>, Vector128<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// This file contains two ICryptoTransforms: ToBase64Transform and FromBase64Transform
// they may be attached to a CryptoStream in either read or write mode
using System.Text;
namespace System.Security.Cryptography
{
public enum FromBase64TransformMode
{
IgnoreWhiteSpaces = 0,
DoNotIgnoreWhiteSpaces = 1,
}
public class ToBase64Transform : ICryptoTransform
{
// converting to Base64 takes 3 bytes input and generates 4 bytes output
public int InputBlockSize => 3;
public int OutputBlockSize => 4;
public bool CanTransformMultipleBlocks => false;
public virtual bool CanReuseTransform => true;
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
ValidateTransformBlock(inputBuffer, inputOffset, inputCount);
// For now, only convert 3 bytes to 4
byte[] tempBytes = ConvertToBase64(inputBuffer, inputOffset, 3);
Buffer.BlockCopy(tempBytes, 0, outputBuffer, outputOffset, tempBytes.Length);
return tempBytes.Length;
}
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
ValidateTransformBlock(inputBuffer, inputOffset, inputCount);
// Convert.ToBase64CharArray already does padding, so all we have to check is that
// the inputCount wasn't 0
if (inputCount == 0)
{
return Array.Empty<byte>();
}
// Again, for now only a block at a time
return ConvertToBase64(inputBuffer, inputOffset, inputCount);
}
private byte[] ConvertToBase64(byte[] inputBuffer, int inputOffset, int inputCount)
{
char[] temp = new char[4];
Convert.ToBase64CharArray(inputBuffer, inputOffset, inputCount, temp, 0);
byte[] tempBytes = Encoding.ASCII.GetBytes(temp);
if (tempBytes.Length != 4)
throw new CryptographicException(SR.Cryptography_SSE_InvalidDataSize);
return tempBytes;
}
private static void ValidateTransformBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
if (inputBuffer == null) throw new ArgumentNullException(nameof(inputBuffer));
if (inputOffset < 0) throw new ArgumentOutOfRangeException(nameof(inputOffset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (inputCount < 0 || (inputCount > inputBuffer.Length)) throw new ArgumentException(SR.Argument_InvalidValue);
if ((inputBuffer.Length - inputCount) < inputOffset) throw new ArgumentException(SR.Argument_InvalidOffLen);
}
// Must implement IDisposable, but in this case there's nothing to do.
public void Dispose()
{
Clear();
}
public void Clear()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) { }
~ToBase64Transform()
{
// A finalizer is not necessary here, however since we shipped a finalizer that called
// Dispose(false) in desktop v2.0, we need to keep it in case any existing code had subclassed
// this transform and expects to have a base class finalizer call its dispose method.
Dispose(false);
}
}
public class FromBase64Transform : ICryptoTransform
{
private byte[] _inputBuffer = new byte[4];
private int _inputIndex;
private FromBase64TransformMode _whitespaces;
public FromBase64Transform() : this(FromBase64TransformMode.IgnoreWhiteSpaces) { }
public FromBase64Transform(FromBase64TransformMode whitespaces)
{
_whitespaces = whitespaces;
_inputIndex = 0;
}
// Converting from Base64 generates 3 bytes output from each 4 bytes input block
public int InputBlockSize => 1;
public int OutputBlockSize => 3;
public bool CanTransformMultipleBlocks => false;
public virtual bool CanReuseTransform => true;
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
ValidateTransformBlock(inputBuffer, inputOffset, inputCount);
if (_inputBuffer == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic);
int effectiveCount;
byte[] temp = GetTempBuffer(inputBuffer, inputOffset, inputCount, out effectiveCount);
if (effectiveCount + _inputIndex < 4)
{
Buffer.BlockCopy(temp, 0, _inputBuffer, _inputIndex, effectiveCount);
_inputIndex += effectiveCount;
return 0;
}
byte[] result = ConvertFromBase64(temp, effectiveCount);
Buffer.BlockCopy(result, 0, outputBuffer, outputOffset, result.Length);
return result.Length;
}
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
ValidateTransformBlock(inputBuffer, inputOffset, inputCount);
if (_inputBuffer == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic);
int effectiveCount;
byte[] temp = GetTempBuffer(inputBuffer, inputOffset, inputCount, out effectiveCount);
if (effectiveCount + _inputIndex < 4)
{
Reset();
return Array.Empty<byte>();
}
byte[] result = ConvertFromBase64(temp, effectiveCount);
// reinitialize the transform
Reset();
return result;
}
private byte[] GetTempBuffer(byte[] inputBuffer, int inputOffset, int inputCount, out int effectiveCount)
{
byte[] temp;
if (_whitespaces == FromBase64TransformMode.IgnoreWhiteSpaces)
{
temp = DiscardWhiteSpaces(inputBuffer, inputOffset, inputCount);
effectiveCount = temp.Length;
}
else
{
temp = new byte[inputCount];
Buffer.BlockCopy(inputBuffer, inputOffset, temp, 0, inputCount);
effectiveCount = inputCount;
}
return temp;
}
private byte[] ConvertFromBase64(byte[] temp, int effectiveCount)
{
// Get the number of 4 bytes blocks to transform
int numBlocks = (effectiveCount + _inputIndex) / 4;
byte[] transformBuffer = new byte[_inputIndex + effectiveCount];
Buffer.BlockCopy(_inputBuffer, 0, transformBuffer, 0, _inputIndex);
Buffer.BlockCopy(temp, 0, transformBuffer, _inputIndex, effectiveCount);
_inputIndex = (effectiveCount + _inputIndex) % 4;
Buffer.BlockCopy(temp, effectiveCount - _inputIndex, _inputBuffer, 0, _inputIndex);
char[] tempChar = Encoding.ASCII.GetChars(transformBuffer, 0, 4 * numBlocks);
byte[] tempBytes = Convert.FromBase64CharArray(tempChar, 0, 4 * numBlocks);
return tempBytes;
}
private byte[] DiscardWhiteSpaces(byte[] inputBuffer, int inputOffset, int inputCount)
{
int i, iCount = 0;
for (i = 0; i < inputCount; i++)
{
if (char.IsWhiteSpace((char)inputBuffer[inputOffset + i])) iCount++;
}
// If there's nothing to do, leave early
if (iCount == 0 && inputOffset == 0)
{
return inputBuffer;
}
byte[] rgbOut = new byte[inputCount - iCount];
iCount = 0;
for (i = 0; i < inputCount; i++)
{
if (!char.IsWhiteSpace((char)inputBuffer[inputOffset + i]))
{
rgbOut[iCount++] = inputBuffer[inputOffset + i];
}
}
return rgbOut;
}
private static void ValidateTransformBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
if (inputBuffer == null) throw new ArgumentNullException(nameof(inputBuffer));
if (inputOffset < 0) throw new ArgumentOutOfRangeException(nameof(inputOffset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (inputCount < 0 || (inputCount > inputBuffer.Length)) throw new ArgumentException(SR.Argument_InvalidValue);
if ((inputBuffer.Length - inputCount) < inputOffset) throw new ArgumentException(SR.Argument_InvalidOffLen);
}
// must implement IDisposable, which in this case means clearing the input buffer
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Reset the state of the transform so it can be used again
private void Reset()
{
_inputIndex = 0;
}
public void Clear()
{
Dispose();
}
protected virtual void Dispose(bool disposing)
{
// we always want to clear the input buffer
if (disposing)
{
if (_inputBuffer != null)
Array.Clear(_inputBuffer, 0, _inputBuffer.Length);
_inputBuffer = null;
_inputIndex = 0;
}
}
~FromBase64Transform()
{
Dispose(false);
}
}
}
| |
// 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.EssentialContacts.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 GeneratedEssentialContactsServiceClientSnippets
{
/// <summary>Snippet for CreateContact</summary>
public void CreateContactRequestObject()
{
// Snippet: CreateContact(CreateContactRequest, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
CreateContactRequest request = new CreateContactRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
Contact = new Contact(),
};
// Make the request
Contact response = essentialContactsServiceClient.CreateContact(request);
// End snippet
}
/// <summary>Snippet for CreateContactAsync</summary>
public async Task CreateContactRequestObjectAsync()
{
// Snippet: CreateContactAsync(CreateContactRequest, CallSettings)
// Additional: CreateContactAsync(CreateContactRequest, CancellationToken)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = await EssentialContactsServiceClient.CreateAsync();
// Initialize request argument(s)
CreateContactRequest request = new CreateContactRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
Contact = new Contact(),
};
// Make the request
Contact response = await essentialContactsServiceClient.CreateContactAsync(request);
// End snippet
}
/// <summary>Snippet for CreateContact</summary>
public void CreateContact()
{
// Snippet: CreateContact(string, Contact, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
Contact contact = new Contact();
// Make the request
Contact response = essentialContactsServiceClient.CreateContact(parent, contact);
// End snippet
}
/// <summary>Snippet for CreateContactAsync</summary>
public async Task CreateContactAsync()
{
// Snippet: CreateContactAsync(string, Contact, CallSettings)
// Additional: CreateContactAsync(string, Contact, CancellationToken)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = await EssentialContactsServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
Contact contact = new Contact();
// Make the request
Contact response = await essentialContactsServiceClient.CreateContactAsync(parent, contact);
// End snippet
}
/// <summary>Snippet for CreateContact</summary>
public void CreateContactResourceNames1()
{
// Snippet: CreateContact(ProjectName, Contact, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
Contact contact = new Contact();
// Make the request
Contact response = essentialContactsServiceClient.CreateContact(parent, contact);
// End snippet
}
/// <summary>Snippet for CreateContactAsync</summary>
public async Task CreateContactResourceNames1Async()
{
// Snippet: CreateContactAsync(ProjectName, Contact, CallSettings)
// Additional: CreateContactAsync(ProjectName, Contact, CancellationToken)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = await EssentialContactsServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
Contact contact = new Contact();
// Make the request
Contact response = await essentialContactsServiceClient.CreateContactAsync(parent, contact);
// End snippet
}
/// <summary>Snippet for CreateContact</summary>
public void CreateContactResourceNames2()
{
// Snippet: CreateContact(FolderName, Contact, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
FolderName parent = FolderName.FromFolder("[FOLDER]");
Contact contact = new Contact();
// Make the request
Contact response = essentialContactsServiceClient.CreateContact(parent, contact);
// End snippet
}
/// <summary>Snippet for CreateContactAsync</summary>
public async Task CreateContactResourceNames2Async()
{
// Snippet: CreateContactAsync(FolderName, Contact, CallSettings)
// Additional: CreateContactAsync(FolderName, Contact, CancellationToken)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = await EssentialContactsServiceClient.CreateAsync();
// Initialize request argument(s)
FolderName parent = FolderName.FromFolder("[FOLDER]");
Contact contact = new Contact();
// Make the request
Contact response = await essentialContactsServiceClient.CreateContactAsync(parent, contact);
// End snippet
}
/// <summary>Snippet for CreateContact</summary>
public void CreateContactResourceNames3()
{
// Snippet: CreateContact(OrganizationName, Contact, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
OrganizationName parent = OrganizationName.FromOrganization("[ORGANIZATION]");
Contact contact = new Contact();
// Make the request
Contact response = essentialContactsServiceClient.CreateContact(parent, contact);
// End snippet
}
/// <summary>Snippet for CreateContactAsync</summary>
public async Task CreateContactResourceNames3Async()
{
// Snippet: CreateContactAsync(OrganizationName, Contact, CallSettings)
// Additional: CreateContactAsync(OrganizationName, Contact, CancellationToken)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = await EssentialContactsServiceClient.CreateAsync();
// Initialize request argument(s)
OrganizationName parent = OrganizationName.FromOrganization("[ORGANIZATION]");
Contact contact = new Contact();
// Make the request
Contact response = await essentialContactsServiceClient.CreateContactAsync(parent, contact);
// End snippet
}
/// <summary>Snippet for UpdateContact</summary>
public void UpdateContactRequestObject()
{
// Snippet: UpdateContact(UpdateContactRequest, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
UpdateContactRequest request = new UpdateContactRequest
{
Contact = new Contact(),
UpdateMask = new FieldMask(),
};
// Make the request
Contact response = essentialContactsServiceClient.UpdateContact(request);
// End snippet
}
/// <summary>Snippet for UpdateContactAsync</summary>
public async Task UpdateContactRequestObjectAsync()
{
// Snippet: UpdateContactAsync(UpdateContactRequest, CallSettings)
// Additional: UpdateContactAsync(UpdateContactRequest, CancellationToken)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = await EssentialContactsServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateContactRequest request = new UpdateContactRequest
{
Contact = new Contact(),
UpdateMask = new FieldMask(),
};
// Make the request
Contact response = await essentialContactsServiceClient.UpdateContactAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateContact</summary>
public void UpdateContact()
{
// Snippet: UpdateContact(Contact, FieldMask, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
Contact contact = new Contact();
FieldMask updateMask = new FieldMask();
// Make the request
Contact response = essentialContactsServiceClient.UpdateContact(contact, updateMask);
// End snippet
}
/// <summary>Snippet for UpdateContactAsync</summary>
public async Task UpdateContactAsync()
{
// Snippet: UpdateContactAsync(Contact, FieldMask, CallSettings)
// Additional: UpdateContactAsync(Contact, FieldMask, CancellationToken)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = await EssentialContactsServiceClient.CreateAsync();
// Initialize request argument(s)
Contact contact = new Contact();
FieldMask updateMask = new FieldMask();
// Make the request
Contact response = await essentialContactsServiceClient.UpdateContactAsync(contact, updateMask);
// End snippet
}
/// <summary>Snippet for ListContacts</summary>
public void ListContactsRequestObject()
{
// Snippet: ListContacts(ListContactsRequest, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
ListContactsRequest request = new ListContactsRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
};
// Make the request
PagedEnumerable<ListContactsResponse, Contact> response = essentialContactsServiceClient.ListContacts(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Contact 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 (ListContactsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Contact 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<Contact> 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 (Contact 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 ListContactsAsync</summary>
public async Task ListContactsRequestObjectAsync()
{
// Snippet: ListContactsAsync(ListContactsRequest, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = await EssentialContactsServiceClient.CreateAsync();
// Initialize request argument(s)
ListContactsRequest request = new ListContactsRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
};
// Make the request
PagedAsyncEnumerable<ListContactsResponse, Contact> response = essentialContactsServiceClient.ListContactsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Contact 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((ListContactsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Contact 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<Contact> 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 (Contact 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 ListContacts</summary>
public void ListContacts()
{
// Snippet: ListContacts(string, string, int?, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
// Make the request
PagedEnumerable<ListContactsResponse, Contact> response = essentialContactsServiceClient.ListContacts(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Contact 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 (ListContactsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Contact 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<Contact> 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 (Contact 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 ListContactsAsync</summary>
public async Task ListContactsAsync()
{
// Snippet: ListContactsAsync(string, string, int?, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = await EssentialContactsServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
// Make the request
PagedAsyncEnumerable<ListContactsResponse, Contact> response = essentialContactsServiceClient.ListContactsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Contact 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((ListContactsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Contact 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<Contact> 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 (Contact 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 ListContacts</summary>
public void ListContactsResourceNames1()
{
// Snippet: ListContacts(ProjectName, string, int?, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
// Make the request
PagedEnumerable<ListContactsResponse, Contact> response = essentialContactsServiceClient.ListContacts(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Contact 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 (ListContactsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Contact 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<Contact> 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 (Contact 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 ListContactsAsync</summary>
public async Task ListContactsResourceNames1Async()
{
// Snippet: ListContactsAsync(ProjectName, string, int?, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = await EssentialContactsServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
// Make the request
PagedAsyncEnumerable<ListContactsResponse, Contact> response = essentialContactsServiceClient.ListContactsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Contact 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((ListContactsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Contact 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<Contact> 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 (Contact 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 ListContacts</summary>
public void ListContactsResourceNames2()
{
// Snippet: ListContacts(FolderName, string, int?, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
FolderName parent = FolderName.FromFolder("[FOLDER]");
// Make the request
PagedEnumerable<ListContactsResponse, Contact> response = essentialContactsServiceClient.ListContacts(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Contact 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 (ListContactsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Contact 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<Contact> 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 (Contact 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 ListContactsAsync</summary>
public async Task ListContactsResourceNames2Async()
{
// Snippet: ListContactsAsync(FolderName, string, int?, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = await EssentialContactsServiceClient.CreateAsync();
// Initialize request argument(s)
FolderName parent = FolderName.FromFolder("[FOLDER]");
// Make the request
PagedAsyncEnumerable<ListContactsResponse, Contact> response = essentialContactsServiceClient.ListContactsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Contact 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((ListContactsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Contact 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<Contact> 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 (Contact 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 ListContacts</summary>
public void ListContactsResourceNames3()
{
// Snippet: ListContacts(OrganizationName, string, int?, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
OrganizationName parent = OrganizationName.FromOrganization("[ORGANIZATION]");
// Make the request
PagedEnumerable<ListContactsResponse, Contact> response = essentialContactsServiceClient.ListContacts(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Contact 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 (ListContactsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Contact 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<Contact> 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 (Contact 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 ListContactsAsync</summary>
public async Task ListContactsResourceNames3Async()
{
// Snippet: ListContactsAsync(OrganizationName, string, int?, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = await EssentialContactsServiceClient.CreateAsync();
// Initialize request argument(s)
OrganizationName parent = OrganizationName.FromOrganization("[ORGANIZATION]");
// Make the request
PagedAsyncEnumerable<ListContactsResponse, Contact> response = essentialContactsServiceClient.ListContactsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Contact 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((ListContactsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Contact 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<Contact> 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 (Contact 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 GetContact</summary>
public void GetContactRequestObject()
{
// Snippet: GetContact(GetContactRequest, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
GetContactRequest request = new GetContactRequest
{
ContactName = ContactName.FromProjectContact("[PROJECT]", "[CONTACT]"),
};
// Make the request
Contact response = essentialContactsServiceClient.GetContact(request);
// End snippet
}
/// <summary>Snippet for GetContactAsync</summary>
public async Task GetContactRequestObjectAsync()
{
// Snippet: GetContactAsync(GetContactRequest, CallSettings)
// Additional: GetContactAsync(GetContactRequest, CancellationToken)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = await EssentialContactsServiceClient.CreateAsync();
// Initialize request argument(s)
GetContactRequest request = new GetContactRequest
{
ContactName = ContactName.FromProjectContact("[PROJECT]", "[CONTACT]"),
};
// Make the request
Contact response = await essentialContactsServiceClient.GetContactAsync(request);
// End snippet
}
/// <summary>Snippet for GetContact</summary>
public void GetContact()
{
// Snippet: GetContact(string, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/contacts/[CONTACT]";
// Make the request
Contact response = essentialContactsServiceClient.GetContact(name);
// End snippet
}
/// <summary>Snippet for GetContactAsync</summary>
public async Task GetContactAsync()
{
// Snippet: GetContactAsync(string, CallSettings)
// Additional: GetContactAsync(string, CancellationToken)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = await EssentialContactsServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/contacts/[CONTACT]";
// Make the request
Contact response = await essentialContactsServiceClient.GetContactAsync(name);
// End snippet
}
/// <summary>Snippet for GetContact</summary>
public void GetContactResourceNames()
{
// Snippet: GetContact(ContactName, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
ContactName name = ContactName.FromProjectContact("[PROJECT]", "[CONTACT]");
// Make the request
Contact response = essentialContactsServiceClient.GetContact(name);
// End snippet
}
/// <summary>Snippet for GetContactAsync</summary>
public async Task GetContactResourceNamesAsync()
{
// Snippet: GetContactAsync(ContactName, CallSettings)
// Additional: GetContactAsync(ContactName, CancellationToken)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = await EssentialContactsServiceClient.CreateAsync();
// Initialize request argument(s)
ContactName name = ContactName.FromProjectContact("[PROJECT]", "[CONTACT]");
// Make the request
Contact response = await essentialContactsServiceClient.GetContactAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteContact</summary>
public void DeleteContactRequestObject()
{
// Snippet: DeleteContact(DeleteContactRequest, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
DeleteContactRequest request = new DeleteContactRequest
{
ContactName = ContactName.FromProjectContact("[PROJECT]", "[CONTACT]"),
};
// Make the request
essentialContactsServiceClient.DeleteContact(request);
// End snippet
}
/// <summary>Snippet for DeleteContactAsync</summary>
public async Task DeleteContactRequestObjectAsync()
{
// Snippet: DeleteContactAsync(DeleteContactRequest, CallSettings)
// Additional: DeleteContactAsync(DeleteContactRequest, CancellationToken)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = await EssentialContactsServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteContactRequest request = new DeleteContactRequest
{
ContactName = ContactName.FromProjectContact("[PROJECT]", "[CONTACT]"),
};
// Make the request
await essentialContactsServiceClient.DeleteContactAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteContact</summary>
public void DeleteContact()
{
// Snippet: DeleteContact(string, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/contacts/[CONTACT]";
// Make the request
essentialContactsServiceClient.DeleteContact(name);
// End snippet
}
/// <summary>Snippet for DeleteContactAsync</summary>
public async Task DeleteContactAsync()
{
// Snippet: DeleteContactAsync(string, CallSettings)
// Additional: DeleteContactAsync(string, CancellationToken)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = await EssentialContactsServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/contacts/[CONTACT]";
// Make the request
await essentialContactsServiceClient.DeleteContactAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteContact</summary>
public void DeleteContactResourceNames()
{
// Snippet: DeleteContact(ContactName, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
ContactName name = ContactName.FromProjectContact("[PROJECT]", "[CONTACT]");
// Make the request
essentialContactsServiceClient.DeleteContact(name);
// End snippet
}
/// <summary>Snippet for DeleteContactAsync</summary>
public async Task DeleteContactResourceNamesAsync()
{
// Snippet: DeleteContactAsync(ContactName, CallSettings)
// Additional: DeleteContactAsync(ContactName, CancellationToken)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = await EssentialContactsServiceClient.CreateAsync();
// Initialize request argument(s)
ContactName name = ContactName.FromProjectContact("[PROJECT]", "[CONTACT]");
// Make the request
await essentialContactsServiceClient.DeleteContactAsync(name);
// End snippet
}
/// <summary>Snippet for ComputeContacts</summary>
public void ComputeContactsRequestObject()
{
// Snippet: ComputeContacts(ComputeContactsRequest, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
ComputeContactsRequest request = new ComputeContactsRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
NotificationCategories =
{
NotificationCategory.Unspecified,
},
};
// Make the request
PagedEnumerable<ComputeContactsResponse, Contact> response = essentialContactsServiceClient.ComputeContacts(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Contact 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 (ComputeContactsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Contact 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<Contact> 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 (Contact 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 ComputeContactsAsync</summary>
public async Task ComputeContactsRequestObjectAsync()
{
// Snippet: ComputeContactsAsync(ComputeContactsRequest, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = await EssentialContactsServiceClient.CreateAsync();
// Initialize request argument(s)
ComputeContactsRequest request = new ComputeContactsRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
NotificationCategories =
{
NotificationCategory.Unspecified,
},
};
// Make the request
PagedAsyncEnumerable<ComputeContactsResponse, Contact> response = essentialContactsServiceClient.ComputeContactsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Contact 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((ComputeContactsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Contact 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<Contact> 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 (Contact 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 SendTestMessage</summary>
public void SendTestMessageRequestObject()
{
// Snippet: SendTestMessage(SendTestMessageRequest, CallSettings)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = EssentialContactsServiceClient.Create();
// Initialize request argument(s)
SendTestMessageRequest request = new SendTestMessageRequest
{
ContactsAsContactNames =
{
ContactName.FromProjectContact("[PROJECT]", "[CONTACT]"),
},
ResourceAsProjectName = ProjectName.FromProject("[PROJECT]"),
NotificationCategory = NotificationCategory.Unspecified,
};
// Make the request
essentialContactsServiceClient.SendTestMessage(request);
// End snippet
}
/// <summary>Snippet for SendTestMessageAsync</summary>
public async Task SendTestMessageRequestObjectAsync()
{
// Snippet: SendTestMessageAsync(SendTestMessageRequest, CallSettings)
// Additional: SendTestMessageAsync(SendTestMessageRequest, CancellationToken)
// Create client
EssentialContactsServiceClient essentialContactsServiceClient = await EssentialContactsServiceClient.CreateAsync();
// Initialize request argument(s)
SendTestMessageRequest request = new SendTestMessageRequest
{
ContactsAsContactNames =
{
ContactName.FromProjectContact("[PROJECT]", "[CONTACT]"),
},
ResourceAsProjectName = ProjectName.FromProject("[PROJECT]"),
NotificationCategory = NotificationCategory.Unspecified,
};
// Make the request
await essentialContactsServiceClient.SendTestMessageAsync(request);
// End snippet
}
}
}
| |
using UnityEngine;
using UnityEngine.Serialization;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Fungus
{
/**
* Temp hidden object which lets us use the entire inspector window to inspect
* the block command list.
*/
public class BlockInspector : ScriptableObject
{
[FormerlySerializedAs("sequence")]
public Block block;
}
/**
* Custom editor for the temp hidden object.
*/
[CustomEditor (typeof(BlockInspector), true)]
public class BlockInspectorEditor : Editor
{
protected Vector2 blockScrollPos;
protected Vector2 commandScrollPos;
protected bool resize = false;
protected bool clamp = false;
protected float topPanelHeight = 50;
// Cache the block and command editors so we only create and destroy them
// when a different block / command is selected.
protected BlockEditor activeBlockEditor;
protected CommandEditor activeCommandEditor;
protected Command activeCommand; // Command currently being inspected
// Cached command editors to avoid creating / destroying editors more than necessary
// This list is static so persists between
protected static List<CommandEditor> cachedCommandEditors = new List<CommandEditor>();
protected void OnDestroy()
{
ClearEditors();
}
protected void OnEnable()
{
ClearEditors();
}
protected void OnDisable()
{
ClearEditors();
}
protected void ClearEditors()
{
foreach (CommandEditor commandEditor in cachedCommandEditors)
{
DestroyImmediate(commandEditor);
}
cachedCommandEditors.Clear();
activeCommandEditor = null;
}
public override void OnInspectorGUI ()
{
BlockInspector blockInspector = target as BlockInspector;
Block block = blockInspector.block;
if (block == null)
{
return;
}
Flowchart flowchart = block.GetFlowchart();
if (activeBlockEditor == null ||
block != activeBlockEditor.target)
{
DestroyImmediate(activeBlockEditor);
activeBlockEditor = Editor.CreateEditor(block) as BlockEditor;
}
activeBlockEditor.DrawBlockName(flowchart);
// Using a custom rect area to get the correct 5px indent for the scroll views
Rect blockRect = new Rect(5, topPanelHeight, Screen.width - 6, Screen.height - 70);
GUILayout.BeginArea(blockRect);
blockScrollPos = GUILayout.BeginScrollView(blockScrollPos, GUILayout.Height(flowchart.blockViewHeight));
activeBlockEditor.DrawBlockGUI(flowchart);
GUILayout.EndScrollView();
Command inspectCommand = null;
if (flowchart.selectedCommands.Count == 1)
{
inspectCommand = flowchart.selectedCommands[0];
}
if (Application.isPlaying &&
inspectCommand != null &&
inspectCommand.parentBlock != block)
{
GUILayout.EndArea();
Repaint();
return;
}
// Only change the activeCommand at the start of the GUI call sequence
if (Event.current.type == EventType.Layout)
{
activeCommand = inspectCommand;
}
DrawCommandUI(flowchart, inspectCommand);
}
public void DrawCommandUI(Flowchart flowchart, Command inspectCommand)
{
ResizeScrollView(flowchart);
GUILayout.Space(7);
activeBlockEditor.DrawButtonToolbar();
commandScrollPos = GUILayout.BeginScrollView(commandScrollPos);
if (inspectCommand != null)
{
if (activeCommandEditor == null ||
inspectCommand != activeCommandEditor.target)
{
// See if we have a cached version of the command editor already,
var editors = (from e in cachedCommandEditors where (e.target == inspectCommand) select e);
if (editors.Count() > 0)
{
// Use cached editor
activeCommandEditor = editors.First();
}
else
{
// No cached editor, so create a new one.
activeCommandEditor = Editor.CreateEditor(inspectCommand) as CommandEditor;
cachedCommandEditors.Add(activeCommandEditor);
}
}
if (activeCommandEditor != null)
{
activeCommandEditor.DrawCommandInspectorGUI();
}
}
GUILayout.EndScrollView();
GUILayout.EndArea();
// Draw the resize bar after everything else has finished drawing
// This is mainly to avoid incorrect indenting.
Rect resizeRect = new Rect(0, topPanelHeight + flowchart.blockViewHeight + 1, Screen.width, 4f);
GUI.color = new Color(0.64f, 0.64f, 0.64f);
GUI.DrawTexture(resizeRect, EditorGUIUtility.whiteTexture);
resizeRect.height = 1;
GUI.color = new Color32(132, 132, 132, 255);
GUI.DrawTexture(resizeRect, EditorGUIUtility.whiteTexture);
resizeRect.y += 3;
GUI.DrawTexture(resizeRect, EditorGUIUtility.whiteTexture);
GUI.color = Color.white;
Repaint();
}
private void ResizeScrollView(Flowchart flowchart)
{
Rect cursorChangeRect = new Rect(0, flowchart.blockViewHeight + 1, Screen.width, 4f);
EditorGUIUtility.AddCursorRect(cursorChangeRect, MouseCursor.ResizeVertical);
if (Event.current.type == EventType.mouseDown && cursorChangeRect.Contains(Event.current.mousePosition))
{
resize = true;
}
if (resize)
{
Undo.RecordObject(flowchart, "Resize view");
flowchart.blockViewHeight = Event.current.mousePosition.y;
}
ClampBlockViewHeight(flowchart);
// Stop resizing if mouse is outside inspector window.
// This isn't standard Unity UI behavior but it is robust and safe.
if (resize && Event.current.type == EventType.mouseDrag)
{
Rect windowRect = new Rect(0, 0, Screen.width, Screen.height);
if (!windowRect.Contains(Event.current.mousePosition))
{
resize = false;
}
}
if (Event.current.type == EventType.MouseUp)
{
resize = false;
}
}
protected virtual void ClampBlockViewHeight(Flowchart flowchart)
{
// Screen.height seems to temporarily reset to 480 for a single frame whenever a command like
// Copy, Paste, etc. happens. Only clamp the block view height when one of these operations is not occuring.
if (Event.current.commandName != "")
{
clamp = false;
}
if (clamp)
{
// Make sure block view is always clamped to visible area
float height = flowchart.blockViewHeight;
height = Mathf.Max(200, height);
height = Mathf.Min(Screen.height - 200,height);
flowchart.blockViewHeight = height;
}
if (Event.current.type == EventType.Repaint)
{
clamp = true;
}
}
}
}
| |
using SimpleJson;
using System;
using System.Collections.Generic;
using System.Text;
namespace Pomelo.Protobuf
{
public class MsgDecoder
{
// The message format(like .proto file)
private JsonObject protos { set; get; }
private int offset { set; get; }
// The binary message from server.
private byte[] buffer { set; get; }
private Util util { set; get; }
public MsgDecoder(JsonObject protos)
{
if (protos == null)
protos = new JsonObject();
this.protos = protos;
this.util = new Util();
}
// Decode message from server.
public JsonObject Decode(string route, byte[] buf)
{
this.buffer = buf;
this.offset = 0;
object proto = null;
if (this.protos.TryGetValue(route, out proto))
{
JsonObject msg = new JsonObject();
return this.DecodeMsg(msg, (JsonObject)proto, this.buffer.Length);
}
return null;
}
// Decode the message.
private JsonObject DecodeMsg(JsonObject msg, JsonObject proto, int length)
{
while (this.offset < length)
{
Dictionary<string, int> head = this.GetHead();
int tag;
if (head.TryGetValue("tag", out tag) == false)
{
continue;
}
object _tags = null;
if (proto.TryGetValue("__tags", out _tags) == false)
{
continue;
}
object name;
if (((JsonObject)_tags).TryGetValue(tag.ToString(), out name) == false)
{
continue;
}
object value;
if (proto.TryGetValue(name.ToString(), out value) == false)
{
continue;
}
object option;
if (((JsonObject)(value)).TryGetValue("option", out option) == false)
{
continue;
}
switch (option.ToString())
{
case "optional":
case "required":
object type;
if (((JsonObject)(value)).TryGetValue("type", out type))
{
msg.Add(name.ToString(), this.DecodeProp(type.ToString(), proto));
}
break;
case "repeated":
object _name;
if (!msg.TryGetValue(name.ToString(), out _name))
{
msg.Add(name.ToString(), new JsonArray());
}
object value_type;
if (msg.TryGetValue(name.ToString(), out _name) && ((JsonObject)(value)).TryGetValue("type", out value_type))
{
this.DecodeArray((List<object>)_name, value_type.ToString(), proto);
}
break;
}
}
return msg;
}
// Decode array in message.
private void DecodeArray(List<object> list, string type, JsonObject proto)
{
if (this.util.IsSimpleType(type))
{
int length = (int)Decoder.DecodeUInt32(this.GetBytes());
for (int i = 0; i < length; i++)
{
list.Add(this.DecodeProp(type, null));
}
}
else
{
list.Add(this.DecodeProp(type, proto));
}
}
// Decode each simple type in message.
private object DecodeProp(string type, JsonObject proto)
{
switch (type)
{
case "uInt32":
return Decoder.DecodeUInt64(this.GetBytes());
case "int32":
case "sInt32":
return Decoder.DecodeSInt32(this.GetBytes());
case "float":
return this.DecodeFloat();
case "double":
return this.DecodeDouble();
case "string":
return this.DecodeString();
default:
return this.decodeObject(type, proto);
}
}
// Decode the user-defined object type in message.
private JsonObject decodeObject(string type, JsonObject proto)
{
if (proto == null)
{
return new JsonObject();
}
object __messages;
if (proto.TryGetValue("__messages", out __messages) == false)
{
return new JsonObject();
}
object _type;
if (((JsonObject)__messages).TryGetValue(type, out _type) || protos.TryGetValue("message " + type, out _type))
{
int l = (int)Decoder.DecodeUInt32(this.GetBytes());
JsonObject msg = new JsonObject();
return this.DecodeMsg(msg, (JsonObject)_type, this.offset + l);
}
return new JsonObject();
}
// Decode string type.
private string DecodeString()
{
int length = (int)Decoder.DecodeUInt32(this.GetBytes());
string msg_string = Encoding.UTF8.GetString(this.buffer, this.offset, length);
this.offset += length;
return msg_string;
}
// Decode double type.
private double DecodeDouble()
{
double msg_double = BitConverter.Int64BitsToDouble((long)this.ReadRawLittleEndian64());
this.offset += 8;
return msg_double;
}
// Decode float type
private float DecodeFloat()
{
float msg_float = BitConverter.ToSingle(this.buffer, this.offset);
this.offset += 4;
return msg_float;
}
// Read long in littleEndian
private ulong ReadRawLittleEndian64()
{
ulong b1 = this.buffer[this.offset];
ulong b2 = this.buffer[this.offset + 1];
ulong b3 = this.buffer[this.offset + 2];
ulong b4 = this.buffer[this.offset + 3];
ulong b5 = this.buffer[this.offset + 4];
ulong b6 = this.buffer[this.offset + 5];
ulong b7 = this.buffer[this.offset + 6];
ulong b8 = this.buffer[this.offset + 7];
return b1 | (b2 << 8) | (b3 << 16) | (b4 << 24)
| (b5 << 32) | (b6 << 40) | (b7 << 48) | (b8 << 56);
}
// Get the type and tag.
private Dictionary<string, int> GetHead()
{
int tag = (int)Decoder.DecodeUInt32(this.GetBytes());
Dictionary<string, int> head = new Dictionary<string, int>();
head.Add("type", tag & 0x7);
head.Add("tag", tag >> 3);
return head;
}
// Get bytes.
private byte[] GetBytes()
{
List<byte> arrayList = new List<byte>();
int pos = this.offset;
byte b;
do
{
b = this.buffer[pos];
arrayList.Add(b);
pos++;
} while (b >= 128);
this.offset = pos;
int length = arrayList.Count;
byte[] bytes = new byte[length];
for (int i = 0; i < length; i++)
{
bytes[i] = arrayList[i];
}
return bytes;
}
}
}
| |
//
// EqualizerView.cs
//
// Authors:
// Aaron Bockover <abockover@novell.com>
// Ivan N. Zlatev <contact i-nZ.net>
// Alexander Hixon <hixon.alexander@mediati.org>
//
// Copyright (C) 2006-2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using Gtk;
using Gdk;
using Banshee.ServiceStack;
using Banshee.MediaEngine;
namespace Banshee.Equalizer.Gui
{
public class EqualizerView : HBox
{
private HBox band_box;
private uint [] frequencies;
private EqualizerBandScale [] band_scales;
private EqualizerBandScale amplifier_scale;
private EqualizerSetting active_eq;
private int [] range = new int[3];
public event EqualizerChangedEventHandler EqualizerChanged;
public event AmplifierChangedEventHandler AmplifierChanged;
public EqualizerView () : base ()
{
BuildWidget ();
}
private void BuildWidget ()
{
Spacing = 10;
int [] br = ((IEqualizer)ServiceManager.PlayerEngine.ActiveEngine).BandRange;
int mid = (br[0] + br[1]) / 2;
range[0] = br[0];
range[1] = mid;
range[2] = br[1];
amplifier_scale = new EqualizerBandScale (0, range[1] * 10, range[0] * 10, range[2] * 10, "Preamp");
amplifier_scale.ValueChanged += OnAmplifierValueChanged;
amplifier_scale.Show ();
PackStart (amplifier_scale, false, false, 0);
EqualizerLevelsBox eq_levels = new EqualizerLevelsBox (
FormatDecibelString (range[2]),
FormatDecibelString (range[1]),
FormatDecibelString (range[0])
);
eq_levels.Show ();
PackStart (eq_levels, false, false, 0);
band_box = new HBox ();
band_box.Homogeneous = true;
band_box.Show ();
PackStart (band_box, true, true, 0);
BuildBands ();
}
private string FormatDecibelString (int db)
{
if (db > 0) {
return String.Format ("+{0} dB", db);
} else {
return String.Format ("{0} dB", db);
}
}
private void BuildBands ()
{
foreach (Widget widget in band_box.Children) {
band_box.Remove (widget);
}
if (frequencies == null || frequencies.Length <= 0) {
frequencies = new uint[0];
band_scales = new EqualizerBandScale[0];
return;
}
band_scales = new EqualizerBandScale[10];
for (uint i = 0; i < 10; i++) {
string label = frequencies[i] < 1000 ?
String.Format ("{0} Hz", frequencies[i]) :
String.Format ("{0} kHz", (int)Math.Round (frequencies[i] / 1000.0));
band_scales[i] = new EqualizerBandScale (i, range[1] * 10, range[0] * 10, range[2] * 10, label);
band_scales[i].ValueChanged += OnEqualizerValueChanged;
band_scales[i].Show ();
band_box.PackStart (band_scales[i], true, true, 0);
}
}
private void OnEqualizerValueChanged (object o, EventArgs args)
{
EqualizerBandScale scale = o as EqualizerBandScale;
if (active_eq != null) {
active_eq.SetGain (scale.Band, (double)scale.Value / 10);
}
if (EqualizerChanged != null) {
EqualizerChanged (this, new EqualizerChangedEventArgs (scale.Band, scale.Value));
}
}
private void OnAmplifierValueChanged (object o, EventArgs args)
{
EqualizerBandScale scale = o as EqualizerBandScale;
if (active_eq != null) {
active_eq.AmplifierLevel = (double) (scale.Value / 10.0);
}
if (AmplifierChanged != null) {
AmplifierChanged (this, new AmplifierChangedEventArgs (scale.Value));
}
}
public uint [] Frequencies {
get { return (uint [])frequencies.Clone (); }
set {
frequencies = (uint [])value.Clone ();
BuildBands ();
}
}
public int [] Preset {
get {
int [] result = new int[band_scales.Length];
for (int i = 0; i < band_scales.Length; i++) {
result[i] = (int) band_scales[i].Value;
}
return result;
}
set {
for (int i = 0; i < value.Length; i++) {
band_scales[i].Value = value[i];
}
}
}
public void SetBand(uint band, double value)
{
band_scales[band].Value = (int) (value * 10);
}
public double AmplifierLevel {
get { return (double) amplifier_scale.Value / 10; }
set { amplifier_scale.Value = (int) (value * 10); }
}
public EqualizerSetting EqualizerSetting {
get { return active_eq; }
set {
active_eq = value;
if (active_eq == null) {
AmplifierLevel = 0;
return;
}
AmplifierLevel = active_eq.AmplifierLevel;
for (int i = 0; i < active_eq.BandCount; i++) {
uint x = (uint) i;
SetBand (x, active_eq[x]);
}
}
}
}
public delegate void EqualizerChangedEventHandler (object o, EqualizerChangedEventArgs args);
public delegate void AmplifierChangedEventHandler (object o, AmplifierChangedEventArgs args);
public sealed class EqualizerChangedEventArgs : EventArgs
{
private uint band;
private int value;
public EqualizerChangedEventArgs (uint band, int value)
{
this.band = band;
this.value = value;
}
public uint Band {
get { return this.band; }
}
public int Value {
get { return this.value; }
}
}
public sealed class AmplifierChangedEventArgs : EventArgs
{
private int value;
public AmplifierChangedEventArgs (int value)
{
this.value = value;
}
public int Value {
get { return this.value; }
}
}
}
| |
/*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
/**
* Created at 11:34:45 AM Jan 23, 2011
*/
using System.Diagnostics;
using SharpBox2D.Common;
using SharpBox2D.Pooling;
namespace SharpBox2D.Dynamics.Joints
{
//Gear Joint:
//C0 = (coordinate1 + ratio * coordinate2)_initial
//C = (coordinate1 + ratio * coordinate2) - C0 = 0
//J = [J1 ratio * J2]
//K = J * invM * JT
//= J1 * invM1 * J1T + ratio * ratio * J2 * invM2 * J2T
//
//Revolute:
//coordinate = rotation
//Cdot = angularVelocity
//J = [0 0 1]
//K = J * invM * JT = invI
//
//Prismatic:
//coordinate = dot(p - pg, ug)
//Cdot = dot(v + cross(w, r), ug)
//J = [ug cross(r, ug)]
//K = J * invM * JT = invMass + invI * cross(r, ug)^2
/**
* A gear joint is used to connect two joints together. Either joint can be a revolute or prismatic
* joint. You specify a gear ratio to bind the motions together: coordinate1 + ratio * coordinate2 =
* constant The ratio can be negative or positive. If one joint is a revolute joint and the other
* joint is a prismatic joint, then the ratio will have units of length or units of 1/length.
*
* @warning The revolute and prismatic joints must be attached to fixed bodies (which must be body1
* on those joints).
* @warning You have to manually destroy the gear joint if joint1 or joint2 is destroyed.
* @author Daniel Murphy
*/
public class GearJoint : Joint
{
private Joint m_joint1;
private Joint m_joint2;
private JointType m_typeA;
private JointType m_typeB;
// Body A is connected to body C
// Body B is connected to body D
private Body m_bodyC;
private Body m_bodyD;
// Solver shared
private Vec2 m_localAnchorA = new Vec2();
private Vec2 m_localAnchorB = new Vec2();
private Vec2 m_localAnchorC = new Vec2();
private Vec2 m_localAnchorD = new Vec2();
private Vec2 m_localAxisC = new Vec2();
private Vec2 m_localAxisD = new Vec2();
private float m_referenceAngleA;
private float m_referenceAngleB;
private float m_constant;
private float m_ratio;
private float m_impulse;
// Solver temp
private int m_indexA, m_indexB, m_indexC, m_indexD;
private Vec2 m_lcA = new Vec2(),
m_lcB = new Vec2(),
m_lcC = new Vec2(),
m_lcD = new Vec2();
private float m_mA, m_mB, m_mC, m_mD;
private float m_iA, m_iB, m_iC, m_iD;
private Vec2 m_JvAC = new Vec2(), m_JvBD = new Vec2();
private float m_JwA, m_JwB, m_JwC, m_JwD;
private float m_mass;
internal GearJoint(IWorldPool argWorldPool, GearJointDef def) :
base(argWorldPool, def)
{
m_joint1 = def.joint1;
m_joint2 = def.joint2;
m_typeA = m_joint1.getType();
m_typeB = m_joint2.getType();
Debug.Assert(m_typeA == JointType.REVOLUTE || m_typeA == JointType.PRISMATIC);
Debug.Assert(m_typeB == JointType.REVOLUTE || m_typeB == JointType.PRISMATIC);
float coordinateA, coordinateB;
// TODO_ERIN there might be some problem with the joint edges in Joint.
m_bodyC = m_joint1.getBodyA();
m_bodyA = m_joint1.getBodyB();
// Get geometry of joint1
Transform xfA = m_bodyA.m_xf;
float aA = m_bodyA.m_sweep.a;
Transform xfC = m_bodyC.m_xf;
float aC = m_bodyC.m_sweep.a;
if (m_typeA == JointType.REVOLUTE)
{
RevoluteJoint revolute = (RevoluteJoint) def.joint1;
m_localAnchorC.set(revolute.m_localAnchorA);
m_localAnchorA.set(revolute.m_localAnchorB);
m_referenceAngleA = revolute.m_referenceAngle;
m_localAxisC.setZero();
coordinateA = aA - aC - m_referenceAngleA;
}
else
{
Vec2 pA = pool.popVec2();
Vec2 temp = pool.popVec2();
PrismaticJoint prismatic = (PrismaticJoint) def.joint1;
m_localAnchorC.set(prismatic.m_localAnchorA);
m_localAnchorA.set(prismatic.m_localAnchorB);
m_referenceAngleA = prismatic.m_referenceAngle;
m_localAxisC.set(prismatic.m_localXAxisA);
Vec2 pC = m_localAnchorC;
Rot.mulToOutUnsafe(xfA.q, m_localAnchorA, ref temp);
temp.addLocal(xfA.p);
temp.subLocal(xfC.p);
Rot.mulTransUnsafe(xfC.q, temp, ref pA);
pA.subLocal(pC);
coordinateA = Vec2.dot(pA, m_localAxisC);
pool.pushVec2(2);
}
m_bodyD = m_joint2.getBodyA();
m_bodyB = m_joint2.getBodyB();
// Get geometry of joint2
Transform xfB = m_bodyB.m_xf;
float aB = m_bodyB.m_sweep.a;
Transform xfD = m_bodyD.m_xf;
float aD = m_bodyD.m_sweep.a;
if (m_typeB == JointType.REVOLUTE)
{
RevoluteJoint revolute = (RevoluteJoint) def.joint2;
m_localAnchorD.set(revolute.m_localAnchorA);
m_localAnchorB.set(revolute.m_localAnchorB);
m_referenceAngleB = revolute.m_referenceAngle;
m_localAxisD.setZero();
coordinateB = aB - aD - m_referenceAngleB;
}
else
{
Vec2 pB = pool.popVec2();
Vec2 temp = pool.popVec2();
PrismaticJoint prismatic = (PrismaticJoint) def.joint2;
m_localAnchorD.set(prismatic.m_localAnchorA);
m_localAnchorB.set(prismatic.m_localAnchorB);
m_referenceAngleB = prismatic.m_referenceAngle;
m_localAxisD.set(prismatic.m_localXAxisA);
Vec2 pD = m_localAnchorD;
Rot.mulToOutUnsafe(xfB.q, m_localAnchorB, ref temp);
temp.addLocal(xfB.p);
temp.subLocal(xfD.p);
Rot.mulTransUnsafe(xfD.q, temp, ref pB);
pB.subLocal(pD);
coordinateB = Vec2.dot(pB, m_localAxisD);
pool.pushVec2(2);
}
m_ratio = def.ratio;
m_constant = coordinateA + m_ratio*coordinateB;
m_impulse = 0.0f;
}
public override void getAnchorA(ref Vec2 argOut)
{
m_bodyA.getWorldPointToOut(m_localAnchorA, ref argOut);
}
public override void getAnchorB(ref Vec2 argOut)
{
m_bodyB.getWorldPointToOut(m_localAnchorB, ref argOut);
}
public override void getReactionForce(float inv_dt, ref Vec2 argOut)
{
argOut.set(m_JvAC);
argOut.mulLocal(m_impulse);
argOut.mulLocal(inv_dt);
}
public override float getReactionTorque(float inv_dt)
{
float L = m_impulse*m_JwA;
return inv_dt*L;
}
public void setRatio(float argRatio)
{
m_ratio = argRatio;
}
public float getRatio()
{
return m_ratio;
}
public override void initVelocityConstraints(SolverData data)
{
m_indexA = m_bodyA.m_islandIndex;
m_indexB = m_bodyB.m_islandIndex;
m_indexC = m_bodyC.m_islandIndex;
m_indexD = m_bodyD.m_islandIndex;
m_lcA.set(m_bodyA.m_sweep.localCenter);
m_lcB.set(m_bodyB.m_sweep.localCenter);
m_lcC.set(m_bodyC.m_sweep.localCenter);
m_lcD.set(m_bodyD.m_sweep.localCenter);
m_mA = m_bodyA.m_invMass;
m_mB = m_bodyB.m_invMass;
m_mC = m_bodyC.m_invMass;
m_mD = m_bodyD.m_invMass;
m_iA = m_bodyA.m_invI;
m_iB = m_bodyB.m_invI;
m_iC = m_bodyC.m_invI;
m_iD = m_bodyD.m_invI;
// Vec2 cA = data.positions[m_indexA].c;
float aA = data.positions[m_indexA].a;
Vec2 vA = data.velocities[m_indexA].v;
float wA = data.velocities[m_indexA].w;
// Vec2 cB = data.positions[m_indexB].c;
float aB = data.positions[m_indexB].a;
Vec2 vB = data.velocities[m_indexB].v;
float wB = data.velocities[m_indexB].w;
// Vec2 cC = data.positions[m_indexC].c;
float aC = data.positions[m_indexC].a;
Vec2 vC = data.velocities[m_indexC].v;
float wC = data.velocities[m_indexC].w;
// Vec2 cD = data.positions[m_indexD].c;
float aD = data.positions[m_indexD].a;
Vec2 vD = data.velocities[m_indexD].v;
float wD = data.velocities[m_indexD].w;
Rot qA = pool.popRot(), qB = pool.popRot(), qC = pool.popRot(), qD = pool.popRot();
qA.set(aA);
qB.set(aB);
qC.set(aC);
qD.set(aD);
m_mass = 0.0f;
Vec2 temp = pool.popVec2();
if (m_typeA == JointType.REVOLUTE)
{
m_JvAC.setZero();
m_JwA = 1.0f;
m_JwC = 1.0f;
m_mass += m_iA + m_iC;
}
else
{
Vec2 rC = pool.popVec2();
Vec2 rA = pool.popVec2();
Rot.mulToOutUnsafe(qC, m_localAxisC, ref m_JvAC);
temp.set(m_localAnchorC);
temp.subLocal(m_lcC);
Rot.mulToOutUnsafe(qC, temp, ref rC);
temp.set(m_localAnchorA);
temp.subLocal(m_lcA);
Rot.mulToOutUnsafe(qA,temp, ref rA);
m_JwC = Vec2.cross(rC, m_JvAC);
m_JwA = Vec2.cross(rA, m_JvAC);
m_mass += m_mC + m_mA + m_iC*m_JwC*m_JwC + m_iA*m_JwA*m_JwA;
pool.pushVec2(2);
}
if (m_typeB == JointType.REVOLUTE)
{
m_JvBD.setZero();
m_JwB = m_ratio;
m_JwD = m_ratio;
m_mass += m_ratio*m_ratio*(m_iB + m_iD);
}
else
{
Vec2 u = pool.popVec2();
Vec2 rD = pool.popVec2();
Vec2 rB = pool.popVec2();
Rot.mulToOutUnsafe(qD, m_localAxisD, ref u);
temp.set(m_localAnchorD);
temp.subLocal(m_lcD);
Rot.mulToOutUnsafe(qD, temp , ref rD);
temp.set(m_localAnchorB);
temp.subLocal(m_lcB);
Rot.mulToOutUnsafe(qB, temp, ref rB);
m_JvBD.set(u);
m_JvBD.mulLocal(m_ratio);
m_JwD = m_ratio*Vec2.cross(rD, u);
m_JwB = m_ratio*Vec2.cross(rB, u);
m_mass += m_ratio*m_ratio*(m_mD + m_mB) + m_iD*m_JwD*m_JwD + m_iB*m_JwB*m_JwB;
pool.pushVec2(3);
}
// Compute effective mass.
m_mass = m_mass > 0.0f ? 1.0f/m_mass : 0.0f;
if (data.step.warmStarting)
{
vA.x += (m_mA*m_impulse)*m_JvAC.x;
vA.y += (m_mA*m_impulse)*m_JvAC.y;
wA += m_iA*m_impulse*m_JwA;
vB.x += (m_mB*m_impulse)*m_JvBD.x;
vB.y += (m_mB*m_impulse)*m_JvBD.y;
wB += m_iB*m_impulse*m_JwB;
vC.x -= (m_mC*m_impulse)*m_JvAC.x;
vC.y -= (m_mC*m_impulse)*m_JvAC.y;
wC -= m_iC*m_impulse*m_JwC;
vD.x -= (m_mD*m_impulse)*m_JvBD.x;
vD.y -= (m_mD*m_impulse)*m_JvBD.y;
wD -= m_iD*m_impulse*m_JwD;
}
else
{
m_impulse = 0.0f;
}
pool.pushVec2(1);
pool.pushRot(4);
// data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
// data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
// data.velocities[m_indexC].v = vC;
data.velocities[m_indexC].w = wC;
// data.velocities[m_indexD].v = vD;
data.velocities[m_indexD].w = wD;
}
public override void solveVelocityConstraints(SolverData data)
{
Vec2 vA = data.velocities[m_indexA].v;
float wA = data.velocities[m_indexA].w;
Vec2 vB = data.velocities[m_indexB].v;
float wB = data.velocities[m_indexB].w;
Vec2 vC = data.velocities[m_indexC].v;
float wC = data.velocities[m_indexC].w;
Vec2 vD = data.velocities[m_indexD].v;
float wD = data.velocities[m_indexD].w;
Vec2 temp1 = pool.popVec2();
Vec2 temp2 = pool.popVec2();
temp1.set(vA);
temp1.subLocal(vC);
temp2.set(vB);
temp2.subLocal(vD);
float Cdot =
Vec2.dot(m_JvAC, temp1) + Vec2.dot(m_JvBD, temp2);
Cdot += (m_JwA*wA - m_JwC*wC) + (m_JwB*wB - m_JwD*wD);
pool.pushVec2(2);
float impulse = -m_mass*Cdot;
m_impulse += impulse;
vA.x += (m_mA*impulse)*m_JvAC.x;
vA.y += (m_mA*impulse)*m_JvAC.y;
wA += m_iA*impulse*m_JwA;
vB.x += (m_mB*impulse)*m_JvBD.x;
vB.y += (m_mB*impulse)*m_JvBD.y;
wB += m_iB*impulse*m_JwB;
vC.x -= (m_mC*impulse)*m_JvAC.x;
vC.y -= (m_mC*impulse)*m_JvAC.y;
wC -= m_iC*impulse*m_JwC;
vD.x -= (m_mD*impulse)*m_JvBD.x;
vD.y -= (m_mD*impulse)*m_JvBD.y;
wD -= m_iD*impulse*m_JwD;
// data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
// data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
// data.velocities[m_indexC].v = vC;
data.velocities[m_indexC].w = wC;
// data.velocities[m_indexD].v = vD;
data.velocities[m_indexD].w = wD;
}
public Joint getJoint1()
{
return m_joint1;
}
public Joint getJoint2()
{
return m_joint2;
}
public override bool solvePositionConstraints(SolverData data)
{
Vec2 cA = data.positions[m_indexA].c;
float aA = data.positions[m_indexA].a;
Vec2 cB = data.positions[m_indexB].c;
float aB = data.positions[m_indexB].a;
Vec2 cC = data.positions[m_indexC].c;
float aC = data.positions[m_indexC].a;
Vec2 cD = data.positions[m_indexD].c;
float aD = data.positions[m_indexD].a;
Rot qA = pool.popRot(), qB = pool.popRot(), qC = pool.popRot(), qD = pool.popRot();
qA.set(aA);
qB.set(aB);
qC.set(aC);
qD.set(aD);
float linearError = 0.0f;
float coordinateA, coordinateB;
Vec2 temp = pool.popVec2();
Vec2 JvAC = pool.popVec2();
Vec2 JvBD = pool.popVec2();
float JwA, JwB, JwC, JwD;
float mass = 0.0f;
if (m_typeA == JointType.REVOLUTE)
{
JvAC.setZero();
JwA = 1.0f;
JwC = 1.0f;
mass += m_iA + m_iC;
coordinateA = aA - aC - m_referenceAngleA;
}
else
{
Vec2 rC = pool.popVec2();
Vec2 rA = pool.popVec2();
Vec2 pC = pool.popVec2();
Vec2 pA = pool.popVec2();
Rot.mulToOutUnsafe(qC, m_localAxisC, ref JvAC);
temp.set(m_localAnchorC);
temp.subLocal(m_lcC);
Rot.mulToOutUnsafe(qC, temp, ref rC);
temp.set(m_localAnchorA);
temp.subLocal(m_lcA);
Rot.mulToOutUnsafe(qA, temp, ref rA);
JwC = Vec2.cross(rC, JvAC);
JwA = Vec2.cross(rA, JvAC);
mass += m_mC + m_mA + m_iC*JwC*JwC + m_iA*JwA*JwA;
pC.set(m_localAnchorC);
pC.subLocal(m_lcC);
temp.set(rA);
temp.addLocal(cA);
temp.subLocal(cC);
Rot.mulTransUnsafe(qC, temp, ref pA);
pA.subLocal(pC);
coordinateA = Vec2.dot(pA, m_localAxisC);
pool.pushVec2(4);
}
if (m_typeB == JointType.REVOLUTE)
{
JvBD.setZero();
JwB = m_ratio;
JwD = m_ratio;
mass += m_ratio*m_ratio*(m_iB + m_iD);
coordinateB = aB - aD - m_referenceAngleB;
}
else
{
Vec2 u = pool.popVec2();
Vec2 rD = pool.popVec2();
Vec2 rB = pool.popVec2();
Vec2 pD = pool.popVec2();
Vec2 pB = pool.popVec2();
Rot.mulToOutUnsafe(qD, m_localAxisD, ref u);
temp.set(m_localAnchorD);
temp.subLocal(m_lcD);
Rot.mulToOutUnsafe(qD, temp, ref rD);
temp.set(m_localAnchorB);
temp.subLocal(m_lcB);
Rot.mulToOutUnsafe(qB, temp, ref rB);
JvBD.set(u);
JvBD.mulLocal(m_ratio);
JwD = Vec2.cross(rD, u);
JwB = Vec2.cross(rB, u);
mass += m_ratio*m_ratio*(m_mD + m_mB) + m_iD*JwD*JwD + m_iB*JwB*JwB;
pD.set(m_localAnchorD);
pD.subLocal(m_lcD);
temp.set(rB);
temp.addLocal(cB);
Rot.mulTransUnsafe(qD, temp, ref pB);
pB.subLocal(pD);
coordinateB = Vec2.dot(pB, m_localAxisD);
pool.pushVec2(5);
}
float C = (coordinateA + m_ratio*coordinateB) - m_constant;
float impulse = 0.0f;
if (mass > 0.0f)
{
impulse = -C/mass;
}
pool.pushVec2(3);
pool.pushRot(4);
cA.x += (m_mA*impulse)*JvAC.x;
cA.y += (m_mA*impulse)*JvAC.y;
aA += m_iA*impulse*JwA;
cB.x += (m_mB*impulse)*JvBD.x;
cB.y += (m_mB*impulse)*JvBD.y;
aB += m_iB*impulse*JwB;
cC.x -= (m_mC*impulse)*JvAC.x;
cC.y -= (m_mC*impulse)*JvAC.y;
aC -= m_iC*impulse*JwC;
cD.x -= (m_mD*impulse)*JvBD.x;
cD.y -= (m_mD*impulse)*JvBD.y;
aD -= m_iD*impulse*JwD;
// data.positions[m_indexA].c = cA;
data.positions[m_indexA].a = aA;
// data.positions[m_indexB].c = cB;
data.positions[m_indexB].a = aB;
// data.positions[m_indexC].c = cC;
data.positions[m_indexC].a = aC;
// data.positions[m_indexD].c = cD;
data.positions[m_indexD].a = aD;
// TODO_ERIN not implemented
return linearError < Settings.linearSlop;
}
}
}
| |
// Copyright 2013-2015 Serilog Contributors
//
// 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.
#nullable enable
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using Serilog.Events;
using Serilog.Parsing;
using Serilog.Rendering;
namespace Serilog.Formatting.Json
{
/// <summary>
/// Formats log events in a simple JSON structure. Instances of this class
/// are safe for concurrent access by multiple threads.
/// </summary>
public class JsonFormatter : ITextFormatter
{
const string ExtensionPointObsoletionMessage = "Extension of JsonFormatter by subclassing is obsolete and will " +
"be removed in a future Serilog version. Write a custom formatter " +
"based on JsonValueFormatter instead. See https://github.com/serilog/serilog/pull/819.";
// Ignore obsoletion errors
#pragma warning disable 618
readonly bool _omitEnclosingObject;
readonly string _closingDelimiter;
readonly bool _renderMessage;
readonly IFormatProvider? _formatProvider;
readonly IDictionary<Type, Action<object, bool, TextWriter>> _literalWriters;
/// <summary>
/// Construct a <see cref="JsonFormatter"/>.
/// </summary>
/// <param name="closingDelimiter">A string that will be written after each log event is formatted.
/// If null, <see cref="Environment.NewLine"/> will be used.</param>
/// <param name="renderMessage">If true, the message will be rendered and written to the output as a
/// property named RenderedMessage.</param>
/// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
public JsonFormatter(
string? closingDelimiter = null,
bool renderMessage = false,
IFormatProvider? formatProvider = null)
: this(false, closingDelimiter, renderMessage, formatProvider)
{
}
/// <summary>
/// Construct a <see cref="JsonFormatter"/>.
/// </summary>
/// <param name="omitEnclosingObject">If true, the properties of the event will be written to
/// the output without enclosing braces. Otherwise, if false, each event will be written as a well-formed
/// JSON object.</param>
/// <param name="closingDelimiter">A string that will be written after each log event is formatted.
/// If null, <see cref="Environment.NewLine"/> will be used. Ignored if <paramref name="omitEnclosingObject"/>
/// is true.</param>
/// <param name="renderMessage">If true, the message will be rendered and written to the output as a
/// property named RenderedMessage.</param>
/// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
[Obsolete("The omitEnclosingObject parameter is obsolete and will be removed in a future Serilog version.")]
public JsonFormatter(
bool omitEnclosingObject,
string? closingDelimiter = null,
bool renderMessage = false,
IFormatProvider? formatProvider = null)
{
_omitEnclosingObject = omitEnclosingObject;
_closingDelimiter = closingDelimiter ?? Environment.NewLine;
_renderMessage = renderMessage;
_formatProvider = formatProvider;
_literalWriters = new Dictionary<Type, Action<object, bool, TextWriter>>
{
{ typeof(bool), (v, _, w) => WriteBoolean((bool)v, w) },
{ typeof(char), (v, _, w) => WriteString(((char)v).ToString(), w) },
{ typeof(byte), WriteToString },
{ typeof(sbyte), WriteToString },
{ typeof(short), WriteToString },
{ typeof(ushort), WriteToString },
{ typeof(int), WriteToString },
{ typeof(uint), WriteToString },
{ typeof(long), WriteToString },
{ typeof(ulong), WriteToString },
{ typeof(float), (v, _, w) => WriteSingle((float)v, w) },
{ typeof(double), (v, _, w) => WriteDouble((double)v, w) },
{ typeof(decimal), WriteToString },
{ typeof(string), (v, _, w) => WriteString((string)v, w) },
{ typeof(DateTime), (v, _, w) => WriteDateTime((DateTime)v, w) },
{ typeof(DateTimeOffset), (v, _, w) => WriteOffset((DateTimeOffset)v, w) },
{ typeof(ScalarValue), (v, q, w) => WriteLiteral(((ScalarValue)v).Value, w, q) },
{ typeof(SequenceValue), (v, _, w) => WriteSequence(((SequenceValue)v).Elements, w) },
{ typeof(DictionaryValue), (v, _, w) => WriteDictionary(((DictionaryValue)v).Elements, w) },
{ typeof(StructureValue), (v, _, w) => WriteStructure(((StructureValue)v).TypeTag, ((StructureValue)v).Properties, w) },
};
}
/// <summary>
/// Format the log event into the output.
/// </summary>
/// <param name="logEvent">The event to format.</param>
/// <param name="output">The output.</param>
/// <exception cref="ArgumentNullException">When <paramref name="logEvent"/> is <code>null</code></exception>
/// <exception cref="ArgumentNullException">When <paramref name="output"/> is <code>null</code></exception>
public void Format(LogEvent logEvent, TextWriter output)
{
if (logEvent == null) throw new ArgumentNullException(nameof(logEvent));
if (output == null) throw new ArgumentNullException(nameof(output));
if (!_omitEnclosingObject)
output.Write("{");
var delim = "";
WriteTimestamp(logEvent.Timestamp, ref delim, output);
WriteLevel(logEvent.Level, ref delim, output);
WriteMessageTemplate(logEvent.MessageTemplate.Text, ref delim, output);
if (_renderMessage)
{
var message = logEvent.RenderMessage(_formatProvider);
WriteRenderedMessage(message, ref delim, output);
}
if (logEvent.Exception != null)
WriteException(logEvent.Exception, ref delim, output);
if (logEvent.Properties.Count != 0)
WriteProperties(logEvent.Properties, output);
var tokensWithFormat = logEvent.MessageTemplate.Tokens
.OfType<PropertyToken>()
.Where(pt => pt.Format != null)
.GroupBy(pt => pt.PropertyName)
.ToArray();
if (tokensWithFormat.Length != 0)
{
WriteRenderings(tokensWithFormat, logEvent.Properties, output);
}
if (!_omitEnclosingObject)
{
output.Write("}");
output.Write(_closingDelimiter);
}
}
/// <summary>
/// Adds a writer function for a given type.
/// </summary>
/// <param name="type">The type of values, which <paramref name="writer" /> handles.</param>
/// <param name="writer">The function, which writes the values.</param>
/// <exception cref="ArgumentNullException">When <paramref name="type"/> is <code>null</code></exception>
/// <exception cref="ArgumentNullException">When <paramref name="writer"/> is <code>null</code></exception>
[Obsolete(ExtensionPointObsoletionMessage)]
protected void AddLiteralWriter(Type type, Action<object, TextWriter> writer)
{
if (type == null) throw new ArgumentNullException(nameof(type));
if (writer == null) throw new ArgumentNullException(nameof(writer));
_literalWriters[type] = (v, _, w) => writer(v, w);
}
/// <summary>
/// Writes out individual renderings of attached properties
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteRenderings(IGrouping<string, PropertyToken>[] tokensWithFormat, IReadOnlyDictionary<string, LogEventPropertyValue> properties, TextWriter output)
{
output.Write(",\"{0}\":{{", "Renderings");
WriteRenderingsValues(tokensWithFormat, properties, output);
output.Write("}");
}
/// <summary>
/// Writes out the values of individual renderings of attached properties
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteRenderingsValues(IGrouping<string, PropertyToken>[] tokensWithFormat, IReadOnlyDictionary<string, LogEventPropertyValue> properties, TextWriter output)
{
var rdelim = "";
foreach (var ptoken in tokensWithFormat)
{
output.Write(rdelim);
rdelim = ",";
output.Write("\"");
output.Write(ptoken.Key);
output.Write("\":[");
var fdelim = "";
foreach (var format in ptoken)
{
output.Write(fdelim);
fdelim = ",";
output.Write("{");
var eldelim = "";
WriteJsonProperty("Format", format.Format, ref eldelim, output);
var sw = new StringWriter();
MessageTemplateRenderer.RenderPropertyToken(format, properties, sw, _formatProvider, isLiteral: true, isJson: false);
WriteJsonProperty("Rendering", sw.ToString(), ref eldelim, output);
output.Write("}");
}
output.Write("]");
}
}
/// <summary>
/// Writes out the attached properties
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteProperties(IReadOnlyDictionary<string, LogEventPropertyValue> properties, TextWriter output)
{
output.Write(",\"{0}\":{{", "Properties");
WritePropertiesValues(properties, output);
output.Write("}");
}
/// <summary>
/// Writes out the attached properties values
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WritePropertiesValues(IReadOnlyDictionary<string, LogEventPropertyValue> properties, TextWriter output)
{
var precedingDelimiter = "";
foreach (var property in properties)
{
WriteJsonProperty(property.Key, property.Value, ref precedingDelimiter, output);
}
}
/// <summary>
/// Writes out the attached exception
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteException(Exception exception, ref string delim, TextWriter output)
{
WriteJsonProperty("Exception", exception, ref delim, output);
}
/// <summary>
/// (Optionally) writes out the rendered message
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteRenderedMessage(string message, ref string delim, TextWriter output)
{
WriteJsonProperty("RenderedMessage", message, ref delim, output);
}
/// <summary>
/// Writes out the message template for the logevent.
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteMessageTemplate(string template, ref string delim, TextWriter output)
{
WriteJsonProperty("MessageTemplate", template, ref delim, output);
}
/// <summary>
/// Writes out the log level
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteLevel(LogEventLevel level, ref string delim, TextWriter output)
{
WriteJsonProperty("Level", level, ref delim, output);
}
/// <summary>
/// Writes out the log timestamp
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteTimestamp(DateTimeOffset timestamp, ref string delim, TextWriter output)
{
WriteJsonProperty("Timestamp", timestamp, ref delim, output);
}
/// <summary>
/// Writes out a structure property
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteStructure(string? typeTag, IEnumerable<LogEventProperty> properties, TextWriter output)
{
output.Write("{");
var delim = "";
if (typeTag != null)
WriteJsonProperty("_typeTag", typeTag, ref delim, output);
foreach (var property in properties)
WriteJsonProperty(property.Name, property.Value, ref delim, output);
output.Write("}");
}
/// <summary>
/// Writes out a sequence property
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteSequence(IEnumerable elements, TextWriter output)
{
output.Write("[");
var delim = "";
foreach (var value in elements)
{
output.Write(delim);
delim = ",";
WriteLiteral(value, output);
}
output.Write("]");
}
/// <summary>
/// Writes out a dictionary
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteDictionary(IReadOnlyDictionary<ScalarValue, LogEventPropertyValue> elements, TextWriter output)
{
output.Write("{");
var delim = "";
foreach (var element in elements)
{
output.Write(delim);
delim = ",";
WriteLiteral(element.Key, output, forceQuotation: true);
output.Write(":");
WriteLiteral(element.Value, output);
}
output.Write("}");
}
/// <summary>
/// Writes out a json property with the specified value on output writer
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteJsonProperty(string name, object value, ref string precedingDelimiter, TextWriter output)
{
output.Write(precedingDelimiter);
output.Write("\"");
output.Write(name);
output.Write("\":");
WriteLiteral(value, output);
precedingDelimiter = ",";
}
/// <summary>
/// Allows a subclass to write out objects that have no configured literal writer.
/// </summary>
/// <param name="value">The value to be written as a json construct</param>
/// <param name="output">The writer to write on</param>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteLiteralValue(object value, TextWriter output)
{
WriteString(value.ToString() ?? "", output);
}
void WriteLiteral(object value, TextWriter output, bool forceQuotation = false)
{
if (value == null)
{
output.Write("null");
return;
}
if (_literalWriters.TryGetValue(value.GetType(), out var writer))
{
writer(value, forceQuotation, output);
return;
}
WriteLiteralValue(value, output);
}
static void WriteToString(object number, bool quote, TextWriter output)
{
if (quote) output.Write('"');
if (number is IFormattable fmt)
output.Write(fmt.ToString(null, CultureInfo.InvariantCulture));
else
output.Write(number.ToString());
if (quote) output.Write('"');
}
static void WriteBoolean(bool value, TextWriter output)
{
output.Write(value ? "true" : "false");
}
static void WriteSingle(float value, TextWriter output)
{
output.Write(value.ToString("R", CultureInfo.InvariantCulture));
}
static void WriteDouble(double value, TextWriter output)
{
output.Write(value.ToString("R", CultureInfo.InvariantCulture));
}
static void WriteOffset(DateTimeOffset value, TextWriter output)
{
output.Write("\"");
output.Write(value.ToString("o"));
output.Write("\"");
}
static void WriteDateTime(DateTime value, TextWriter output)
{
output.Write("\"");
output.Write(value.ToString("o"));
output.Write("\"");
}
static void WriteString(string value, TextWriter output)
{
JsonValueFormatter.WriteQuotedJsonString(value, output);
}
/// <summary>
/// Perform simple JSON string escaping on <paramref name="s"/>.
/// </summary>
/// <param name="s">A raw string.</param>
/// <returns>A JSON-escaped version of <paramref name="s"/>.</returns>
[Obsolete("Use JsonValueFormatter.WriteQuotedJsonString() instead."), EditorBrowsable(EditorBrowsableState.Never)]
public static string? Escape(string s)
{
if (s == null) return null;
var escapedResult = new StringWriter();
JsonValueFormatter.WriteQuotedJsonString(s, escapedResult);
var quoted = escapedResult.ToString();
return quoted.Substring(1, quoted.Length - 2);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using Tharga.Toolkit.Console.Entities;
using Tharga.Toolkit.Console.Interfaces;
namespace Tharga.Toolkit.Console.Helpers
{
internal class InputInstance : IDisposable
{
private readonly object _locationLock = new object();
private bool _finished;
private readonly string _paramName;
private readonly char? _passwordChar;
private readonly IConsole _console;
private static readonly Dictionary<string, List<string>> _commandHistory = new Dictionary<string, List<string>>();
private int _commandHistoryIndex = -1;
private Location _startLocation;
private object _selection;
private static int _currentBufferLineCount;
private static int _cursorLineOffset;
private InputBuffer _inputBuffer;
private readonly CancellationToken _cancellationToken;
//TODO: Theese values should be read from the instance, not as a static value!
public static int CurrentBufferLineCount { get { return _currentBufferLineCount == 0 ? 1 : (_currentBufferLineCount + 1); } private set { _currentBufferLineCount = value; } }
public static int CursorLineOffset { get { return _cursorLineOffset; } set { _cursorLineOffset = value; } }
public InputInstance(IConsole console, string paramName, char? passwordChar, CancellationToken cancellationToken)
{
if (console == null) throw new ArgumentNullException(nameof(console), "No console provided.");
_console = console;
_paramName = paramName;
_passwordChar = passwordChar;
_cancellationToken = cancellationToken;
_console.PushBufferDownEvent += PushBufferDownEvent;
_console.LinesInsertedEvent += LinesInsertedEvent;
_startLocation = new Location(CursorLeft, CursorTop);
}
private int CursorLeft => _console.CursorLeft;
private int CursorTop => _console.CursorTop;
private int BufferWidth => _console.BufferWidth;
private int BufferHeight => _console.BufferHeight;
private void SetCursorPosition(int left, int top)
{
_console.SetCursorPosition(left, top);
}
private void PushBufferDownEvent(object sender, PushBufferDownEventArgs e)
{
//TODO: Create e.LineCount free extra lines after the current buffer and move the cursor where it was before.
//Step1: Remember cursor position
var location = new Location(CursorLeft, CursorTop);
//Step2: move the cursor to the end of the input buffer,
//TODO: (Test by having text after the buffer, in one or several lines
//Step3: Insert lines
for (var i = 0; i < e.LineCount; i++)
System.Console.WriteLine(string.Empty);
//Step4: Move cursor back to position
SetCursorPosition(location.Left, location.Top - 1);
}
private void LinesInsertedEvent(object sender, LinesInsertedEventArgs e)
{
lock (_locationLock)
{
var top = _startLocation.Top + e.LineCount;
if (top >= BufferHeight) top = BufferHeight - 1;
_startLocation = new Location(_startLocation.Left, top);
}
}
public T ReadLine<T>(CommandTreeNode<T> selection, bool allowEscape)
{
_inputBuffer = new InputBuffer();
_inputBuffer.InputBufferChangedEvent += InputBufferChangedEvent;
_console.Output(new WriteEventArgs($"{_paramName}{(_paramName != Constants.Prompt ? ": " : string.Empty)}", OutputLevel.Default, null, null, false, false));
lock (_locationLock)
{
_startLocation = new Location(CursorLeft, CursorTop);
}
while (true)
{
try
{
var preEntryBuffWidth = BufferWidth;
var preEntryCursorLocationTop = CursorTop;
var preStartCursorLocationTop = _startLocation.Top;
var readKey = _console.ReadKey(_cancellationToken);
lock (CommandEngine.SyncRoot)
{
var currentScreenLocation = new Location(CursorLeft, CursorTop); //This is where the cursor actually is on screen.
//This code handle buffer resize on a running console.
if (preEntryBuffWidth != BufferWidth)
{
if (currentScreenLocation.Top != preEntryCursorLocationTop || _startLocation.Top != preStartCursorLocationTop)
{
lock (_locationLock)
{
var pop1 = currentScreenLocation.Top - preEntryCursorLocationTop;
var pop2 = preStartCursorLocationTop - _startLocation.Top;
var top = _startLocation.Top + pop1 + pop2;
if (top >= BufferHeight) top = BufferHeight - 1;
_startLocation = new Location(_startLocation.Left, top);
}
}
}
var currentBufferPosition = ((currentScreenLocation.Top - _startLocation.Top) * BufferWidth) + currentScreenLocation.Left - _startLocation.Left;
//Debug.WriteLine($"cbp: {currentBufferPosition} = (({currentScreenLocation.Top} - {_startLocation.Top}) * {_console.BufferWidth}) + {currentScreenLocation.Left} - {_startLocation.Left}");
//System.Console.Title = $"cbp: {currentBufferPosition} = (({currentScreenLocation.Top} - {_startLocation.Top}) * {_console.BufferWidth}) + {currentScreenLocation.Left} - {_startLocation.Left}";
if (currentBufferPosition < 0)
{
throw new InvalidOperationException("Buffer insert position cannot be less than zero.");
}
if (IsOutputKey(readKey))
{
var input = readKey.KeyChar;
InsertText(currentScreenLocation, input, _inputBuffer, currentBufferPosition, _startLocation);
}
else if (readKey.Modifiers == ConsoleModifiers.Control)
{
switch (readKey.Key)
{
//case ConsoleKey.V:
// var input = System.Windows.Clipboard.GetText().ToArray();
// foreach (var chr in input)
// {
// InsertText(currentScreenLocation, chr, _inputBuffer, currentBufferPosition, _startLocation);
// if (currentScreenLocation.Left == BufferWidth - 1)
// currentScreenLocation = new Location(0, currentScreenLocation.Top + 1);
// else
// currentScreenLocation = new Location(currentScreenLocation.Left + 1, currentScreenLocation.Top);
// currentBufferPosition++;
// }
// break;
case ConsoleKey.LeftArrow:
if (currentBufferPosition > 0)
{
var leftOfCursor = _inputBuffer.ToString().Substring(0, currentBufferPosition).TrimEnd(' ');
var last = leftOfCursor.LastIndexOf(' ');
if (last != -1)
SetCursorPosition(last + _startLocation.Left + 1, CursorTop);
else
SetCursorPosition(_startLocation.Left, CursorTop);
}
break;
case ConsoleKey.RightArrow:
var l2 = _inputBuffer.ToString().IndexOf(' ', currentBufferPosition);
if (l2 != -1)
{
while (_inputBuffer.ToString().Length > l2 + 1 && _inputBuffer.ToString()[l2 + 1] == ' ')
l2++;
SetCursorPosition(l2 + _startLocation.Left + 1, CursorTop);
}
else
{
SetCursorPosition(_inputBuffer.ToString().Length + _startLocation.Left, CursorTop);
}
break;
default:
Trace.TraceWarning("No action for ctrl-" + readKey.Key);
break;
}
}
else
{
switch (readKey.Key)
{
case ConsoleKey.Enter:
return Enter(selection);
case ConsoleKey.LeftArrow:
if (currentBufferPosition == 0) continue;
MoveCursorLeft();
break;
case ConsoleKey.RightArrow:
if (currentBufferPosition == _inputBuffer.Length) continue;
MoveCursorRight();
break;
case ConsoleKey.Home:
MoveCursorToStart(_startLocation);
break;
case ConsoleKey.End:
MoveCursorToEnd(_startLocation, _inputBuffer);
break;
case ConsoleKey.DownArrow:
case ConsoleKey.UpArrow:
RecallCommandHistory(readKey, _inputBuffer);
break;
case ConsoleKey.Delete:
if (currentBufferPosition == _inputBuffer.Length) continue;
MoveBufferLeft(new Location(currentScreenLocation.Left + 1, currentScreenLocation.Top), _inputBuffer, _startLocation);
_inputBuffer.RemoveAt(currentBufferPosition);
CurrentBufferLineCount = (int)Math.Ceiling((decimal)(_inputBuffer.Length - BufferWidth + _startLocation.Left + 1) / BufferWidth);
break;
case ConsoleKey.Backspace:
if (currentBufferPosition == 0) continue;
MoveBufferLeft(currentScreenLocation, _inputBuffer, _startLocation);
_inputBuffer.RemoveAt(currentBufferPosition - 1);
MoveCursorLeft();
CurrentBufferLineCount = (int)Math.Ceiling((decimal)(_inputBuffer.Length - BufferWidth + _startLocation.Left + 1) / BufferWidth);
break;
case ConsoleKey.Escape:
if (allowEscape)
{
if (_inputBuffer.IsEmpty)
{
_console.Output(new WriteEventArgs(null));
throw new CommandEscapeException();
}
}
else
{
}
Clear(_inputBuffer);
break;
case ConsoleKey.Tab:
if (selection != null)
{
CommandTreeNode<T> s;
if (_selection == null)
{
s = selection.Select(_inputBuffer.ToString());
}
else
{
if (readKey.Modifiers == ConsoleModifiers.Shift)
s = selection.Previous(_selection as CommandTreeNode<T>);
else
s = selection.Next(_selection as CommandTreeNode<T>);
}
if (s != null)
{
Clear(_inputBuffer);
_console.Output(new WriteEventArgs(s.FullValuePath, OutputLevel.Default, null, null, false, false));
_inputBuffer.Add(s.FullValuePath);
CurrentBufferLineCount = (int)Math.Ceiling((decimal)(_inputBuffer.Length - BufferWidth + _startLocation.Left + 1) / BufferWidth);
_selection = s;
}
}
break;
case ConsoleKey.PageUp:
case ConsoleKey.PageDown:
case ConsoleKey.LeftWindows:
case ConsoleKey.RightWindows:
case ConsoleKey.Applications:
case ConsoleKey.Insert:
case ConsoleKey.F1:
case ConsoleKey.F2:
case ConsoleKey.F3:
case ConsoleKey.F4:
case ConsoleKey.F5:
case ConsoleKey.F6:
case ConsoleKey.F7:
case ConsoleKey.F8:
case ConsoleKey.F9:
case ConsoleKey.F10:
case ConsoleKey.F11:
case ConsoleKey.F12:
case ConsoleKey.F13:
case ConsoleKey.Oem1:
//Ignore
break;
default:
throw new ArgumentOutOfRangeException($"Key {readKey.Key} is not handled ({readKey.KeyChar}).");
}
}
CursorLineOffset = CursorTop - _startLocation.Top;
}
}
catch (OperationCanceledException exception)
{
Trace.TraceWarning(exception.Message);
//NOTE: Operation was cancelled, causing what ever is in the buffer to be returned, or, should an empty selection be returned?
return Enter(selection);
}
catch (CommandEscapeException)
{
throw;
}
catch (Exception exception)
{
Trace.TraceError(exception.Message);
_console.OutputError(exception);
}
}
}
private T Enter<T>(CommandTreeNode<T> selection)
{
var response = GetResponse(selection, _inputBuffer);
RememberCommandHistory(_inputBuffer);
return response;
}
private bool IsOutputKey(ConsoleKeyInfo readKey)
{
if (readKey.Modifiers == ConsoleModifiers.Control)
return false;
switch (readKey.Key)
{
case ConsoleKey.Enter:
case ConsoleKey.LeftArrow:
case ConsoleKey.RightArrow:
case ConsoleKey.Home:
case ConsoleKey.End:
case ConsoleKey.DownArrow:
case ConsoleKey.UpArrow:
case ConsoleKey.Delete:
case ConsoleKey.Backspace:
case ConsoleKey.Escape:
case ConsoleKey.Tab:
case ConsoleKey.PageUp:
case ConsoleKey.PageDown:
case ConsoleKey.LeftWindows:
case ConsoleKey.RightWindows:
case ConsoleKey.Applications:
case ConsoleKey.Insert:
case ConsoleKey.F1:
case ConsoleKey.F2:
case ConsoleKey.F3:
case ConsoleKey.F4:
case ConsoleKey.F5:
case ConsoleKey.F6:
case ConsoleKey.F7:
case ConsoleKey.F8:
case ConsoleKey.F9:
case ConsoleKey.F10:
case ConsoleKey.F11:
case ConsoleKey.F12:
case ConsoleKey.F13:
return false;
case ConsoleKey.Oem1: //This is the : key on an english keyboard
return true;
default:
return true;
}
}
private void RecallCommandHistory(ConsoleKeyInfo readKey, InputBuffer inputBuffer)
{
if (_commandHistory.ContainsKey(_paramName) && _passwordChar == null)
{
var chi = GetNextCommandHistoryIndex(readKey, _commandHistoryIndex);
Clear(inputBuffer);
_commandHistoryIndex = chi;
_console.Output(new WriteEventArgs(_commandHistory[_paramName][_commandHistoryIndex], OutputLevel.Default, null, null, false, false));
inputBuffer.Add(_commandHistory[_paramName][_commandHistoryIndex]);
}
}
private int GetNextCommandHistoryIndex(ConsoleKeyInfo readKey, int commandHistoryIndex)
{
if (commandHistoryIndex == -1)
{
if (readKey.Key == ConsoleKey.UpArrow)
{
commandHistoryIndex = _commandHistory[_paramName].Count - 1;
}
else
{
commandHistoryIndex = 0;
}
}
else if (readKey.Key == ConsoleKey.UpArrow)
{
commandHistoryIndex++;
if (commandHistoryIndex == _commandHistory[_paramName].Count)
{
commandHistoryIndex = 0;
}
}
else if (readKey.Key == ConsoleKey.DownArrow)
{
commandHistoryIndex--;
if (commandHistoryIndex < 0)
{
commandHistoryIndex = _commandHistory[_paramName].Count - 1;
}
}
return commandHistoryIndex;
}
private void RememberCommandHistory(InputBuffer inputBuffer)
{
if (inputBuffer.Length == 0)
{
return;
}
if (!_commandHistory.ContainsKey(_paramName))
{
_commandHistory.Add(_paramName, new List<string>());
}
var inputString = inputBuffer.ToString();
_commandHistory[_paramName].RemoveAll(x => string.Compare(inputString, x, StringComparison.InvariantCulture) == 0);
_commandHistory[_paramName].Add(inputString);
}
private void Clear(InputBuffer inputBuffer)
{
_commandHistoryIndex = -1;
MoveCursorToStart(_startLocation);
_console.Output(new WriteEventArgs(new string(' ', inputBuffer.Length), OutputLevel.Default, null, null, false, false));
MoveCursorToStart(_startLocation);
inputBuffer.Clear();
CurrentBufferLineCount = (int)Math.Ceiling((decimal)(inputBuffer.Length - BufferWidth + _startLocation.Left + 1) / BufferWidth);
}
private T GetResponse<T>(CommandTreeNode<T> selection, InputBuffer inputBuffer)
{
if (_finished) throw new InvalidOperationException("Cannot get response more than once from a single input manager.");
T response;
if (selection != null)
{
if (_selection != null)
{
_console.Output(new WriteEventArgs(null));
var v = _selection as CommandTreeNode<T>;
response = v == null ? default(T) : v.Key;
}
else
{
var items = selection.Subs.Where(x => string.Equals(x.Value, inputBuffer.ToString(), StringComparison.CurrentCultureIgnoreCase)).ToArray();
if (!items.Any())
{
try
{
response = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(inputBuffer.ToString());
_console.Output(new WriteEventArgs(null, OutputLevel.Default));
}
catch (FormatException exception)
{
throw new EntryException("No item match the entry.", exception);
}
catch (Exception exception)
{
throw new EntryException("No item match the entry.", exception);
}
}
else
{
if (items.Count() > 1)
{
throw new EntryException("There are several matches to the entry.");
}
_console.Output(new WriteEventArgs(null, OutputLevel.Default));
response = items.Single().Key;
}
}
}
else
{
response = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(inputBuffer.ToString());
_console.Output(new WriteEventArgs(null));
}
_finished = true;
return response;
}
private void InputBufferChangedEvent(object sender, InputBufferChangedEventArgs e)
{
_selection = null;
}
private void InsertText(Location currentScreenLocation, char input, InputBuffer inputBuffer, int currentBufferPosition, Location startLocation)
{
if (BufferWidth <= 1) throw new ArgumentException("BufferWidth needs to be larger than 1.");
//Check if the text to the right is on more than one line
var charsToTheRight = inputBuffer.Length - currentBufferPosition;
var bufferToTheRight = BufferWidth - currentScreenLocation.Left - startLocation.Left + 1;
if (charsToTheRight > bufferToTheRight)
{
var lines = (int)Math.Ceiling((decimal)(inputBuffer.Length - BufferWidth + startLocation.Left + 1) / BufferWidth);
for (var i = lines; i > 0; i--)
{
_console.MoveBufferArea(0, currentScreenLocation.Top + i - 1 + 1, BufferWidth - 1, 1, 1, currentScreenLocation.Top + i - 1 + 1);
_console.MoveBufferArea(BufferWidth - 1, currentScreenLocation.Top + i - 1, 1, 1, 0, currentScreenLocation.Top + i - 1 + 1);
}
}
_console.MoveBufferArea(currentScreenLocation.Left, currentScreenLocation.Top, BufferWidth - currentScreenLocation.Left, 1, currentScreenLocation.Left + 1, currentScreenLocation.Top);
if (input == 9)
{
_console.Output(new WriteEventArgs(((char)26).ToString(CultureInfo.InvariantCulture), OutputLevel.Default, null, null, false, false));
}
else
{
_console.Output(new WriteEventArgs(_passwordChar?.ToString() ?? input.ToString(), OutputLevel.Default, null, null, false, false));
}
inputBuffer.Insert(currentBufferPosition, input.ToString(CultureInfo.InvariantCulture));
CurrentBufferLineCount = (int)Math.Ceiling((decimal)(inputBuffer.Length - BufferWidth + _startLocation.Left + 1) / BufferWidth);
}
private void MoveBufferLeft(Location currentScreenLocation, InputBuffer inputBuffer, Location startLocation)
{
if (currentScreenLocation.Left == 0)
{
currentScreenLocation = new Location(BufferWidth, currentScreenLocation.Top - 1);
}
var targetLeft = currentScreenLocation.Left - 1;
_console.MoveBufferArea(currentScreenLocation.Left, currentScreenLocation.Top, BufferWidth - currentScreenLocation.Left, 1, targetLeft, currentScreenLocation.Top);
var done = BufferWidth - startLocation.Left;
var line = 1;
while (inputBuffer.Length >= done)
{
_console.MoveBufferArea(0, currentScreenLocation.Top + line, 1, 1, BufferWidth - 1, currentScreenLocation.Top + line - 1);
_console.MoveBufferArea(1, currentScreenLocation.Top + line, BufferWidth - 1, 1, 0, currentScreenLocation.Top + line);
done += BufferWidth;
line++;
}
}
private void MoveCursorToStart(Location startLocation)
{
SetCursorPosition(startLocation.Left, startLocation.Top);
}
private void MoveCursorToEnd(Location startLocation, InputBuffer inputBuffer)
{
var pos = startLocation.Left + inputBuffer.Length;
var ln = 0;
while (pos > BufferWidth)
{
ln++;
pos -= BufferWidth;
}
if(pos == BufferWidth)
SetCursorPosition(0, startLocation.Top + ln + 1);
else
SetCursorPosition(pos, startLocation.Top + ln);
}
private void MoveCursorRight()
{
if (CursorLeft == BufferWidth - 1)
{
SetCursorPosition(0, CursorTop + 1);
}
else
{
SetCursorPosition(CursorLeft + 1, CursorTop);
}
}
private void MoveCursorLeft()
{
if (CursorLeft == 0)
{
SetCursorPosition(BufferWidth - 1, CursorTop - 1);
}
else
{
SetCursorPosition(CursorLeft - 1, CursorTop);
}
}
public void Cancel()
{
throw new NotImplementedException();
}
public void Dispose()
{
_console?.Dispose();
}
}
}
| |
//
// PixbufUtils.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
// Larry Ewing <lewing@novell.com>
// Stephane Delcroix <sdelcroix@src.gnome.org>
//
// Copyright (C) 2004-2010 Novell, Inc.
// Copyright (C) 2010 Ruben Vermeersch
// Copyright (C) 2004-2007 Larry Ewing
// Copyright (C) 2006-2009 Stephane Delcroix
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Runtime.InteropServices;
using Cairo;
using Gdk;
using FSpot.Cms;
using FSpot.Core;
using FSpot.Utils;
using FSpot.Imaging;
using FSpot.UI.Dialog;
using Hyena;
using TagLib.Image;
using Pinta.Core;
using Pinta.Effects;
public static class PixbufUtils
{
static Pixbuf error_pixbuf = null;
public static Pixbuf ErrorPixbuf {
get {
if (error_pixbuf == null)
error_pixbuf = GtkUtil.TryLoadIcon (FSpot.Core.Global.IconTheme, "f-spot-question-mark", 256, (Gtk.IconLookupFlags)0);
return error_pixbuf;
}
}
public static Pixbuf LoadingPixbuf = PixbufUtils.LoadFromAssembly ("f-spot-loading.png");
public static double Fit (Pixbuf pixbuf,
int dest_width, int dest_height,
bool upscale_smaller,
out int fit_width, out int fit_height)
{
return Fit (pixbuf.Width, pixbuf.Height,
dest_width, dest_height,
upscale_smaller,
out fit_width, out fit_height);
}
public static double Fit (int orig_width, int orig_height,
int dest_width, int dest_height,
bool upscale_smaller,
out int fit_width, out int fit_height)
{
if (orig_width == 0 || orig_height == 0) {
fit_width = 0;
fit_height = 0;
return 0.0;
}
double scale = Math.Min (dest_width / (double)orig_width,
dest_height / (double)orig_height);
if (scale > 1.0 && !upscale_smaller)
scale = 1.0;
fit_width = (int)Math.Round (scale * orig_width);
fit_height = (int)Math.Round (scale * orig_height);
return scale;
}
// FIXME: These should be in GTK#. When my patch is committed, these LoadFrom* methods will
// go away.
public class AspectLoader
{
Gdk.PixbufLoader loader = new Gdk.PixbufLoader ();
int max_width;
int max_height;
ImageOrientation orientation;
public AspectLoader (int max_width, int max_height)
{
this.max_height = max_height;
this.max_width = max_width;
loader.SizePrepared += HandleSizePrepared;
}
private void HandleSizePrepared (object obj, SizePreparedArgs args)
{
switch (orientation) {
case ImageOrientation.LeftTop:
case ImageOrientation.LeftBottom:
case ImageOrientation.RightTop:
case ImageOrientation.RightBottom:
int tmp = max_width;
max_width = max_height;
max_height = tmp;
break;
default:
break;
}
int scale_width = 0;
int scale_height = 0;
double scale = Fit (args.Width, args.Height, max_width, max_height, true, out scale_width, out scale_height);
if (scale < 1.0)
loader.SetSize (scale_width, scale_height);
}
public Pixbuf Load (System.IO.Stream stream, ImageOrientation orientation)
{
int count;
byte [] data = new byte [8192];
while (((count = stream.Read (data, 0, data.Length)) > 0) && loader.Write (data, (ulong)count)) {
;
}
loader.Close ();
Pixbuf orig = loader.Pixbuf;
Gdk.Pixbuf rotated = FSpot.Utils.PixbufUtils.TransformOrientation (orig, orientation);
if (orig != rotated)
orig.Dispose ();
loader.Dispose ();
return rotated;
}
public Pixbuf LoadFromFile (string path)
{
try {
orientation = GetOrientation (new SafeUri (path));
using (FileStream fs = System.IO.File.OpenRead (path)) {
return Load (fs, orientation);
}
} catch (Exception) {
Log.ErrorFormat ("Error loading photo {0}", path);
return null;
}
}
}
public static Pixbuf ScaleToMaxSize (Pixbuf pixbuf, int width, int height, bool upscale = true)
{
int scale_width = 0;
int scale_height = 0;
double scale = Fit (pixbuf, width, height, upscale, out scale_width, out scale_height);
Gdk.Pixbuf result;
if (upscale || (scale < 1.0))
result = pixbuf.ScaleSimple (scale_width, scale_height, (scale_width > 20) ? Gdk.InterpType.Bilinear : Gdk.InterpType.Nearest);
else
result = pixbuf.Copy ();
return result;
}
static public Pixbuf LoadAtMaxSize (string path, int max_width, int max_height)
{
PixbufUtils.AspectLoader loader = new AspectLoader (max_width, max_height);
return loader.LoadFromFile (path);
}
public static Pixbuf TagIconFromPixbuf (Pixbuf source)
{
return IconFromPixbuf (source, (int)Tag.IconSize.Large);
}
public static Pixbuf IconFromPixbuf (Pixbuf source, int size)
{
Pixbuf tmp = null;
Pixbuf icon = null;
if (source.Width > source.Height)
source = tmp = new Pixbuf (source, (source.Width - source.Height) / 2, 0, source.Height, source.Height);
else if (source.Width < source.Height)
source = tmp = new Pixbuf (source, 0, (source.Height - source.Width) / 2, source.Width, source.Width);
if (source.Width == source.Height)
icon = source.ScaleSimple (size, size, InterpType.Bilinear);
else
throw new Exception ("Bad logic leads to bad accidents");
if (tmp != null)
tmp.Dispose ();
return icon;
}
static Pixbuf LoadFromAssembly (string resource)
{
try {
return new Pixbuf (System.Reflection.Assembly.GetEntryAssembly (), resource);
} catch {
return null;
}
}
public static Gdk.Pixbuf ScaleToAspect (Gdk.Pixbuf orig, int width, int height)
{
Gdk.Rectangle pos;
double scale = Fit (orig, width, height, false, out pos.Width, out pos.Height);
pos.X = (width - pos.Width) / 2;
pos.Y = (height - pos.Height) / 2;
Pixbuf scaled = new Pixbuf (Colorspace.Rgb, false, 8, width, height);
scaled.Fill (0x000000);
orig.Composite (scaled, pos.X, pos.Y,
pos.Width, pos.Height,
pos.X, pos.Y, scale, scale,
Gdk.InterpType.Bilinear,
255);
return scaled;
}
public static Pixbuf Flatten (Pixbuf pixbuf)
{
if (!pixbuf.HasAlpha)
return null;
Pixbuf flattened = new Pixbuf (Colorspace.Rgb, false, 8, pixbuf.Width, pixbuf.Height);
pixbuf.CompositeColor (flattened, 0, 0,
pixbuf.Width, pixbuf.Height,
0, 0, 1, 1,
InterpType.Bilinear,
255, 0, 0, 2000, 0xffffff, 0xffffff);
return flattened;
}
unsafe public static byte[] Pixbuf_GetRow (byte* pixels, int row, int rowstride, int width, int channels, byte[] dest)
{
byte* ptr = ((byte*)pixels) + (row * rowstride);
Marshal.Copy (((IntPtr)ptr), dest, 0, width * channels);
return dest;
}
unsafe public static void Pixbuf_SetRow (byte* pixels, byte[] dest, int row, int rowstride, int width, int channels)
{
byte* destPtr = pixels + row * rowstride;
for (int i=0; i < width*channels; i++) {
destPtr [i] = dest [i];
}
}
unsafe public static Pixbuf UnsharpMask (Pixbuf src,
double radius,
double amount,
double threshold,
ThreadProgressDialog progressDialog)
{
// Make sure the pixbuf has an alpha channel before we try to blur it
src = src.AddAlpha (false, 0, 0, 0);
Pixbuf result = Blur (src, (int)radius, progressDialog);
int sourceRowstride = src.Rowstride;
int sourceHeight = src.Height;
int sourceChannels = src.NChannels;
int sourceWidth = src.Width;
int resultRowstride = result.Rowstride;
int resultWidth = result.Width;
int resultChannels = result.NChannels;
byte[] srcRow = new byte[sourceRowstride];
byte[] destRow = new byte[resultRowstride];
byte* sourcePixels = (byte*)src.Pixels;
byte* resultPixels = (byte*)result.Pixels;
for (int row=0; row < sourceHeight; row++) {
Pixbuf_GetRow (sourcePixels, row, sourceRowstride, sourceWidth, sourceChannels, srcRow);
Pixbuf_GetRow (resultPixels, row, resultRowstride, resultWidth, resultChannels, destRow);
int diff;
for (int i=0; i < sourceWidth*sourceChannels; i++) {
diff = srcRow [i] - destRow [i];
if (Math.Abs (2 * diff) < threshold)
diff = 0;
int val = (int)(srcRow [i] + amount * diff);
if (val > 255)
val = 255;
else if (val < 0)
val = 0;
destRow [i] = (byte)val;
}
Pixbuf_SetRow (resultPixels, destRow, row, resultRowstride, resultWidth, resultChannels);
// This is the other half of the progress so start and halfway
if (progressDialog != null)
progressDialog.Fraction = ((double)row / ((double) sourceHeight - 1) ) * 0.25 + 0.75;
}
return result;
}
public static Pixbuf Blur (Pixbuf src, int radius, ThreadProgressDialog dialog)
{
ImageSurface sourceSurface = Hyena.Gui.PixbufImageSurface.Create (src);
ImageSurface destinationSurface = new ImageSurface (Cairo.Format.Rgb24, src.Width, src.Height);
// If we do it as a bunch of single lines (rectangles of one pixel) then we can give the progress
// here instead of going deeper to provide the feedback
for (int i=0; i < src.Height; i++) {
GaussianBlurEffect.RenderBlurEffect (sourceSurface, destinationSurface, new[] { new Gdk.Rectangle (0, i, src.Width, 1) }, radius);
if (dialog != null) {
// This only half of the entire process
double fraction = ((double)i / (double)(src.Height - 1)) * 0.75;
dialog.Fraction = fraction;
}
}
return destinationSurface.ToPixbuf ();
}
public static ImageSurface Clone (this ImageSurface surf)
{
ImageSurface newsurf = new ImageSurface (surf.Format, surf.Width, surf.Height);
using (Context g = new Context (newsurf)) {
g.SetSource (surf);
g.Paint ();
}
return newsurf;
}
public unsafe static Gdk.Pixbuf RemoveRedeye (Gdk.Pixbuf src, Gdk.Rectangle area)
{
return RemoveRedeye (src, area, -15);
}
//threshold, factors and comparisons borrowed from the gimp plugin 'redeye.c' by Robert Merkel
public unsafe static Gdk.Pixbuf RemoveRedeye (Gdk.Pixbuf src, Gdk.Rectangle area, int threshold)
{
Gdk.Pixbuf copy = src.Copy ();
Gdk.Pixbuf selection = new Gdk.Pixbuf (copy, area.X, area.Y, area.Width, area.Height);
byte * spix = (byte *)selection.Pixels;
int h = selection.Height;
int w = selection.Width;
int channels = src.NChannels;
double RED_FACTOR = 0.5133333;
double GREEN_FACTOR = 1;
double BLUE_FACTOR = 0.1933333;
for (int j = 0; j < h; j++) {
byte * s = spix;
for (int i = 0; i < w; i++) {
int adjusted_red = (int)(s [0] * RED_FACTOR);
int adjusted_green = (int)(s [1] * GREEN_FACTOR);
int adjusted_blue = (int)(s [2] * BLUE_FACTOR);
if (adjusted_red >= adjusted_green - threshold
&& adjusted_red >= adjusted_blue - threshold)
s [0] = (byte)(((double)(adjusted_green + adjusted_blue)) / (2.0 * RED_FACTOR));
s += channels;
}
spix += selection.Rowstride;
}
return copy;
}
public static unsafe Pixbuf ColorAdjust (Pixbuf src, double brightness, double contrast,
double hue, double saturation, int src_color, int dest_color)
{
Pixbuf adjusted = new Pixbuf (Colorspace.Rgb, src.HasAlpha, 8, src.Width, src.Height);
PixbufUtils.ColorAdjust (src, adjusted, brightness, contrast, hue, saturation, src_color, dest_color);
return adjusted;
}
public static FSpot.Cms.Format PixbufCmsFormat (Pixbuf buf)
{
return buf.HasAlpha ? FSpot.Cms.Format.Rgba8Planar : FSpot.Cms.Format.Rgb8;
}
public static unsafe void ColorAdjust (Pixbuf src, Pixbuf dest,
double brightness, double contrast,
double hue, double saturation,
int src_color, int dest_color)
{
if (src.Width != dest.Width || src.Height != dest.Height)
throw new Exception ("Invalid Dimensions");
var srgb = Profile.CreateStandardRgb ();
var bchsw = Profile.CreateAbstract (256,
0.0,
brightness, contrast,
hue, saturation, src_color,
dest_color);
Profile [] list = { srgb, bchsw, srgb };
var trans = new Transform (list,
PixbufCmsFormat (src),
PixbufCmsFormat (dest),
Intent.Perceptual, 0x0100);
ColorAdjust (src, dest, trans);
trans.Dispose ();
srgb.Dispose ();
bchsw.Dispose ();
}
public static unsafe void ColorAdjust (Gdk.Pixbuf src, Gdk.Pixbuf dest, Transform trans)
{
int width = src.Width;
byte * srcpix = (byte *)src.Pixels;
byte * destpix = (byte *)dest.Pixels;
for (int row = 0; row < src.Height; row++) {
trans.Apply ((IntPtr)(srcpix + row * src.Rowstride),
(IntPtr)(destpix + row * dest.Rowstride),
(uint)width);
}
}
public static unsafe bool IsGray (Gdk.Pixbuf pixbuf, int max_difference)
{
int chan = pixbuf.NChannels;
byte * pix = (byte *)pixbuf.Pixels;
int h = pixbuf.Height;
int w = pixbuf.Width;
int stride = pixbuf.Rowstride;
for (int j = 0; j < h; j++) {
byte * p = pix;
for (int i = 0; i < w; i++) {
if (Math.Abs (p [0] - p [1]) > max_difference || Math.Abs (p [0] - p [2]) > max_difference)
return false;
p += chan;
}
pix += stride;
}
return true;
}
public static unsafe void ReplaceColor (Gdk.Pixbuf src, Gdk.Pixbuf dest)
{
if (src.HasAlpha || !dest.HasAlpha || (src.Width != dest.Width) || (src.Height != dest.Height))
throw new ApplicationException ("invalid pixbufs");
byte * dpix = (byte *)dest.Pixels;
byte * spix = (byte *)src.Pixels;
int h = src.Height;
int w = src.Width;
for (int j = 0; j < h; j++) {
byte * d = dpix;
byte * s = spix;
for (int i = 0; i < w; i++) {
d [0] = s [0];
d [1] = s [1];
d [2] = s [2];
d += 4;
s += 3;
}
dpix += dest.Rowstride;
spix += src.Rowstride;
}
}
public static ImageOrientation GetOrientation (SafeUri uri)
{
using (var img = ImageFile.Create (uri)) {
return img.Orientation;
}
}
[DllImport("libgnome-desktop-2-17.dll")]
static extern IntPtr gnome_desktop_thumbnail_scale_down_pixbuf (IntPtr pixbuf, int dest_width, int dest_height);
public static Gdk.Pixbuf ScaleDown (Gdk.Pixbuf src, int width, int height)
{
IntPtr raw_ret = gnome_desktop_thumbnail_scale_down_pixbuf (src.Handle, width, height);
Gdk.Pixbuf ret;
if (raw_ret == IntPtr.Zero)
ret = null;
else
ret = (Gdk.Pixbuf)GLib.Object.GetObject (raw_ret, true);
return ret;
}
public static void CreateDerivedVersion (SafeUri source, SafeUri destination)
{
CreateDerivedVersion (source, destination, 95);
}
public static void CreateDerivedVersion (SafeUri source, SafeUri destination, uint jpeg_quality)
{
if (source.GetExtension () == destination.GetExtension ()) {
// Simple copy will do!
var file_from = GLib.FileFactory.NewForUri (source);
var file_to = GLib.FileFactory.NewForUri (destination);
file_from.Copy (file_to, GLib.FileCopyFlags.AllMetadata | GLib.FileCopyFlags.Overwrite, null, null);
return;
}
// Else make a derived copy with metadata copied
using (var img = ImageFile.Create (source)) {
using (var pixbuf = img.Load ()) {
CreateDerivedVersion (source, destination, jpeg_quality, pixbuf);
}
}
}
public static void CreateDerivedVersion (SafeUri source, SafeUri destination, uint jpeg_quality, Pixbuf pixbuf)
{
SaveToSuitableFormat (destination, pixbuf, jpeg_quality);
using (var metadata_from = Metadata.Parse (source)) {
using (var metadata_to = Metadata.Parse (destination)) {
metadata_to.CopyFrom (metadata_from);
// Reset orientation to make sure images appear upright.
metadata_to.ImageTag.Orientation = ImageOrientation.TopLeft;
metadata_to.Save ();
}
}
}
private static void SaveToSuitableFormat (SafeUri destination, Pixbuf pixbuf, uint jpeg_quality)
{
// FIXME: this needs to work on streams rather than filenames. Do that when we switch to
// newer GDK.
var extension = destination.GetExtension ().ToLower ();
if (extension == ".png")
pixbuf.Save (destination.LocalPath, "png");
else if (extension == ".jpg" || extension == ".jpeg")
pixbuf.Save (destination.LocalPath, "jpeg", jpeg_quality);
else
throw new NotImplementedException ("Saving this file format is not supported");
}
#region Gdk hackery
// This hack below is needed because there is no wrapped version of
// Save which allows specifying the variable arguments (it's not
// possible with p/invoke).
[DllImport("libgdk_pixbuf-2.0-0.dll")]
static extern bool gdk_pixbuf_save (IntPtr raw, IntPtr filename, IntPtr type, out IntPtr error,
IntPtr optlabel1, IntPtr optvalue1, IntPtr dummy);
private static bool Save (this Pixbuf pixbuf, string filename, string type, uint jpeg_quality)
{
IntPtr error = IntPtr.Zero;
IntPtr nfilename = GLib.Marshaller.StringToPtrGStrdup (filename);
IntPtr ntype = GLib.Marshaller.StringToPtrGStrdup (type);
IntPtr optlabel1 = GLib.Marshaller.StringToPtrGStrdup ("quality");
IntPtr optvalue1 = GLib.Marshaller.StringToPtrGStrdup (jpeg_quality.ToString ());
bool ret = gdk_pixbuf_save (pixbuf.Handle, nfilename, ntype, out error, optlabel1, optvalue1, IntPtr.Zero);
GLib.Marshaller.Free (nfilename);
GLib.Marshaller.Free (ntype);
GLib.Marshaller.Free (optlabel1);
GLib.Marshaller.Free (optvalue1);
if (error != IntPtr.Zero)
throw new GLib.GException (error);
return ret;
}
#endregion
}
| |
/*
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.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleans.CodeGeneration;
using Orleans.Runtime;
namespace Orleans.Streams
{
[Serializable]
internal class PubSubGrainState : GrainState
{
public HashSet<PubSubPublisherState> Producers { get; set; }
public HashSet<PubSubSubscriptionState> Consumers { get; set; }
}
[Orleans.Providers.StorageProvider(ProviderName = "PubSubStore")]
internal class PubSubRendezvousGrain : Grain<PubSubGrainState>, IPubSubRendezvousGrain
{
private Logger logger;
private const bool DEBUG_PUB_SUB = false;
private static readonly CounterStatistic counterProducersAdded;
private static readonly CounterStatistic counterProducersRemoved;
private static readonly CounterStatistic counterProducersTotal;
private static readonly CounterStatistic counterConsumersAdded;
private static readonly CounterStatistic counterConsumersRemoved;
private static readonly CounterStatistic counterConsumersTotal;
static PubSubRendezvousGrain()
{
counterProducersAdded = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_ADDED);
counterProducersRemoved = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_REMOVED);
counterProducersTotal = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_TOTAL);
counterConsumersAdded = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_ADDED);
counterConsumersRemoved = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_REMOVED);
counterConsumersTotal = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_TOTAL);
}
public override async Task OnActivateAsync()
{
logger = GetLogger(this.GetType().Name + "-" + RuntimeIdentity + "-" + IdentityString);
LogPubSubCounts("OnActivateAsync");
if (State.Consumers == null)
State.Consumers = new HashSet<PubSubSubscriptionState>();
if (State.Producers == null)
State.Producers = new HashSet<PubSubPublisherState>();
int numRemoved = RemoveDeadProducers();
if (numRemoved > 0)
{
if (State.Producers.Count > 0 || State.Consumers.Count > 0)
await WriteStateAsync();
else
await ClearStateAsync(); //State contains no producers or consumers, remove it from storage
}
if (logger.IsVerbose)
logger.Info("OnActivateAsync-Done");
}
public override Task OnDeactivateAsync()
{
LogPubSubCounts("OnDeactivateAsync");
return TaskDone.Done;
}
private int RemoveDeadProducers()
{
// Remove only those we know for sure are Dead.
int numRemoved = 0;
if (State.Producers != null && State.Producers.Count > 0)
numRemoved = State.Producers.RemoveWhere(producerState => IsDeadProducer(producerState.Producer));
if (numRemoved > 0)
{
LogPubSubCounts("RemoveDeadProducers: removed {0} outdated producers", numRemoved);
counterProducersRemoved.Increment();
counterProducersTotal.DecrementBy(numRemoved);
}
return numRemoved;
}
/// accept and notify only Active producers.
private static bool IsActiveProducer(IStreamProducerExtension producer)
{
var grainRef = producer as GrainReference;
if (grainRef !=null && grainRef.GrainId.IsSystemTarget && grainRef.IsInitializedSystemTarget)
return RuntimeClient.Current.GetSiloStatus(grainRef.SystemTargetSilo).Equals(SiloStatus.Active);
return true;
}
private static bool IsDeadProducer(IStreamProducerExtension producer)
{
var grainRef = producer as GrainReference;
if (grainRef != null && grainRef.GrainId.IsSystemTarget && grainRef.IsInitializedSystemTarget)
return RuntimeClient.Current.GetSiloStatus(grainRef.SystemTargetSilo).Equals(SiloStatus.Dead);
return false;
}
public async Task<ISet<PubSubSubscriptionState>> RegisterProducer(StreamId streamId, IStreamProducerExtension streamProducer)
{
if (!IsActiveProducer(streamProducer))
throw new ArgumentException(String.Format("Trying to register non active IStreamProducerExtension: {0}", streamProducer.ToString()), "streamProducer");
RemoveDeadProducers();
var publisherState = new PubSubPublisherState(streamId, streamProducer);
State.Producers.Add(publisherState);
counterProducersAdded.Increment();
counterProducersTotal.Increment();
LogPubSubCounts("RegisterProducer {0}", streamProducer);
await WriteStateAsync();
return State.Consumers.Where(c => !c.IsFaulted).ToSet();
}
public async Task UnregisterProducer(StreamId streamId, IStreamProducerExtension streamProducer)
{
int numRemoved = State.Producers.RemoveWhere(s => s.Equals(streamId, streamProducer));
counterProducersRemoved.Increment();
counterProducersTotal.DecrementBy(numRemoved);
LogPubSubCounts("UnregisterProducer {0} NumRemoved={1}", streamProducer, numRemoved);
if (numRemoved > 0)
await WriteStateAsync();
if (State.Producers.Count == 0 && State.Consumers.Count == 0)
{
await ClearStateAsync(); //State contains no producers or consumers, remove it from storage
DeactivateOnIdle(); // No producers or consumers left now, so flag ourselves to expedite Deactivation
}
}
public async Task RegisterConsumer(
GuidId subscriptionId,
StreamId streamId,
IStreamConsumerExtension streamConsumer,
IStreamFilterPredicateWrapper filter)
{
PubSubSubscriptionState pubSubState = State.Consumers.FirstOrDefault(s => s.Equals(subscriptionId));
if (pubSubState == null)
{
pubSubState = new PubSubSubscriptionState(subscriptionId, streamId, streamConsumer, filter);
State.Consumers.Add(pubSubState);
}
if (pubSubState.IsFaulted)
throw new FaultedSubscriptionException(subscriptionId, streamId);
if (filter != null)
pubSubState.AddFilter(filter);
counterConsumersAdded.Increment();
counterConsumersTotal.Increment();
LogPubSubCounts("RegisterConsumer {0}", streamConsumer);
await WriteStateAsync();
int numProducers = State.Producers.Count;
if (numProducers > 0)
{
if (logger.IsVerbose)
logger.Info("Notifying {0} existing producer(s) about new consumer {1}. Producers={2}",
numProducers, streamConsumer, Utils.EnumerableToString(State.Producers));
// Notify producers about a new streamConsumer.
var tasks = new List<Task>();
var producers = State.Producers.ToList();
bool someProducersRemoved = false;
foreach (var producerState in producers)
{
PubSubPublisherState producer = producerState; // Capture loop variable
if (!IsActiveProducer(producer.Producer))
{
// Producer is not active (could be stopping / shutting down) so skip
if (logger.IsVerbose) logger.Verbose("Producer {0} on stream {1} is not active - skipping.", producer, streamId);
continue;
}
Task addSubscriberPromise = producer.Producer.AddSubscriber(subscriptionId, streamId, streamConsumer, filter)
.ContinueWith(t =>
{
if (t.IsFaulted)
{
var exc = t.Exception.GetBaseException();
if (exc is GrainExtensionNotInstalledException)
{
logger.Warn((int) ErrorCode.Stream_ProducerIsDead,
"Producer {0} on stream {1} is no longer active - discarding.",
producer, streamId);
// This publisher has gone away, so we should cleanup pub-sub state.
bool removed = State.Producers.Remove(producer);
someProducersRemoved = true; // Re-save state changes at end
counterProducersRemoved.Increment();
counterProducersTotal.DecrementBy(removed ? 1 : 0);
// And ignore this error
}
else
{
throw exc;
}
}
}, TaskContinuationOptions.OnlyOnFaulted);
tasks.Add(addSubscriberPromise);
}
Exception exception = null;
try
{
await Task.WhenAll(tasks);
}
catch (Exception exc)
{
exception = exc;
}
if (someProducersRemoved)
await WriteStateAsync();
if (exception != null)
throw exception;
}
}
public async Task UnregisterConsumer(GuidId subscriptionId, StreamId streamId)
{
if(State.Consumers.Any(c => c.IsFaulted && c.Equals(subscriptionId)))
throw new FaultedSubscriptionException(subscriptionId, streamId);
int numRemoved = State.Consumers.RemoveWhere(c => c.Equals(subscriptionId));
counterConsumersRemoved.Increment();
counterConsumersTotal.DecrementBy(numRemoved);
LogPubSubCounts("UnregisterSubscription {0} NumRemoved={1}", subscriptionId, numRemoved);
await WriteStateAsync();
await NotifyProducersOfRemovedSubscription(subscriptionId, streamId);
await ClearStateWhenEmpty();
}
public Task<int> ProducerCount(StreamId streamId)
{
return Task.FromResult(State.Producers.Count);
}
public Task<int> ConsumerCount(StreamId streamId)
{
return Task.FromResult(GetConsumersForStream(streamId).Length);
}
public Task<PubSubSubscriptionState[]> DiagGetConsumers(StreamId streamId)
{
return Task.FromResult(GetConsumersForStream(streamId));
}
private PubSubSubscriptionState[] GetConsumersForStream(StreamId streamId)
{
return State.Consumers.Where(c => !c.IsFaulted && c.Stream.Equals(streamId)).ToArray();
}
private void LogPubSubCounts(string fmt, params object[] args)
{
if (logger.IsVerbose || DEBUG_PUB_SUB)
{
int numProducers = 0;
int numConsumers = 0;
if (State != null && State.Producers != null)
numProducers = State.Producers.Count;
if (State != null && State.Consumers != null)
numConsumers = State.Consumers.Count;
string when = args != null && args.Length != 0 ? String.Format(fmt, args) : fmt;
logger.Info("{0}. Now have total of {1} producers and {2} consumers. All Consumers = {3}, All Producers = {4}",
when, numProducers, numConsumers, Utils.EnumerableToString(State.Consumers), Utils.EnumerableToString(State.Producers));
}
}
// Check that what we have cached locally matches what is in the persistent table.
public async Task Validate()
{
var captureProducers = State.Producers;
var captureConsumers = State.Consumers;
await ReadStateAsync();
if (captureProducers.Count != State.Producers.Count)
{
throw new Exception(String.Format("State mismatch between PubSubRendezvousGrain and its persistent state. captureProducers.Count={0}, State.Producers.Count={1}",
captureProducers.Count, State.Producers.Count));
}
foreach (var producer in captureProducers)
if (!State.Producers.Contains(producer))
throw new Exception(String.Format("State mismatch between PubSubRendezvousGrain and its persistent state. captureProducers={0}, State.Producers={1}",
Utils.EnumerableToString(captureProducers), Utils.EnumerableToString(State.Producers)));
if (captureConsumers.Count != State.Consumers.Count)
{
LogPubSubCounts("Validate: Consumer count mismatch");
throw new Exception(String.Format("State mismatch between PubSubRendezvousGrain and its persistent state. captureConsumers.Count={0}, State.Consumers.Count={1}",
captureConsumers.Count, State.Consumers.Count));
}
foreach (PubSubSubscriptionState consumer in captureConsumers)
if (!State.Consumers.Contains(consumer))
throw new Exception(String.Format("State mismatch between PubSubRendezvousGrain and its persistent state. captureConsumers={0}, State.Consumers={1}",
Utils.EnumerableToString(captureConsumers), Utils.EnumerableToString(State.Consumers)));
}
public Task<List<GuidId>> GetAllSubscriptions(StreamId streamId, IStreamConsumerExtension streamConsumer)
{
List<GuidId> subscriptionIds = State.Consumers.Where(c => !c.IsFaulted && c.Consumer.Equals(streamConsumer))
.Select(c => c.SubscriptionId)
.ToList();
return Task.FromResult(subscriptionIds);
}
public async Task FaultSubscription(GuidId subscriptionId)
{
PubSubSubscriptionState pubSubState = State.Consumers.FirstOrDefault(s => s.Equals(subscriptionId));
if (pubSubState == null)
{
return;
}
pubSubState.Fault();
if (logger.IsVerbose) logger.Verbose("Setting subscription {0} to a faulted state.", subscriptionId.Guid);
await WriteStateAsync();
await NotifyProducersOfRemovedSubscription(pubSubState.SubscriptionId, pubSubState.Stream);
await ClearStateWhenEmpty();
}
private async Task NotifyProducersOfRemovedSubscription(GuidId subscriptionId, StreamId streamId)
{
int numProducers = State.Producers.Count;
if (numProducers > 0)
{
if (logger.IsVerbose) logger.Verbose("Notifying {0} existing producers about unregistered consumer.", numProducers);
// Notify producers about unregistered consumer.
var tasks = new List<Task>();
foreach (var producerState in State.Producers.Where(producerState => IsActiveProducer(producerState.Producer)))
tasks.Add(producerState.Producer.RemoveSubscriber(subscriptionId, streamId));
await Task.WhenAll(tasks);
}
}
private async Task ClearStateWhenEmpty()
{
if (State.Producers.Count == 0 && State.Consumers.Count == 0) // + we already know that numProducers == 0 from previous if-clause
{
await ClearStateAsync(); //State contains no producers or consumers, remove it from storage
// No producers or consumers left now, so flag ourselves to expedite Deactivation
DeactivateOnIdle();
}
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.dll Alpha
// Description: A library module for the DotSpatial geospatial framework for .Net.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 11/12/2008 1:58:22 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Windows.Forms;
namespace DotSpatial.Data.Forms
{
/// <summary>
/// DirectoryView
/// </summary>
public class DirectoryView : ScrollingControl
{
#region Private Variables
/// <summary>
/// Designer variable
/// </summary>
//private IContainer components = null; // the members to be contained
private string _directory;
private List<DirectoryItem> _items;
private DirectoryItem _selectedItem; // the most recently selected
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of DirectoryView
/// </summary>
public DirectoryView()
{
_items = new List<DirectoryItem>();
InitializeComponent();
}
#endregion
#region Methods
#endregion
#region Properties
/// <summary>
/// Gets or sets the selected item. In cases of a multiple select, this is the
/// last member added to the selection.
/// </summary>
public DirectoryItem SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value;
Invalidate();
}
}
/// <summary>
/// Gets or sets the string path that should be itemized in the view.
/// </summary>
public string Directory
{
get { return _directory; }
set
{
_directory = value;
UpdateContent();
}
}
/// <summary>
/// Gets or sets the collection of DirectoryItems to draw in this control
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public List<DirectoryItem> Items
{
get { return _items; }
set { _items = value; }
}
/// <summary>
/// Draws
/// </summary>
/// <param name="e"></param>
protected override void OnInitialize(PaintEventArgs e)
{
UpdateContent();
// translate into document coordinates
Matrix oldMat = e.Graphics.Transform;
Matrix mat = new Matrix();
e.Graphics.Transform = mat;
foreach (DirectoryItem item in _items)
{
if (ControlRectangle.IntersectsWith(item.Bounds))
{
item.Draw(e);
}
}
e.Graphics.Transform = oldMat;
base.OnInitialize(e);
}
#endregion
#region Protected Methods
/// <summary>
/// Gets or sets the Font to be used for all of the items in this view.
/// </summary>
[Category("Appearance"), Description("Gets or sets the Font to be used for all of the items in this view.")]
public override Font Font
{
get
{
return base.Font;
}
set
{
base.Font = value;
UpdateContent();
}
}
/// <summary>
/// Handles the situation where the mouse has been pressed down.
/// </summary>
/// <param name="e"></param>
protected override void OnMouseDown(MouseEventArgs e)
{
foreach (DirectoryItem di in _items)
{
if (di.Bounds.Contains(e.Location))
{
di.IsSelected = true;
RefreshItem(di);
Invalidate(DocumentToClient(di.Bounds));
}
}
base.OnMouseDown(e);
}
/// <summary>
/// Updates the buffer in order to correctly re-draw this item, if it is on the page, and then invalidates
/// the area where this will be drawn.
/// </summary>
/// <param name="item">The directory item to invalidate</param>
public void RefreshItem(DirectoryItem item)
{
Graphics g = Graphics.FromImage(Page);
Brush b = new SolidBrush(item.BackColor);
g.FillRectangle(b, DocumentToClient(item.Bounds));
b.Dispose();
// first translate into document coordinates
Matrix mat = new Matrix();
mat.Translate(ClientRectangle.X, ClientRectangle.Y);
g.Transform = mat;
item.Draw(new PaintEventArgs(g, item.Bounds));
g.Dispose();
}
///// <summary>
///// This handles drawing but extends the
///// </summary>
///// <param name="e"></param>
//protected override void OnDraw(PaintEventArgs e)
//{
// base.OnDraw(e);
// foreach (DirectoryItem item in _items)
// {
// item.Draw(e);
// }
//}
#endregion
private void InitializeComponent()
{
}
/// <summary>
/// Removes the existing Directory Items from the control
/// </summary>
public virtual void Clear()
{
if (_items != null) _items.Clear();
}
/// <summary>
/// Causes the control to refresh the current content.
/// </summary>
public void UpdateContent()
{
if (Controls == null) return;
SuspendLayout();
int tp = 1;
Clear();
Graphics g = CreateGraphics();
SizeF fontSize = g.MeasureString("TEST", Font);
int fontHeight = (int)(fontSize.Height + 4);
if (fontHeight < 20) fontHeight = 20;
AddFolders(ref tp, fontHeight);
AddFiles(ref tp, fontHeight);
if (tp < fontHeight * _items.Count) tp = fontHeight * _items.Count;
DocumentRectangle = new Rectangle(DocumentRectangle.X, DocumentRectangle.Y, ClientRectangle.Width, tp);
ResetScroll();
ResumeLayout(false);
}
private void AddFiles(ref int tp, int fontHeight)
{
if (_directory == null) return;
string[] files = System.IO.Directory.GetFiles(_directory);
foreach (string file in files)
{
FileItem fi = new FileItem(file);
if (fi.ItemType == ItemType.Custom) continue;
fi.Top = tp;
fi.Font = Font;
fi.Height = fontHeight;
_items.Add(fi);
tp += fontHeight;
}
}
private void AddFolders(ref int tp, int fontHeight)
{
if (_directory == null) return;
string temp = _directory.Trim(Path.DirectorySeparatorChar);
string[] currentDirectoryParts = temp.Split(Path.DirectorySeparatorChar);
if (currentDirectoryParts.Length > 1)
{
if (_directory != null)
{
DirectoryInfo parent = System.IO.Directory.GetParent(_directory);
if (parent != null)
{
FolderItem up = new FolderItem(parent.FullName);
up.Text = "..";
up.Font = this.Font;
up.Top = tp;
up.Height = fontHeight;
_items.Add(up);
}
}
tp += fontHeight;
}
if (_directory != null)
{
string[] subDirs = System.IO.Directory.GetDirectories(_directory);
if (_items == null) _items = new List<DirectoryItem>();
foreach (string dir in subDirs)
{
FolderItem di = new FolderItem(dir);
di.Font = this.Font;
di.Top = tp;
di.Height = fontHeight;
//di.Navigate += new EventHandler<NavigateEventArgs>(item_Navigate);
//di.SelectChanged += new EventHandler<SelectEventArgs>(item_SelectChanged);
_items.Add(di);
tp += fontHeight;
}
}
}
}
}
| |
// 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.IO;
using System.Text;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Diagnostics;
using System.Globalization;
using System.Collections;
using System.Security.Policy;
using System.Collections.Generic;
using System.Runtime.Versioning;
using System.Threading.Tasks;
namespace System.Xml
{
internal partial class XsdValidatingReader : XmlReader, IXmlSchemaInfo, IXmlLineInfo, IXmlNamespaceResolver
{
// Gets the text value of the current node.
public override Task<string> GetValueAsync()
{
if ((int)_validationState < 0)
{
return Task.FromResult(_cachedNode.RawValue);
}
return _coreReader.GetValueAsync();
}
public override Task<object> ReadContentAsObjectAsync()
{
if (!CanReadContentAs(this.NodeType))
{
throw CreateReadContentAsException(nameof(ReadContentAsObject));
}
return InternalReadContentAsObjectAsync(true);
}
public override async Task<string> ReadContentAsStringAsync()
{
if (!CanReadContentAs(this.NodeType))
{
throw CreateReadContentAsException(nameof(ReadContentAsString));
}
object typedValue = await InternalReadContentAsObjectAsync().ConfigureAwait(false);
XmlSchemaType xmlType = NodeType == XmlNodeType.Attribute ? AttributeXmlType : ElementXmlType;
try
{
if (xmlType != null)
{
return xmlType.ValueConverter.ToString(typedValue);
}
else
{
return typedValue as string;
}
}
catch (InvalidCastException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo);
}
catch (FormatException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo);
}
catch (OverflowException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo);
}
}
public override async Task<object> ReadContentAsAsync(Type returnType, IXmlNamespaceResolver namespaceResolver)
{
if (!CanReadContentAs(this.NodeType))
{
throw CreateReadContentAsException(nameof(ReadContentAs));
}
string originalStringValue;
var tuple_0 = await InternalReadContentAsObjectTupleAsync(false).ConfigureAwait(false);
originalStringValue = tuple_0.Item1;
object typedValue = tuple_0.Item2;
XmlSchemaType xmlType = NodeType == XmlNodeType.Attribute ? AttributeXmlType : ElementXmlType; //TODO special case for xsd:duration and xsd:dateTime
try
{
if (xmlType != null)
{
// special-case convertions to DateTimeOffset; typedValue is by default a DateTime
// which cannot preserve time zone, so we need to convert from the original string
if (returnType == typeof(DateTimeOffset) && xmlType.Datatype is Datatype_dateTimeBase)
{
typedValue = originalStringValue;
}
return xmlType.ValueConverter.ChangeType(typedValue, returnType);
}
else
{
return XmlUntypedConverter.Untyped.ChangeType(typedValue, returnType, namespaceResolver);
}
}
catch (FormatException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo);
}
catch (InvalidCastException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo);
}
catch (OverflowException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo);
}
}
public override async Task<object> ReadElementContentAsObjectAsync()
{
if (this.NodeType != XmlNodeType.Element)
{
throw CreateReadElementContentAsException(nameof(ReadElementContentAsObject));
}
var tuple_1 = await InternalReadElementContentAsObjectAsync(true).ConfigureAwait(false);
return tuple_1.Item2;
}
public override async Task<string> ReadElementContentAsStringAsync()
{
if (this.NodeType != XmlNodeType.Element)
{
throw CreateReadElementContentAsException(nameof(ReadElementContentAsString));
}
XmlSchemaType xmlType;
var tuple_9 = await InternalReadElementContentAsObjectAsync().ConfigureAwait(false);
xmlType = tuple_9.Item1;
object typedValue = tuple_9.Item2;
try
{
if (xmlType != null)
{
return xmlType.ValueConverter.ToString(typedValue);
}
else
{
return typedValue as string;
}
}
catch (InvalidCastException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo);
}
catch (FormatException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo);
}
catch (OverflowException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo);
}
}
public override async Task<object> ReadElementContentAsAsync(Type returnType, IXmlNamespaceResolver namespaceResolver)
{
if (this.NodeType != XmlNodeType.Element)
{
throw CreateReadElementContentAsException(nameof(ReadElementContentAs));
}
XmlSchemaType xmlType;
string originalStringValue;
var tuple_10 = await InternalReadElementContentAsObjectTupleAsync(false).ConfigureAwait(false);
xmlType = tuple_10.Item1;
originalStringValue = tuple_10.Item2;
object typedValue = tuple_10.Item3;
try
{
if (xmlType != null)
{
// special-case convertions to DateTimeOffset; typedValue is by default a DateTime
// which cannot preserve time zone, so we need to convert from the original string
if (returnType == typeof(DateTimeOffset) && xmlType.Datatype is Datatype_dateTimeBase)
{
typedValue = originalStringValue;
}
return xmlType.ValueConverter.ChangeType(typedValue, returnType, namespaceResolver);
}
else
{
return XmlUntypedConverter.Untyped.ChangeType(typedValue, returnType, namespaceResolver);
}
}
catch (FormatException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo);
}
catch (InvalidCastException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo);
}
catch (OverflowException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo);
}
}
private Task<bool> ReadAsync_Read(Task<bool> task)
{
if (task.IsSuccess())
{
if (task.Result)
{
return ProcessReaderEventAsync().ReturnTrueTaskWhenFinishAsync();
}
else
{
_validator.EndValidation();
if (_coreReader.EOF)
{
_validationState = ValidatingReaderState.EOF;
}
return AsyncHelper.DoneTaskFalse;
}
}
else
{
return _ReadAsync_Read(task);
}
}
private async Task<bool> _ReadAsync_Read(Task<bool> task)
{
if (await task.ConfigureAwait(false))
{
await ProcessReaderEventAsync().ConfigureAwait(false);
return true;
}
else
{
_validator.EndValidation();
if (_coreReader.EOF)
{
_validationState = ValidatingReaderState.EOF;
}
return false;
}
}
private Task<bool> ReadAsync_ReadAhead(Task task)
{
if (task.IsSuccess())
{
_validationState = ValidatingReaderState.Read;
return AsyncHelper.DoneTaskTrue; ;
}
else
{
return _ReadAsync_ReadAhead(task);
}
}
private async Task<bool> _ReadAsync_ReadAhead(Task task)
{
await task.ConfigureAwait(false);
_validationState = ValidatingReaderState.Read;
return true;
}
// Reads the next node from the stream/TextReader.
public override Task<bool> ReadAsync()
{
switch (_validationState)
{
case ValidatingReaderState.Read:
Task<bool> readTask = _coreReader.ReadAsync();
return ReadAsync_Read(readTask);
case ValidatingReaderState.ParseInlineSchema:
return ProcessInlineSchemaAsync().ReturnTrueTaskWhenFinishAsync();
case ValidatingReaderState.OnAttribute:
case ValidatingReaderState.OnDefaultAttribute:
case ValidatingReaderState.ClearAttributes:
case ValidatingReaderState.OnReadAttributeValue:
ClearAttributesInfo();
if (_inlineSchemaParser != null)
{
_validationState = ValidatingReaderState.ParseInlineSchema;
goto case ValidatingReaderState.ParseInlineSchema;
}
else
{
_validationState = ValidatingReaderState.Read;
goto case ValidatingReaderState.Read;
}
case ValidatingReaderState.ReadAhead: //Will enter here on calling Skip()
ClearAttributesInfo();
Task task = ProcessReaderEventAsync();
return ReadAsync_ReadAhead(task);
case ValidatingReaderState.OnReadBinaryContent:
_validationState = _savedState;
return _readBinaryHelper.FinishAsync().CallBoolTaskFuncWhenFinishAsync(thisRef => thisRef.ReadAsync(), this);
case ValidatingReaderState.Init:
_validationState = ValidatingReaderState.Read;
if (_coreReader.ReadState == ReadState.Interactive)
{ //If the underlying reader is already positioned on a ndoe, process it
return ProcessReaderEventAsync().ReturnTrueTaskWhenFinishAsync();
}
else
{
goto case ValidatingReaderState.Read;
}
case ValidatingReaderState.ReaderClosed:
case ValidatingReaderState.EOF:
return AsyncHelper.DoneTaskFalse;
default:
return AsyncHelper.DoneTaskFalse;
}
}
// Skips to the end tag of the current element.
public override async Task SkipAsync()
{
int startDepth = Depth;
switch (NodeType)
{
case XmlNodeType.Element:
if (_coreReader.IsEmptyElement)
{
break;
}
bool callSkipToEndElem = true;
//If union and unionValue has been parsed till EndElement, then validator.ValidateEndElement has been called
//Hence should not call SkipToEndElement as the current context has already been popped in the validator
if ((_xmlSchemaInfo.IsUnionType || _xmlSchemaInfo.IsDefault) && _coreReader is XsdCachingReader)
{
callSkipToEndElem = false;
}
await _coreReader.SkipAsync().ConfigureAwait(false);
_validationState = ValidatingReaderState.ReadAhead;
if (callSkipToEndElem)
{
_validator.SkipToEndElement(_xmlSchemaInfo);
}
break;
case XmlNodeType.Attribute:
MoveToElement();
goto case XmlNodeType.Element;
}
//For all other NodeTypes Skip() same as Read()
await ReadAsync().ConfigureAwait(false);
return;
}
public override async Task<int> ReadContentAsBase64Async(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (_validationState != ValidatingReaderState.OnReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
_savedState = _validationState;
}
// restore original state in order to have a normal Read() behavior when called from readBinaryHelper
_validationState = _savedState;
// call to the helper
int readCount = await _readBinaryHelper.ReadContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
// set OnReadBinaryContent state again and return
_savedState = _validationState;
_validationState = ValidatingReaderState.OnReadBinaryContent;
return readCount;
}
public override async Task<int> ReadContentAsBinHexAsync(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (_validationState != ValidatingReaderState.OnReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
_savedState = _validationState;
}
// restore original state in order to have a normal Read() behavior when called from readBinaryHelper
_validationState = _savedState;
// call to the helper
int readCount = await _readBinaryHelper.ReadContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
// set OnReadBinaryContent state again and return
_savedState = _validationState;
_validationState = ValidatingReaderState.OnReadBinaryContent;
return readCount;
}
public override async Task<int> ReadElementContentAsBase64Async(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (_validationState != ValidatingReaderState.OnReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
_savedState = _validationState;
}
// restore original state in order to have a normal Read() behavior when called from readBinaryHelper
_validationState = _savedState;
// call to the helper
int readCount = await _readBinaryHelper.ReadElementContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
// set OnReadBinaryContent state again and return
_savedState = _validationState;
_validationState = ValidatingReaderState.OnReadBinaryContent;
return readCount;
}
public override async Task<int> ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (_validationState != ValidatingReaderState.OnReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
_savedState = _validationState;
}
// restore original state in order to have a normal Read() behavior when called from readBinaryHelper
_validationState = _savedState;
// call to the helper
int readCount = await _readBinaryHelper.ReadElementContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
// set OnReadBinaryContent state again and return
_savedState = _validationState;
_validationState = ValidatingReaderState.OnReadBinaryContent;
return readCount;
}
private Task ProcessReaderEventAsync()
{
if (_replayCache)
{ //if in replay mode, do nothing since nodes have been validated already
//If NodeType == XmlNodeType.EndElement && if manageNamespaces, may need to pop namespace scope, since scope is not popped in ReadAheadForMemberType
return Task.CompletedTask;
}
switch (_coreReader.NodeType)
{
case XmlNodeType.Element:
return ProcessElementEventAsync();
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
_validator.ValidateWhitespace(GetStringValue);
break;
case XmlNodeType.Text: // text inside a node
case XmlNodeType.CDATA: // <![CDATA[...]]>
_validator.ValidateText(GetStringValue);
break;
case XmlNodeType.EndElement:
return ProcessEndElementEventAsync();
case XmlNodeType.EntityReference:
throw new InvalidOperationException();
case XmlNodeType.DocumentType:
#if TEMP_HACK_FOR_SCHEMA_INFO
validator.SetDtdSchemaInfo((SchemaInfo)coreReader.DtdInfo);
#else
_validator.SetDtdSchemaInfo(_coreReader.DtdInfo);
#endif
break;
default:
break;
}
return Task.CompletedTask;
}
// SxS: This function calls ValidateElement on XmlSchemaValidator which is annotated with ResourceExposure attribute.
// Since the resource names (namespace location) are not provided directly by the user (they are read from the source
// document) and the function does not expose any resources it is fine to suppress the SxS warning.
private async Task ProcessElementEventAsync()
{
if (_processInlineSchema && IsXSDRoot(_coreReader.LocalName, _coreReader.NamespaceURI) && _coreReader.Depth > 0)
{
_xmlSchemaInfo.Clear();
_attributeCount = _coreReaderAttributeCount = _coreReader.AttributeCount;
if (!_coreReader.IsEmptyElement)
{ //If its not empty schema, then parse else ignore
_inlineSchemaParser = new Parser(SchemaType.XSD, _coreReaderNameTable, _validator.SchemaSet.GetSchemaNames(_coreReaderNameTable), _validationEvent);
await _inlineSchemaParser.StartParsingAsync(_coreReader, null).ConfigureAwait(false);
_inlineSchemaParser.ParseReaderNode();
_validationState = ValidatingReaderState.ParseInlineSchema;
}
else
{
_validationState = ValidatingReaderState.ClearAttributes;
}
}
else
{ //Validate element
//Clear previous data
_atomicValue = null;
_originalAtomicValueString = null;
_xmlSchemaInfo.Clear();
if (_manageNamespaces)
{
_nsManager.PushScope();
}
//Find Xsi attributes that need to be processed before validating the element
string xsiSchemaLocation = null;
string xsiNoNamespaceSL = null;
string xsiNil = null;
string xsiType = null;
if (_coreReader.MoveToFirstAttribute())
{
do
{
string objectNs = _coreReader.NamespaceURI;
string objectName = _coreReader.LocalName;
if (Ref.Equal(objectNs, _nsXsi))
{
if (Ref.Equal(objectName, _xsiSchemaLocation))
{
xsiSchemaLocation = _coreReader.Value;
}
else if (Ref.Equal(objectName, _xsiNoNamespaceSchemaLocation))
{
xsiNoNamespaceSL = _coreReader.Value;
}
else if (Ref.Equal(objectName, _xsiType))
{
xsiType = _coreReader.Value;
}
else if (Ref.Equal(objectName, _xsiNil))
{
xsiNil = _coreReader.Value;
}
}
if (_manageNamespaces && Ref.Equal(_coreReader.NamespaceURI, _nsXmlNs))
{
_nsManager.AddNamespace(_coreReader.Prefix.Length == 0 ? string.Empty : _coreReader.LocalName, _coreReader.Value);
}
} while (_coreReader.MoveToNextAttribute());
_coreReader.MoveToElement();
}
_validator.ValidateElement(_coreReader.LocalName, _coreReader.NamespaceURI, _xmlSchemaInfo, xsiType, xsiNil, xsiSchemaLocation, xsiNoNamespaceSL);
ValidateAttributes();
_validator.ValidateEndOfAttributes(_xmlSchemaInfo);
if (_coreReader.IsEmptyElement)
{
await ProcessEndElementEventAsync().ConfigureAwait(false);
}
_validationState = ValidatingReaderState.ClearAttributes;
}
}
private async Task ProcessEndElementEventAsync()
{
_atomicValue = _validator.ValidateEndElement(_xmlSchemaInfo);
_originalAtomicValueString = GetOriginalAtomicValueStringOfElement();
if (_xmlSchemaInfo.IsDefault)
{ //The atomicValue returned is a default value
Debug.Assert(_atomicValue != null);
int depth = _coreReader.Depth;
_coreReader = GetCachingReader();
_cachingReader.RecordTextNode(_xmlSchemaInfo.XmlType.ValueConverter.ToString(_atomicValue), _originalAtomicValueString, depth + 1, 0, 0);
_cachingReader.RecordEndElementNode();
await _cachingReader.SetToReplayModeAsync().ConfigureAwait(false);
_replayCache = true;
}
else if (_manageNamespaces)
{
_nsManager.PopScope();
}
}
private async Task ProcessInlineSchemaAsync()
{
Debug.Assert(_inlineSchemaParser != null);
if (await _coreReader.ReadAsync().ConfigureAwait(false))
{
if (_coreReader.NodeType == XmlNodeType.Element)
{
_attributeCount = _coreReaderAttributeCount = _coreReader.AttributeCount;
}
else
{ //Clear attributes info if nodeType is not element
ClearAttributesInfo();
}
if (!_inlineSchemaParser.ParseReaderNode())
{
_inlineSchemaParser.FinishParsing();
XmlSchema schema = _inlineSchemaParser.XmlSchema;
_validator.AddSchema(schema);
_inlineSchemaParser = null;
_validationState = ValidatingReaderState.Read;
}
}
}
private Task<object> InternalReadContentAsObjectAsync()
{
return InternalReadContentAsObjectAsync(false);
}
private async Task<object> InternalReadContentAsObjectAsync(bool unwrapTypedValue)
{
var tuple_11 = await InternalReadContentAsObjectTupleAsync(unwrapTypedValue).ConfigureAwait(false);
return tuple_11.Item2;
}
private async Task<Tuple<string, object>> InternalReadContentAsObjectTupleAsync(bool unwrapTypedValue)
{
Tuple<string, object> tuple;
string originalStringValue;
XmlNodeType nodeType = this.NodeType;
if (nodeType == XmlNodeType.Attribute)
{
originalStringValue = this.Value;
if (_attributePSVI != null && _attributePSVI.typedAttributeValue != null)
{
if (_validationState == ValidatingReaderState.OnDefaultAttribute)
{
XmlSchemaAttribute schemaAttr = _attributePSVI.attributeSchemaInfo.SchemaAttribute;
originalStringValue = (schemaAttr.DefaultValue != null) ? schemaAttr.DefaultValue : schemaAttr.FixedValue;
}
tuple = new Tuple<string, object>(originalStringValue, ReturnBoxedValue(_attributePSVI.typedAttributeValue, AttributeSchemaInfo.XmlType, unwrapTypedValue));
return tuple;
}
else
{ //return string value
tuple = new Tuple<string, object>(originalStringValue, this.Value);
return tuple;
}
}
else if (nodeType == XmlNodeType.EndElement)
{
if (_atomicValue != null)
{
originalStringValue = _originalAtomicValueString;
tuple = new Tuple<string, object>(originalStringValue, _atomicValue);
return tuple;
}
else
{
originalStringValue = string.Empty;
tuple = new Tuple<string, object>(originalStringValue, string.Empty);
return tuple;
}
}
else
{ //Positioned on text, CDATA, PI, Comment etc
if (_validator.CurrentContentType == XmlSchemaContentType.TextOnly)
{ //if current element is of simple type
object value = ReturnBoxedValue(await ReadTillEndElementAsync().ConfigureAwait(false), _xmlSchemaInfo.XmlType, unwrapTypedValue);
originalStringValue = _originalAtomicValueString;
tuple = new Tuple<string, object>(originalStringValue, value);
return tuple;
}
else
{
XsdCachingReader cachingReader = _coreReader as XsdCachingReader;
if (cachingReader != null)
{
originalStringValue = cachingReader.ReadOriginalContentAsString();
}
else
{
originalStringValue = await InternalReadContentAsStringAsync().ConfigureAwait(false);
}
tuple = new Tuple<string, object>(originalStringValue, originalStringValue);
return tuple;
}
}
}
private Task<Tuple<XmlSchemaType, object>> InternalReadElementContentAsObjectAsync()
{
return InternalReadElementContentAsObjectAsync(false);
}
private async Task<Tuple<XmlSchemaType, object>> InternalReadElementContentAsObjectAsync(bool unwrapTypedValue)
{
var tuple_13 = await InternalReadElementContentAsObjectTupleAsync(unwrapTypedValue).ConfigureAwait(false);
return new Tuple<XmlSchemaType, object>(tuple_13.Item1, tuple_13.Item3);
}
private async Task<Tuple<XmlSchemaType, string, object>> InternalReadElementContentAsObjectTupleAsync(bool unwrapTypedValue)
{
Tuple<XmlSchemaType, string, object> tuple;
XmlSchemaType xmlType;
string originalString;
Debug.Assert(this.NodeType == XmlNodeType.Element);
object typedValue = null;
xmlType = null;
//If its an empty element, can have default/fixed value
if (this.IsEmptyElement)
{
if (_xmlSchemaInfo.ContentType == XmlSchemaContentType.TextOnly)
{
typedValue = ReturnBoxedValue(_atomicValue, _xmlSchemaInfo.XmlType, unwrapTypedValue);
}
else
{
typedValue = _atomicValue;
}
originalString = _originalAtomicValueString;
xmlType = ElementXmlType; //Set this for default values
await this.ReadAsync().ConfigureAwait(false);
tuple = new Tuple<XmlSchemaType, string, object>(xmlType, originalString, typedValue);
return tuple;
}
// move to content and read typed value
await this.ReadAsync().ConfigureAwait(false);
if (this.NodeType == XmlNodeType.EndElement)
{ //If IsDefault is true, the next node will be EndElement
if (_xmlSchemaInfo.IsDefault)
{
if (_xmlSchemaInfo.ContentType == XmlSchemaContentType.TextOnly)
{
typedValue = ReturnBoxedValue(_atomicValue, _xmlSchemaInfo.XmlType, unwrapTypedValue);
}
else
{ //anyType has default value
typedValue = _atomicValue;
}
originalString = _originalAtomicValueString;
}
else
{ //Empty content
typedValue = string.Empty;
originalString = string.Empty;
}
}
else if (this.NodeType == XmlNodeType.Element)
{ //the first child is again element node
throw new XmlException(SR.Xml_MixedReadElementContentAs, string.Empty, this as IXmlLineInfo);
}
else
{
var tuple_14 = await InternalReadContentAsObjectTupleAsync(unwrapTypedValue).ConfigureAwait(false);
originalString = tuple_14.Item1;
typedValue = tuple_14.Item2;
// ReadElementContentAsXXX cannot be called on mixed content, if positioned on node other than EndElement, Error
if (this.NodeType != XmlNodeType.EndElement)
{
throw new XmlException(SR.Xml_MixedReadElementContentAs, string.Empty, this as IXmlLineInfo);
}
}
xmlType = ElementXmlType; //Set this as we are moving ahead to the next node
// move to next node
await this.ReadAsync().ConfigureAwait(false);
tuple = new Tuple<XmlSchemaType, string, object>(xmlType, originalString, typedValue);
return tuple;
}
private async Task<object> ReadTillEndElementAsync()
{
if (_atomicValue == null)
{
while (await _coreReader.ReadAsync().ConfigureAwait(false))
{
if (_replayCache)
{ //If replaying nodes in the cache, they have already been validated
continue;
}
switch (_coreReader.NodeType)
{
case XmlNodeType.Element:
await ProcessReaderEventAsync().ConfigureAwait(false);
goto breakWhile;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
_validator.ValidateText(GetStringValue);
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
_validator.ValidateWhitespace(GetStringValue);
break;
case XmlNodeType.Comment:
case XmlNodeType.ProcessingInstruction:
break;
case XmlNodeType.EndElement:
_atomicValue = _validator.ValidateEndElement(_xmlSchemaInfo);
_originalAtomicValueString = GetOriginalAtomicValueStringOfElement();
if (_manageNamespaces)
{
_nsManager.PopScope();
}
goto breakWhile;
}
continue;
breakWhile:
break;
}
}
else
{ //atomicValue != null, meaning already read ahead - Switch reader
if (_atomicValue == this)
{ //switch back invalid marker; dont need it since coreReader moved to endElement
_atomicValue = null;
}
SwitchReader();
}
return _atomicValue;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
namespace StatsdClient
{
public interface IAllowsDelta { }
public interface IAllowsDouble { }
public interface IAllowsInteger { }
public interface IAllowsSampleRate { }
public interface IAllowsString { }
public class Statsd : IStatsd
{
#region Private Fields
private readonly object _commandCollectionLock = new object();
private readonly Dictionary<Type, string> _commandToUnit = new Dictionary<Type, string>
{
{typeof (Counting), "c"},
{typeof (Timing), "ms"},
{typeof (Gauge), "g"},
{typeof (Histogram), "h"},
{typeof (Meter), "m"},
{typeof (Set), "s"}
};
private readonly string _prefix;
private readonly int _sendWaitTimeout;
#endregion Private Fields
#region Public Constructors
public Statsd(IMetricsSender sender, IRandomGenerator randomGenerator, IStopWatchFactory stopwatchFactory, string prefix, int sendWaitTimeout = Timeout.Infinite)
{
if (sender == null) throw new ArgumentNullException("sender");
if (randomGenerator == null) throw new ArgumentNullException("randomGenerator");
if (stopwatchFactory == null) throw new ArgumentNullException("stopwatchFactory");
Commands = new List<string>();
StopwatchFactory = stopwatchFactory;
Sender = sender;
RandomGenerator = randomGenerator;
_prefix = prefix.EndsWith(".") ? prefix : prefix + ".";
_sendWaitTimeout = sendWaitTimeout;
}
public Statsd(IMetricsSender udp, IRandomGenerator randomGenerator, IStopWatchFactory stopwatchFactory)
: this(udp, randomGenerator, stopwatchFactory, string.Empty, Timeout.Infinite)
{ }
public Statsd(IMetricsSender udp, string prefix, int sendWaitTimeout = Timeout.Infinite)
: this(udp, new RandomGenerator(), new StopWatchFactory(), prefix, sendWaitTimeout)
{ }
public Statsd(IMetricsSender udp)
: this(udp, "")
{ }
#endregion Public Constructors
#region Public Properties
public List<string> Commands { get; private set; }
#endregion Public Properties
#region Private Properties
private IRandomGenerator RandomGenerator { get; set; }
private IMetricsSender Sender { get; set; }
private IStopWatchFactory StopwatchFactory { get; set; }
#endregion Private Properties
#region Public Methods
public void Add<TCommandType>(string name, string value) where TCommandType : IAllowsString
{
ThreadSafeAddCommand(GetCommand(name, value.ToString(CultureInfo.InvariantCulture),
_commandToUnit[typeof(TCommandType)], 1));
}
public void Add<TCommandType>(string name, int value) where TCommandType : IAllowsInteger
{
ThreadSafeAddCommand(GetCommand(name, value.ToString(CultureInfo.InvariantCulture),
_commandToUnit[typeof(TCommandType)], 1));
}
public void Add<TCommandType>(string name, double value) where TCommandType : IAllowsDouble
{
ThreadSafeAddCommand(GetCommand(name, string.Format(CultureInfo.InvariantCulture, "{0:F15}", value),
_commandToUnit[typeof(TCommandType)], 1));
}
public void Add<TCommandType>(string name, double value, bool isDelta)
where TCommandType : IAllowsDouble, IAllowsDelta
{
var prefix = GetDeltaPrefix(value, isDelta);
ThreadSafeAddCommand(GetCommand(name, string.Format(CultureInfo.InvariantCulture,
"{0}{1:F15}", prefix, value), _commandToUnit[typeof(TCommandType)], 1));
}
public void Add<TCommandType>(string name, int value, double sampleRate)
where TCommandType : IAllowsInteger, IAllowsSampleRate
{
if (RandomGenerator.ShouldSend(sampleRate))
{
Commands.Add(GetCommand(name, value.ToString(CultureInfo.InvariantCulture),
_commandToUnit[typeof(TCommandType)], sampleRate));
}
}
public void Add(Action actionToTime, string statName, double sampleRate = 1)
{
var stopwatch = StopwatchFactory.Get();
try
{
stopwatch.Start();
actionToTime();
}
finally
{
stopwatch.Stop();
if (RandomGenerator.ShouldSend(sampleRate))
{
Add<Timing>(statName, stopwatch.ElapsedMilliseconds());
}
}
}
public void Send<TCommandType>(string name, int value) where TCommandType : IAllowsInteger
{
Commands = new List<string>
{
GetCommand(name, value.ToString(CultureInfo.InvariantCulture), _commandToUnit[typeof(TCommandType)], 1)
};
Send().WaitAndUnwrapException(_sendWaitTimeout);
}
public void Send<TCommandType>(string name, double value) where TCommandType : IAllowsDouble
{
Commands = new List<string>
{
GetCommand(name, string.Format(CultureInfo.InvariantCulture,"{0:F15}", value),
_commandToUnit[typeof(TCommandType)], 1)
};
Send().WaitAndUnwrapException(_sendWaitTimeout);
}
public void Send<TCommandType>(string name, string value) where TCommandType : IAllowsString
{
Commands = new List<string>
{
GetCommand(name, value.ToString(CultureInfo.InvariantCulture), _commandToUnit[typeof(TCommandType)], 1)
};
Send().WaitAndUnwrapException(_sendWaitTimeout);
}
public void Send<TCommandType>(string name, int value, double sampleRate)
where TCommandType : IAllowsInteger, IAllowsSampleRate
{
if (RandomGenerator.ShouldSend(sampleRate))
{
Commands = new List<string>
{
GetCommand(name, value.ToString(CultureInfo.InvariantCulture),
_commandToUnit[typeof(TCommandType)], sampleRate)
};
Send().WaitAndUnwrapException(_sendWaitTimeout);
}
}
public void Send<TCommandType>(string name, double value, bool isDelta)
where TCommandType : IAllowsDouble, IAllowsDelta
{
var prefix = GetDeltaPrefix(value, isDelta);
Commands = new List<string>
{
GetCommand(name, prefix + value.ToString(CultureInfo.InvariantCulture),
_commandToUnit[typeof(TCommandType)], 1)
};
Send().WaitAndUnwrapException(_sendWaitTimeout);
}
public async Task Send()
{
try
{
await Sender.Send(string.Join("", Commands.ToArray()));
Commands = new List<string>(); // only reset our list if it made it through properly!
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
throw; // let the caller handle errors
}
}
public void Send(Action actionToTime, string statName, double sampleRate = 1)
{
var stopwatch = StopwatchFactory.Get();
try
{
stopwatch.Start();
actionToTime();
}
finally
{
stopwatch.Stop();
if (RandomGenerator.ShouldSend(sampleRate))
{
Send<Timing>(statName, stopwatch.ElapsedMilliseconds());
}
}
}
#endregion Public Methods
#region Private Methods
private string GetCommand(string name, string value, string unit, double sampleRate)
{
var format = sampleRate == 1 ? "{0}:{1}|{2}\n" : "{0}:{1}|{2}|@{3}\n";
return string.Format(CultureInfo.InvariantCulture, format, _prefix + name, value, unit, sampleRate);
}
private string GetDeltaPrefix(double value, bool isDelta)
{
return isDelta && value >= 0 ? "+" : string.Empty;
}
private void ThreadSafeAddCommand(string command)
{
lock (_commandCollectionLock)
{
Commands.Add(command);
}
}
#endregion Private Methods
#region Public Classes
public class Counting : IAllowsSampleRate, IAllowsInteger { }
public class Gauge : IAllowsDouble, IAllowsDelta { }
public class Histogram : IAllowsInteger { }
public class Meter : IAllowsInteger { }
public class Set : IAllowsString { }
public class Timing : IAllowsSampleRate, IAllowsInteger { }
#endregion Public Classes
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Diagnostics.Contracts;
namespace System.Xml.Linq
{
// Summary:
// Contains the LINQ to XML extension methods.
public static class Extensions
{
// Summary:
// Returns a collection of elements that contains the ancestors of every node
// in the source collection.
//
// Parameters:
// source:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XNode that
// contains the source collection.
//
// Type parameters:
// T:
// The type of the objects in source, constrained to System.Xml.Linq.XNode.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// that contains the ancestors of every node in the source collection.
public static IEnumerable<XElement> Ancestors<T>(this IEnumerable<T> source) where T : XNode
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<IEnumerable<XElement>>() != null);
return default(IEnumerable<XElement>);
}
//
// Summary:
// Returns a filtered collection of elements that contains the ancestors of
// every node in the source collection. Only elements that have a matching System.Xml.Linq.XName
// are included in the collection.
//
// Parameters:
// source:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XNode that
// contains the source collection.
//
// name:
// The System.Xml.Linq.XName to match.
//
// Type parameters:
// T:
// The type of the objects in source, constrained to System.Xml.Linq.XNode.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// that contains the ancestors of every node in the source collection. Only
// elements that have a matching System.Xml.Linq.XName are included in the collection.
public static IEnumerable<XElement> Ancestors<T>(this IEnumerable<T> source, XName name) where T : XNode
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<IEnumerable<XElement>>() != null);
return default(IEnumerable<XElement>);
}
//
// Summary:
// Returns a collection of elements that contains every element in the source
// collection, and the ancestors of every element in the source collection.
//
// Parameters:
// source:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// that contains the source collection.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// that contains every element in the source collection, and the ancestors of
// every element in the source collection.
public static IEnumerable<XElement> AncestorsAndSelf(this IEnumerable<XElement> source)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<IEnumerable<XElement>>() != null);
return default(IEnumerable<XElement>);
}
//
// Summary:
// Returns a filtered collection of elements that contains every element in
// the source collection, and the ancestors of every element in the source collection.
// Only elements that have a matching System.Xml.Linq.XName are included in
// the collection.
//
// Parameters:
// source:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// that contains the source collection.
//
// name:
// The System.Xml.Linq.XName to match.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// that contains every element in the source collection, and the ancestors of
// every element in the source collection. Only elements that have a matching
// System.Xml.Linq.XName are included in the collection.
public static IEnumerable<XElement> AncestorsAndSelf(this IEnumerable<XElement> source, XName name)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<IEnumerable<XElement>>() != null);
return default(IEnumerable<XElement>);
}
//
// Summary:
// Returns a collection of the attributes of every element in the source collection.
//
// Parameters:
// source:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// that contains the source collection.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XAttribute
// that contains the attributes of every element in the source collection.
public static IEnumerable<XAttribute> Attributes(this IEnumerable<XElement> source)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<IEnumerable<XAttribute>>() != null);
return default(IEnumerable<XAttribute>);
}
//
// Summary:
// Returns a filtered collection of the attributes of every element in the source
// collection. Only elements that have a matching System.Xml.Linq.XName are
// included in the collection.
//
// Parameters:
// source:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// that contains the source collection.
//
// name:
// The System.Xml.Linq.XName to match.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XAttribute
// that contains a filtered collection of the attributes of every element in
// the source collection. Only elements that have a matching System.Xml.Linq.XName
// are included in the collection.
public static IEnumerable<XAttribute> Attributes(this IEnumerable<XElement> source, XName name)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<IEnumerable<XAttribute>>() != null);
return default(IEnumerable<XAttribute>);
}
//
// Summary:
// Returns a collection of the descendant nodes of every document and element
// in the source collection.
//
// Parameters:
// source:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XContainer
// that contains the source collection.
//
// Type parameters:
// T:
// The type of the objects in source, constrained to System.Xml.Linq.XContainer.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XNode of
// the descendant nodes of every document and element in the source collection.
public static IEnumerable<XNode> DescendantNodes<T>(this IEnumerable<T> source) where T : XContainer
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<IEnumerable<XNode>>() != null);
return default(IEnumerable<XNode>);
}
//
// Summary:
// Returns a collection of nodes that contains every element in the source collection,
// and the descendant nodes of every element in the source collection.
//
// Parameters:
// source:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// that contains the source collection.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XNode that
// contains every element in the source collection, and the descendant nodes
// of every element in the source collection.
public static IEnumerable<XNode> DescendantNodesAndSelf(this IEnumerable<XElement> source)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<IEnumerable<XNode>>() != null);
return default(IEnumerable<XNode>);
}
//
// Summary:
// Returns a collection of elements that contains the descendant elements of
// every element and document in the source collection.
//
// Parameters:
// source:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XContainer
// that contains the source collection.
//
// Type parameters:
// T:
// The type of the objects in source, constrained to System.Xml.Linq.XContainer.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// that contains the descendant elements of every element and document in the
// source collection.
public static IEnumerable<XElement> Descendants<T>(this IEnumerable<T> source) where T : XContainer
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<IEnumerable<XElement>>() != null);
return default(IEnumerable<XElement>);
}
//
// Summary:
// Returns a filtered collection of elements that contains the descendant elements
// of every element and document in the source collection. Only elements that
// have a matching System.Xml.Linq.XName are included in the collection.
//
// Parameters:
// source:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XContainer
// that contains the source collection.
//
// name:
// The System.Xml.Linq.XName to match.
//
// Type parameters:
// T:
// The type of the objects in source, constrained to System.Xml.Linq.XContainer.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// that contains the descendant elements of every element and document in the
// source collection. Only elements that have a matching System.Xml.Linq.XName
// are included in the collection.
public static IEnumerable<XElement> Descendants<T>(this IEnumerable<T> source, XName name) where T : XContainer
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<IEnumerable<XElement>>() != null);
return default(IEnumerable<XElement>);
}
//
// Summary:
// Returns a collection of elements that contains every element in the source
// collection, and the descendent elements of every element in the source collection.
//
// Parameters:
// source:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// that contains the source collection.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// that contains every element in the source collection, and the descendent
// elements of every element in the source collection.
public static IEnumerable<XElement> DescendantsAndSelf(this IEnumerable<XElement> source)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<IEnumerable<XElement>>() != null);
return default(IEnumerable<XElement>);
}
//
// Summary:
// Returns a filtered collection of elements that contains every element in
// the source collection, and the descendents of every element in the source
// collection. Only elements that have a matching System.Xml.Linq.XName are
// included in the collection.
//
// Parameters:
// source:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// that contains the source collection.
//
// name:
// The System.Xml.Linq.XName to match.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// that contains every element in the source collection, and the descendents
// of every element in the source collection. Only elements that have a matching
// System.Xml.Linq.XName are included in the collection.
public static IEnumerable<XElement> DescendantsAndSelf(this IEnumerable<XElement> source, XName name)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<IEnumerable<XElement>>() != null);
return default(IEnumerable<XElement>);
}
//
// Summary:
// Returns a collection of the child elements of every element and document
// in the source collection.
//
// Parameters:
// source:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// that contains the source collection.
//
// Type parameters:
// T:
// The type of the objects in source, constrained to System.Xml.Linq.XContainer.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// of the child elements of every element or document in the source collection.
public static IEnumerable<XElement> Elements<T>(this IEnumerable<T> source) where T : XContainer
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<IEnumerable<XElement>>() != null);
return default(IEnumerable<XElement>);
}
//
// Summary:
// Returns a filtered collection of the child elements of every element and
// document in the source collection. Only elements that have a matching System.Xml.Linq.XName
// are included in the collection.
//
// Parameters:
// source:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// that contains the source collection.
//
// name:
// The System.Xml.Linq.XName to match.
//
// Type parameters:
// T:
// The type of the objects in source, constrained to System.Xml.Linq.XContainer.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XElement
// of the child elements of every element and document in the source collection.
// Only elements that have a matching System.Xml.Linq.XName are included in
// the collection.
public static IEnumerable<XElement> Elements<T>(this IEnumerable<T> source, XName name) where T : XContainer
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<IEnumerable<XElement>>() != null);
return default(IEnumerable<XElement>);
}
//
// Summary:
// Returns a collection of nodes that contains all nodes in the source collection,
// sorted in document order.
//
// Parameters:
// source:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XNode that
// contains the source collection.
//
// Type parameters:
// T:
// The type of the objects in source, constrained to System.Xml.Linq.XNode.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XNode that
// contains all nodes in the source collection, sorted in document order.
public static IEnumerable<T> InDocumentOrder<T>(this IEnumerable<T> source) where T : XNode
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<IEnumerable<T>>() != null);
return default(IEnumerable<T>);
}
//
// Summary:
// Returns a collection of the child nodes of every document and element in
// the source collection.
//
// Parameters:
// source:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XNode that
// contains the source collection.
//
// Type parameters:
// T:
// The type of the objects in source, constrained to System.Xml.Linq.XContainer.
//
// Returns:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XNode of
// the child nodes of every document and element in the source collection.
public static IEnumerable<XNode> Nodes<T>(this IEnumerable<T> source) where T : XContainer
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<IEnumerable<XNode>>() != null);
return default(IEnumerable<XNode>);
}
//
// Summary:
// Removes every node in the source collection from its parent node.
//
// Parameters:
// source:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XNode that
// contains the source collection.
//
// Type parameters:
// T:
// The type of the objects in source, constrained to System.Xml.Linq.XNode.
public static void Remove<T>(this IEnumerable<T> source) where T : XNode
{
Contract.Requires(source != null);
}
//
// Summary:
// Removes every attribute in the source collection from its parent element.
//
// Parameters:
// source:
// An System.Collections.Generic.IEnumerable<T> of System.Xml.Linq.XAttribute
// that contains the source collection.
public static void Remove(this IEnumerable<XAttribute> source)
{
Contract.Requires(source != null);
}
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculus.com/licenses/LICENSE-3.3
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
/// <summary>
/// Miscellaneous extension methods that any script can use.
/// </summary>
public static class OVRExtensions
{
/// <summary>
/// Converts the given world-space transform to an OVRPose in tracking space.
/// </summary>
public static OVRPose ToTrackingSpacePose(this Transform transform)
{
OVRPose headPose;
headPose.position = UnityEngine.VR.InputTracking.GetLocalPosition(UnityEngine.VR.VRNode.Head);
headPose.orientation = UnityEngine.VR.InputTracking.GetLocalRotation(UnityEngine.VR.VRNode.Head);
var ret = headPose * transform.ToHeadSpacePose();
return ret;
}
/// <summary>
/// Converts the given world-space transform to an OVRPose in head space.
/// </summary>
public static OVRPose ToHeadSpacePose(this Transform transform)
{
return Camera.current.transform.ToOVRPose().Inverse() * transform.ToOVRPose();
}
internal static OVRPose ToOVRPose(this Transform t, bool isLocal = false)
{
OVRPose pose;
pose.orientation = (isLocal) ? t.localRotation : t.rotation;
pose.position = (isLocal) ? t.localPosition : t.position;
return pose;
}
internal static void FromOVRPose(this Transform t, OVRPose pose, bool isLocal = false)
{
if (isLocal)
{
t.localRotation = pose.orientation;
t.localPosition = pose.position;
}
else
{
t.rotation = pose.orientation;
t.position = pose.position;
}
}
internal static OVRPose ToOVRPose(this OVRPlugin.Posef p)
{
return new OVRPose()
{
position = new Vector3(p.Position.x, p.Position.y, -p.Position.z),
orientation = new Quaternion(-p.Orientation.x, -p.Orientation.y, p.Orientation.z, p.Orientation.w)
};
}
internal static OVRTracker.Frustum ToFrustum(this OVRPlugin.Frustumf f)
{
return new OVRTracker.Frustum()
{
nearZ = f.zNear,
farZ = f.zFar,
fov = new Vector2()
{
x = Mathf.Rad2Deg * f.fovX,
y = Mathf.Rad2Deg * f.fovY
}
};
}
internal static Color FromColorf(this OVRPlugin.Colorf c)
{
return new Color() { r = c.r, g = c.g, b = c.b, a = c.a };
}
internal static OVRPlugin.Colorf ToColorf(this Color c)
{
return new OVRPlugin.Colorf() { r = c.r, g = c.g, b = c.b, a = c.a };
}
internal static Vector3 FromVector3f(this OVRPlugin.Vector3f v)
{
return new Vector3() { x = v.x, y = v.y, z = v.z };
}
internal static Vector3 FromFlippedZVector3f(this OVRPlugin.Vector3f v)
{
return new Vector3() { x = v.x, y = v.y, z = -v.z };
}
internal static OVRPlugin.Vector3f ToVector3f(this Vector3 v)
{
return new OVRPlugin.Vector3f() { x = v.x, y = v.y, z = v.z };
}
internal static OVRPlugin.Vector3f ToFlippedZVector3f(this Vector3 v)
{
return new OVRPlugin.Vector3f() { x = v.x, y = v.y, z = -v.z };
}
internal static Quaternion FromQuatf(this OVRPlugin.Quatf q)
{
return new Quaternion() { x = q.x, y = q.y, z = q.z, w = q.w };
}
internal static OVRPlugin.Quatf ToQuatf(this Quaternion q)
{
return new OVRPlugin.Quatf() { x = q.x, y = q.y, z = q.z, w = q.w };
}
}
/// <summary>
/// An affine transformation built from a Unity position and orientation.
/// </summary>
[System.Serializable]
public struct OVRPose
{
/// <summary>
/// A pose with no translation or rotation.
/// </summary>
public static OVRPose identity
{
get {
return new OVRPose()
{
position = Vector3.zero,
orientation = Quaternion.identity
};
}
}
public override bool Equals(System.Object obj)
{
return obj is OVRPose && this == (OVRPose)obj;
}
public override int GetHashCode()
{
return position.GetHashCode() ^ orientation.GetHashCode();
}
public static bool operator ==(OVRPose x, OVRPose y)
{
return x.position == y.position && x.orientation == y.orientation;
}
public static bool operator !=(OVRPose x, OVRPose y)
{
return !(x == y);
}
/// <summary>
/// The position.
/// </summary>
public Vector3 position;
/// <summary>
/// The orientation.
/// </summary>
public Quaternion orientation;
/// <summary>
/// Multiplies two poses.
/// </summary>
public static OVRPose operator*(OVRPose lhs, OVRPose rhs)
{
var ret = new OVRPose();
ret.position = lhs.position + lhs.orientation * rhs.position;
ret.orientation = lhs.orientation * rhs.orientation;
return ret;
}
/// <summary>
/// Computes the inverse of the given pose.
/// </summary>
public OVRPose Inverse()
{
OVRPose ret;
ret.orientation = Quaternion.Inverse(orientation);
ret.position = ret.orientation * -position;
return ret;
}
/// <summary>
/// Converts the pose from left- to right-handed or vice-versa.
/// </summary>
internal OVRPose flipZ()
{
var ret = this;
ret.position.z = -ret.position.z;
ret.orientation.z = -ret.orientation.z;
ret.orientation.w = -ret.orientation.w;
return ret;
}
internal OVRPlugin.Posef ToPosef()
{
return new OVRPlugin.Posef()
{
Position = position.ToVector3f(),
Orientation = orientation.ToQuatf()
};
}
}
public class OVRNativeBuffer : IDisposable
{
private bool disposed = false;
private int m_numBytes = 0;
private IntPtr m_ptr = IntPtr.Zero;
public OVRNativeBuffer(int numBytes)
{
Reallocate(numBytes);
}
~OVRNativeBuffer()
{
Dispose(false);
}
public void Reset(int numBytes)
{
Reallocate(numBytes);
}
public int GetCapacity()
{
return m_numBytes;
}
public IntPtr GetPointer(int byteOffset = 0)
{
if (byteOffset < 0 || byteOffset >= m_numBytes)
return IntPtr.Zero;
return (byteOffset == 0) ? m_ptr : new IntPtr(m_ptr.ToInt64() + byteOffset);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
// dispose managed resources
}
// dispose unmanaged resources
Release();
disposed = true;
}
private void Reallocate(int numBytes)
{
Release();
if (numBytes > 0)
{
m_ptr = Marshal.AllocHGlobal(numBytes);
m_numBytes = numBytes;
}
else
{
m_ptr = IntPtr.Zero;
m_numBytes = 0;
}
}
private void Release()
{
if (m_ptr != IntPtr.Zero)
{
Marshal.FreeHGlobal(m_ptr);
m_ptr = IntPtr.Zero;
m_numBytes = 0;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace SirindarApi.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace CloudStack.Net
{
public class ListVirtualMachinesRequest : APIListRequest
{
public ListVirtualMachinesRequest() : base("listVirtualMachines") {}
/// <summary>
/// list resources by account. Must be used with the domainId parameter.
/// </summary>
public string Account {
get { return GetParameterValue<string>(nameof(Account).ToLower()); }
set { SetParameterValue(nameof(Account).ToLower(), value); }
}
/// <summary>
/// list vms by affinity group
/// </summary>
public Guid? AffinityGroupId {
get { return GetParameterValue<Guid?>(nameof(AffinityGroupId).ToLower()); }
set { SetParameterValue(nameof(AffinityGroupId).ToLower(), value); }
}
/// <summary>
/// comma separated list of host details requested, value can be a list of [all, group, nics, stats, secgrp, tmpl, servoff, diskoff, iso, volume, min, affgrp]. If no parameter is passed in, the details will be defaulted to all
/// </summary>
public IList<string> Details {
get { return GetList<string>(nameof(Details).ToLower()); }
set { SetParameterValue(nameof(Details).ToLower(), value); }
}
/// <summary>
/// list resources by display flag; only ROOT admin is eligible to pass this parameter
/// </summary>
public bool? Displayvm {
get { return GetParameterValue<bool?>(nameof(Displayvm).ToLower()); }
set { SetParameterValue(nameof(Displayvm).ToLower(), value); }
}
/// <summary>
/// list only resources belonging to the domain specified
/// </summary>
public Guid? DomainId {
get { return GetParameterValue<Guid?>(nameof(DomainId).ToLower()); }
set { SetParameterValue(nameof(DomainId).ToLower(), value); }
}
/// <summary>
/// list by network type; true if need to list vms using Virtual Network, false otherwise
/// </summary>
public bool? ForVirtualNetwork {
get { return GetParameterValue<bool?>(nameof(ForVirtualNetwork).ToLower()); }
set { SetParameterValue(nameof(ForVirtualNetwork).ToLower(), value); }
}
/// <summary>
/// the group ID
/// </summary>
public Guid? GroupId {
get { return GetParameterValue<Guid?>(nameof(GroupId).ToLower()); }
set { SetParameterValue(nameof(GroupId).ToLower(), value); }
}
/// <summary>
/// the host ID
/// </summary>
public Guid? HostId {
get { return GetParameterValue<Guid?>(nameof(HostId).ToLower()); }
set { SetParameterValue(nameof(HostId).ToLower(), value); }
}
/// <summary>
/// the target hypervisor for the template
/// </summary>
public string Hypervisor {
get { return GetParameterValue<string>(nameof(Hypervisor).ToLower()); }
set { SetParameterValue(nameof(Hypervisor).ToLower(), value); }
}
/// <summary>
/// the ID of the virtual machine
/// </summary>
public Guid? Id {
get { return GetParameterValue<Guid?>(nameof(Id).ToLower()); }
set { SetParameterValue(nameof(Id).ToLower(), value); }
}
/// <summary>
/// the IDs of the virtual machines, mutually exclusive with id
/// </summary>
public IList<Guid> Ids {
get { return GetList<Guid>(nameof(Ids).ToLower()); }
set { SetParameterValue(nameof(Ids).ToLower(), value); }
}
/// <summary>
/// list vms by iso
/// </summary>
public Guid? IsoId {
get { return GetParameterValue<Guid?>(nameof(IsoId).ToLower()); }
set { SetParameterValue(nameof(IsoId).ToLower(), value); }
}
/// <summary>
/// defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.
/// </summary>
public bool? Isrecursive {
get { return GetParameterValue<bool?>(nameof(Isrecursive).ToLower()); }
set { SetParameterValue(nameof(Isrecursive).ToLower(), value); }
}
/// <summary>
/// list vms by ssh keypair name
/// </summary>
public string Keypair {
get { return GetParameterValue<string>(nameof(Keypair).ToLower()); }
set { SetParameterValue(nameof(Keypair).ToLower(), value); }
}
/// <summary>
/// List by keyword
/// </summary>
public string Keyword {
get { return GetParameterValue<string>(nameof(Keyword).ToLower()); }
set { SetParameterValue(nameof(Keyword).ToLower(), value); }
}
/// <summary>
/// If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false
/// </summary>
public bool? ListAll {
get { return GetParameterValue<bool?>(nameof(ListAll).ToLower()); }
set { SetParameterValue(nameof(ListAll).ToLower(), value); }
}
/// <summary>
/// name of the virtual machine (a substring match is made against the parameter value, data for all matching VMs will be returned)
/// </summary>
public string Name {
get { return GetParameterValue<string>(nameof(Name).ToLower()); }
set { SetParameterValue(nameof(Name).ToLower(), value); }
}
/// <summary>
/// list by network id
/// </summary>
public Guid? NetworkId {
get { return GetParameterValue<Guid?>(nameof(NetworkId).ToLower()); }
set { SetParameterValue(nameof(NetworkId).ToLower(), value); }
}
/// <summary>
/// the pod ID
/// </summary>
public Guid? PodId {
get { return GetParameterValue<Guid?>(nameof(PodId).ToLower()); }
set { SetParameterValue(nameof(PodId).ToLower(), value); }
}
/// <summary>
/// list objects by project
/// </summary>
public Guid? ProjectId {
get { return GetParameterValue<Guid?>(nameof(ProjectId).ToLower()); }
set { SetParameterValue(nameof(ProjectId).ToLower(), value); }
}
/// <summary>
/// list by the service offering
/// </summary>
public Guid? Serviceofferingid {
get { return GetParameterValue<Guid?>(nameof(Serviceofferingid).ToLower()); }
set { SetParameterValue(nameof(Serviceofferingid).ToLower(), value); }
}
/// <summary>
/// state of the virtual machine. Possible values are: Running, Stopped, Present, Destroyed, Expunged. Present is used for the state equal not destroyed.
/// </summary>
public string State {
get { return GetParameterValue<string>(nameof(State).ToLower()); }
set { SetParameterValue(nameof(State).ToLower(), value); }
}
/// <summary>
/// the storage ID where vm's volumes belong to
/// </summary>
public Guid? StorageId {
get { return GetParameterValue<Guid?>(nameof(StorageId).ToLower()); }
set { SetParameterValue(nameof(StorageId).ToLower(), value); }
}
/// <summary>
/// List resources by tags (key/value pairs)
/// </summary>
public IList<IDictionary<string, object>> Tags {
get { return GetList<IDictionary<string, object>>(nameof(Tags).ToLower()); }
set { SetParameterValue(nameof(Tags).ToLower(), value); }
}
/// <summary>
/// list vms by template
/// </summary>
public Guid? TemplateId {
get { return GetParameterValue<Guid?>(nameof(TemplateId).ToLower()); }
set { SetParameterValue(nameof(TemplateId).ToLower(), value); }
}
/// <summary>
/// the user ID that created the VM and is under the account that owns the VM
/// </summary>
public Guid? UserId {
get { return GetParameterValue<Guid?>(nameof(UserId).ToLower()); }
set { SetParameterValue(nameof(UserId).ToLower(), value); }
}
/// <summary>
/// list vms by vpc
/// </summary>
public Guid? VpcId {
get { return GetParameterValue<Guid?>(nameof(VpcId).ToLower()); }
set { SetParameterValue(nameof(VpcId).ToLower(), value); }
}
/// <summary>
/// the availability zone ID
/// </summary>
public Guid? ZoneId {
get { return GetParameterValue<Guid?>(nameof(ZoneId).ToLower()); }
set { SetParameterValue(nameof(ZoneId).ToLower(), value); }
}
}
/// <summary>
/// List the virtual machines owned by the account.
/// </summary>
public partial interface ICloudStackAPIClient
{
ListResponse<UserVmResponse> ListVirtualMachines(ListVirtualMachinesRequest request);
Task<ListResponse<UserVmResponse>> ListVirtualMachinesAsync(ListVirtualMachinesRequest request);
ListResponse<UserVmResponse> ListVirtualMachinesAllPages(ListVirtualMachinesRequest request);
Task<ListResponse<UserVmResponse>> ListVirtualMachinesAllPagesAsync(ListVirtualMachinesRequest request);
}
public partial class CloudStackAPIClient : ICloudStackAPIClient
{
public ListResponse<UserVmResponse> ListVirtualMachines(ListVirtualMachinesRequest request) => Proxy.Request<ListResponse<UserVmResponse>>(request);
public Task<ListResponse<UserVmResponse>> ListVirtualMachinesAsync(ListVirtualMachinesRequest request) => Proxy.RequestAsync<ListResponse<UserVmResponse>>(request);
public ListResponse<UserVmResponse> ListVirtualMachinesAllPages(ListVirtualMachinesRequest request) => Proxy.RequestAllPages<UserVmResponse>(request);
public Task<ListResponse<UserVmResponse>> ListVirtualMachinesAllPagesAsync(ListVirtualMachinesRequest request) => Proxy.RequestAllPagesAsync<UserVmResponse>(request);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
using System.Text;
namespace System.Data.Common
{
internal class MultipartIdentifier
{
private const int MaxParts = 4;
internal const int ServerIndex = 0;
internal const int CatalogIndex = 1;
internal const int SchemaIndex = 2;
internal const int TableIndex = 3;
/*
Left quote strings need to correspond 1 to 1 with the right quote strings
example: "ab" "cd", passed in for the left and the right quote
would set a or b as a starting quote character.
If a is the starting quote char then c would be the ending quote char
otherwise if b is the starting quote char then d would be the ending quote character.
*/
internal static string[] ParseMultipartIdentifier(string name, string leftQuote, string rightQuote, string property, bool ThrowOnEmptyMultipartName)
{
return ParseMultipartIdentifier(name, leftQuote, rightQuote, '.', MaxParts, true, property, ThrowOnEmptyMultipartName);
}
private enum MPIState
{
MPI_Value,
MPI_ParseNonQuote,
MPI_LookForSeparator,
MPI_LookForNextCharOrSeparator,
MPI_ParseQuote,
MPI_RightQuote,
}
/* Core function for parsing the multipart identifer string.
* paramaters: name - string to parse
* leftquote: set of characters which are valid quoteing characters to initiate a quote
* rightquote: set of characters which are valid to stop a quote, array index's correspond to the the leftquote array.
* separator: separator to use
* limit: number of names to parse out
* removequote:to remove the quotes on the returned string
*/
private static void IncrementStringCount(string name, string[] ary, ref int position, string property)
{
++position;
int limit = ary.Length;
if (position >= limit)
{
throw ADP.InvalidMultipartNameToManyParts(property, name, limit);
}
ary[position] = string.Empty;
}
private static bool IsWhitespace(char ch)
{
return Char.IsWhiteSpace(ch);
}
internal static string[] ParseMultipartIdentifier(string name, string leftQuote, string rightQuote, char separator, int limit, bool removequotes, string property, bool ThrowOnEmptyMultipartName)
{
if (limit <= 0)
{
throw ADP.InvalidMultipartNameToManyParts(property, name, limit);
}
if (-1 != leftQuote.IndexOf(separator) || -1 != rightQuote.IndexOf(separator) || leftQuote.Length != rightQuote.Length)
{
throw ADP.InvalidMultipartNameIncorrectUsageOfQuotes(property, name);
}
string[] parsedNames = new string[limit]; // return string array
int stringCount = 0; // index of current string in the buffer
MPIState state = MPIState.MPI_Value; // Initalize the starting state
StringBuilder sb = new StringBuilder(name.Length); // String buffer to hold the string being currently built, init the string builder so it will never be resized
StringBuilder whitespaceSB = null; // String buffer to hold white space used when parsing nonquoted strings 'a b . c d' = 'a b' and 'c d'
char rightQuoteChar = ' '; // Right quote character to use given the left quote character found.
for (int index = 0; index < name.Length; ++index)
{
char testchar = name[index];
switch (state)
{
case MPIState.MPI_Value:
{
int quoteIndex;
if (IsWhitespace(testchar))
{ // Is White Space then skip the whitespace
continue;
}
else
if (testchar == separator)
{ // If we found a separator, no string was found, initalize the string we are parsing to Empty and the next one to Empty.
// This is NOT a redundent setting of string.Empty it solves the case where we are parsing ".foo" and we should be returning null, null, empty, foo
parsedNames[stringCount] = string.Empty;
IncrementStringCount(name, parsedNames, ref stringCount, property);
}
else
if (-1 != (quoteIndex = leftQuote.IndexOf(testchar)))
{ // If we are a left quote
rightQuoteChar = rightQuote[quoteIndex]; // record the corresponding right quote for the left quote
sb.Length = 0;
if (!removequotes)
{
sb.Append(testchar);
}
state = MPIState.MPI_ParseQuote;
}
else
if (-1 != rightQuote.IndexOf(testchar))
{ // If we shouldn't see a right quote
throw ADP.InvalidMultipartNameIncorrectUsageOfQuotes(property, name);
}
else
{
sb.Length = 0;
sb.Append(testchar);
state = MPIState.MPI_ParseNonQuote;
}
break;
}
case MPIState.MPI_ParseNonQuote:
{
if (testchar == separator)
{
parsedNames[stringCount] = sb.ToString(); // set the currently parsed string
IncrementStringCount(name, parsedNames, ref stringCount, property);
state = MPIState.MPI_Value;
}
else // Quotes are not valid inside a non-quoted name
if (-1 != rightQuote.IndexOf(testchar))
{
throw ADP.InvalidMultipartNameIncorrectUsageOfQuotes(property, name);
}
else
if (-1 != leftQuote.IndexOf(testchar))
{
throw ADP.InvalidMultipartNameIncorrectUsageOfQuotes(property, name);
}
else
if (IsWhitespace(testchar))
{ // If it is Whitespace
parsedNames[stringCount] = sb.ToString(); // Set the currently parsed string
if (null == whitespaceSB)
{
whitespaceSB = new StringBuilder();
}
whitespaceSB.Length = 0;
whitespaceSB.Append(testchar); // start to record the white space, if we are parsing a name like "foo bar" we should return "foo bar"
state = MPIState.MPI_LookForNextCharOrSeparator;
}
else
{
sb.Append(testchar);
}
break;
}
case MPIState.MPI_LookForNextCharOrSeparator:
{
if (!IsWhitespace(testchar))
{ // If it is not whitespace
if (testchar == separator)
{
IncrementStringCount(name, parsedNames, ref stringCount, property);
state = MPIState.MPI_Value;
}
else
{ // If its not a separator and not whitespace
sb.Append(whitespaceSB);
sb.Append(testchar);
parsedNames[stringCount] = sb.ToString(); // Need to set the name here in case the string ends here.
state = MPIState.MPI_ParseNonQuote;
}
}
else
{
whitespaceSB.Append(testchar);
}
break;
}
case MPIState.MPI_ParseQuote:
{
if (testchar == rightQuoteChar)
{ // if se are on a right quote see if we are escapeing the right quote or ending the quoted string
if (!removequotes)
{
sb.Append(testchar);
}
state = MPIState.MPI_RightQuote;
}
else
{
sb.Append(testchar); // Append what we are currently parsing
}
break;
}
case MPIState.MPI_RightQuote:
{
if (testchar == rightQuoteChar)
{ // If the next char is a another right quote then we were escapeing the right quote
sb.Append(testchar);
state = MPIState.MPI_ParseQuote;
}
else
if (testchar == separator)
{ // If its a separator then record what we've parsed
parsedNames[stringCount] = sb.ToString();
IncrementStringCount(name, parsedNames, ref stringCount, property);
state = MPIState.MPI_Value;
}
else
if (!IsWhitespace(testchar))
{ // If it is not white space we got problems
throw ADP.InvalidMultipartNameIncorrectUsageOfQuotes(property, name);
}
else
{ // It is a whitespace character so the following char should be whitespace, separator, or end of string anything else is bad
parsedNames[stringCount] = sb.ToString();
state = MPIState.MPI_LookForSeparator;
}
break;
}
case MPIState.MPI_LookForSeparator:
{
if (!IsWhitespace(testchar))
{ // If it is not whitespace
if (testchar == separator)
{ // If it is a separator
IncrementStringCount(name, parsedNames, ref stringCount, property);
state = MPIState.MPI_Value;
}
else
{ // Othewise not a separator
throw ADP.InvalidMultipartNameIncorrectUsageOfQuotes(property, name);
}
}
break;
}
}
}
// Resolve final states after parsing the string
switch (state)
{
case MPIState.MPI_Value: // These states require no extra action
case MPIState.MPI_LookForSeparator:
case MPIState.MPI_LookForNextCharOrSeparator:
break;
case MPIState.MPI_ParseNonQuote: // Dump what ever was parsed
case MPIState.MPI_RightQuote:
parsedNames[stringCount] = sb.ToString();
break;
case MPIState.MPI_ParseQuote: // Invalid Ending States
default:
throw ADP.InvalidMultipartNameIncorrectUsageOfQuotes(property, name);
}
if (parsedNames[0] == null)
{
if (ThrowOnEmptyMultipartName)
{
throw ADP.InvalidMultipartName(property, name); // Name is entirely made up of whitespace
}
}
else
{
// Shuffle the parsed name, from left justification to right justification, ie [a][b][null][null] goes to [null][null][a][b]
int offset = limit - stringCount - 1;
if (offset > 0)
{
for (int x = limit - 1; x >= offset; --x)
{
parsedNames[x] = parsedNames[x - offset];
parsedNames[x - offset] = null;
}
}
}
return parsedNames;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: UnmanagedMemoryStream
**
** <OWNER>[....]</OWNER>
**
** Purpose: Create a stream over unmanaged memory, mostly
** useful for memory-mapped files.
**
** Date: October 20, 2000 (made public August 4, 2003)
**
===========================================================*/
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Diagnostics.Contracts;
#if !FEATURE_PAL && FEATURE_ASYNC_IO
using System.Threading.Tasks;
#endif // !FEATURE_PAL && FEATURE_ASYNC_IO
namespace System.IO {
/*
* This class is used to access a contiguous block of memory, likely outside
* the GC heap (or pinned in place in the GC heap, but a MemoryStream may
* make more sense in those cases). It's great if you have a pointer and
* a length for a section of memory mapped in by someone else and you don't
* want to copy this into the GC heap. UnmanagedMemoryStream assumes these
* two things:
*
* 1) All the memory in the specified block is readable or writable,
* depending on the values you pass to the constructor.
* 2) The lifetime of the block of memory is at least as long as the lifetime
* of the UnmanagedMemoryStream.
* 3) You clean up the memory when appropriate. The UnmanagedMemoryStream
* currently will do NOTHING to free this memory.
* 4) All calls to Write and WriteByte may not be threadsafe currently.
*
* It may become necessary to add in some sort of
* DeallocationMode enum, specifying whether we unmap a section of memory,
* call free, run a user-provided delegate to free the memory, etc etc.
* We'll suggest user write a subclass of UnmanagedMemoryStream that uses
* a SafeHandle subclass to hold onto the memory.
* Check for problems when using this in the negative parts of a
* process's address space. We may need to use unsigned longs internally
* and change the overflow detection logic.
*
* -----SECURITY MODEL AND SILVERLIGHT-----
* A few key notes about exposing UMS in silverlight:
* 1. No ctors are exposed to transparent code. This version of UMS only
* supports byte* (not SafeBuffer). Therefore, framework code can create
* a UMS and hand it to transparent code. Transparent code can use most
* operations on a UMS, but not operations that directly expose a
* pointer.
*
* 2. Scope of "unsafe" and non-CLS compliant operations reduced: The
* Whidbey version of this class has CLSCompliant(false) at the class
* level and unsafe modifiers at the method level. These were reduced to
* only where the unsafe operation is performed -- i.e. immediately
* around the pointer manipulation. Note that this brings UMS in line
* with recent changes in pu/clr to support SafeBuffer.
*
* 3. Currently, the only caller that creates a UMS is ResourceManager,
* which creates read-only UMSs, and therefore operations that can
* change the length will throw because write isn't supported. A
* conservative option would be to formalize the concept that _only_
* read-only UMSs can be creates, and enforce this by making WriteX and
* SetLength SecurityCritical. However, this is a violation of
* security inheritance rules, so we must keep these safe. The
* following notes make this acceptable for future use.
* a. a race condition in WriteX that could have allowed a thread to
* read from unzeroed memory was fixed
* b. memory region cannot be expanded beyond _capacity; in other
* words, a UMS creator is saying a writeable UMS is safe to
* write to anywhere in the memory range up to _capacity, specified
* in the ctor. Even if the caller doesn't specify a capacity, then
* length is used as the capacity.
*/
public class UnmanagedMemoryStream : Stream
{
//
private const long UnmanagedMemStreamMaxLength = Int64.MaxValue;
[System.Security.SecurityCritical] // auto-generated
private SafeBuffer _buffer;
[SecurityCritical]
private unsafe byte* _mem;
private long _length;
private long _capacity;
private long _position;
private long _offset;
private FileAccess _access;
internal bool _isOpen;
#if !FEATURE_PAL && FEATURE_ASYNC_IO
[NonSerialized]
private Task<Int32> _lastReadTask; // The last successful task returned from ReadAsync
#endif // FEATURE_PAL && FEATURE_ASYNC_IO
// Needed for subclasses that need to map a file, etc.
[System.Security.SecuritySafeCritical] // auto-generated
protected UnmanagedMemoryStream()
{
unsafe {
_mem = null;
}
_isOpen = false;
}
[System.Security.SecuritySafeCritical] // auto-generated
public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length) {
Initialize(buffer, offset, length, FileAccess.Read, false);
}
[System.Security.SecuritySafeCritical] // auto-generated
public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access) {
Initialize(buffer, offset, length, access, false);
}
// We must create one of these without doing a security check. This
// class is created while security is trying to start up. Plus, doing
// a Demand from Assembly.GetManifestResourceStream isn't useful.
[System.Security.SecurityCritical] // auto-generated
internal UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) {
Initialize(buffer, offset, length, access, skipSecurityCheck);
}
[System.Security.SecuritySafeCritical] // auto-generated
protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access) {
Initialize(buffer, offset, length, access, false);
}
[System.Security.SecurityCritical] // auto-generated
internal void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) {
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
if (offset < 0) {
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (length < 0) {
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (buffer.ByteLength < (ulong)(offset + length)) {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSafeBufferOffLen"));
}
if (access < FileAccess.Read || access > FileAccess.ReadWrite) {
throw new ArgumentOutOfRangeException("access");
}
Contract.EndContractBlock();
if (_isOpen) {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice"));
}
if (!skipSecurityCheck) {
#pragma warning disable 618
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
#pragma warning restore 618
}
// check for wraparound
unsafe {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
buffer.AcquirePointer(ref pointer);
if ( (pointer + offset + length) < pointer) {
throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround"));
}
}
finally {
if (pointer != null) {
buffer.ReleasePointer();
}
}
}
_offset = offset;
_buffer = buffer;
_length = length;
_capacity = length;
_access = access;
_isOpen = true;
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public unsafe UnmanagedMemoryStream(byte* pointer, long length)
{
Initialize(pointer, length, length, FileAccess.Read, false);
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access)
{
Initialize(pointer, length, capacity, access, false);
}
// We must create one of these without doing a security check. This
// class is created while security is trying to start up. Plus, doing
// a Demand from Assembly.GetManifestResourceStream isn't useful.
[System.Security.SecurityCritical] // auto-generated
internal unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck)
{
Initialize(pointer, length, capacity, access, skipSecurityCheck);
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access)
{
Initialize(pointer, length, capacity, access, false);
}
[System.Security.SecurityCritical] // auto-generated
internal unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck)
{
if (pointer == null)
throw new ArgumentNullException("pointer");
if (length < 0 || capacity < 0)
throw new ArgumentOutOfRangeException((length < 0) ? "length" : "capacity", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (length > capacity)
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity"));
Contract.EndContractBlock();
// Check for wraparound.
if (((byte*) ((long)pointer + capacity)) < pointer)
throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround"));
if (access < FileAccess.Read || access > FileAccess.ReadWrite)
throw new ArgumentOutOfRangeException("access", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
if (_isOpen)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice"));
if (!skipSecurityCheck)
#pragma warning disable 618
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
#pragma warning restore 618
_mem = pointer;
_offset = 0;
_length = length;
_capacity = capacity;
_access = access;
_isOpen = true;
}
public override bool CanRead {
[Pure]
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
get { return _isOpen && (_access & FileAccess.Read) != 0; }
}
public override bool CanSeek {
[Pure]
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
get { return _isOpen; }
}
public override bool CanWrite {
[Pure]
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
get { return _isOpen && (_access & FileAccess.Write) != 0; }
}
[System.Security.SecuritySafeCritical] // auto-generated
protected override void Dispose(bool disposing)
{
_isOpen = false;
unsafe { _mem = null; }
// Stream allocates WaitHandles for async calls. So for correctness
// call base.Dispose(disposing) for better perf, avoiding waiting
// for the finalizers to run on those types.
base.Dispose(disposing);
}
public override void Flush() {
if (!_isOpen) __Error.StreamIsClosed();
}
#if !FEATURE_PAL && FEATURE_ASYNC_IO
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public override Task FlushAsync(CancellationToken cancellationToken) {
if (cancellationToken.IsCancellationRequested)
return Task.FromCancellation(cancellationToken);
try {
Flush();
return Task.CompletedTask;
} catch(Exception ex) {
return Task.FromException(ex);
}
}
#endif // !FEATURE_PAL && FEATURE_ASYNC_IO
public override long Length {
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
get {
if (!_isOpen) __Error.StreamIsClosed();
return Interlocked.Read(ref _length);
}
}
public long Capacity {
get {
if (!_isOpen) __Error.StreamIsClosed();
return _capacity;
}
}
public override long Position {
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
get {
if (!CanSeek) __Error.StreamIsClosed();
Contract.EndContractBlock();
return Interlocked.Read(ref _position);
}
[System.Security.SecuritySafeCritical] // auto-generated
set {
if (value < 0)
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (!CanSeek) __Error.StreamIsClosed();
#if WIN32
unsafe {
// On 32 bit machines, ensure we don't wrap around.
if (value > (long) Int32.MaxValue || _mem + value < _mem)
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
}
#endif
Interlocked.Exchange(ref _position, value);
}
}
[CLSCompliant(false)]
public unsafe byte* PositionPointer {
[System.Security.SecurityCritical] // auto-generated_required
get {
if (_buffer != null) {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
}
// Use a temp to avoid a race
long pos = Interlocked.Read(ref _position);
if (pos > _capacity)
throw new IndexOutOfRangeException(Environment.GetResourceString("IndexOutOfRange_UMSPosition"));
byte * ptr = _mem + pos;
if (!_isOpen) __Error.StreamIsClosed();
return ptr;
}
[System.Security.SecurityCritical] // auto-generated_required
set {
if (_buffer != null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
if (!_isOpen) __Error.StreamIsClosed();
// Note: subtracting pointers returns an Int64. Working around
// to avoid hitting compiler warning CS0652 on this line.
if (new IntPtr(value - _mem).ToInt64() > UnmanagedMemStreamMaxLength)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength"));
if (value < _mem)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
Interlocked.Exchange(ref _position, value - _mem);
}
}
internal unsafe byte* Pointer {
[System.Security.SecurityCritical] // auto-generated
get {
if (_buffer != null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
return _mem;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override int Read([In, Out] byte[] buffer, int offset, int count) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // Keep this in [....] with contract validation in ReadAsync
if (!_isOpen) __Error.StreamIsClosed();
if (!CanRead) __Error.ReadNotSupported();
// Use a local variable to avoid a race where another thread
// changes our position after we decide we can read some bytes.
long pos = Interlocked.Read(ref _position);
long len = Interlocked.Read(ref _length);
long n = len - pos;
if (n > count)
n = count;
if (n <= 0)
return 0;
int nInt = (int) n; // Safe because n <= count, which is an Int32
if (nInt < 0)
nInt = 0; // _position could be beyond EOF
Contract.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1.
if (_buffer != null) {
unsafe {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
_buffer.AcquirePointer(ref pointer);
Buffer.Memcpy(buffer, offset, pointer + pos + _offset, 0, nInt);
}
finally {
if (pointer != null) {
_buffer.ReleasePointer();
}
}
}
}
else {
unsafe {
Buffer.Memcpy(buffer, offset, _mem + pos, 0, nInt);
}
}
Interlocked.Exchange(ref _position, pos + n);
return nInt;
}
#if !FEATURE_PAL && FEATURE_ASYNC_IO
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // contract validation copied from Read(...)
if (cancellationToken.IsCancellationRequested)
return Task.FromCancellation<Int32>(cancellationToken);
try {
Int32 n = Read(buffer, offset, count);
Task<Int32> t = _lastReadTask;
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<Int32>(n));
} catch (Exception ex) {
Contract.Assert(! (ex is OperationCanceledException));
return Task.FromException<Int32>(ex);
}
}
#endif // !FEATURE_PAL && FEATURE_ASYNC_IO
[System.Security.SecuritySafeCritical] // auto-generated
public override int ReadByte() {
if (!_isOpen) __Error.StreamIsClosed();
if (!CanRead) __Error.ReadNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
if (pos >= len)
return -1;
Interlocked.Exchange(ref _position, pos + 1);
int result;
if (_buffer != null) {
unsafe {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
_buffer.AcquirePointer(ref pointer);
result = *(pointer + pos + _offset);
}
finally {
if (pointer != null) {
_buffer.ReleasePointer();
}
}
}
}
else {
unsafe {
result = _mem[pos];
}
}
return result;
}
public override long Seek(long offset, SeekOrigin loc) {
if (!_isOpen) __Error.StreamIsClosed();
if (offset > UnmanagedMemStreamMaxLength)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength"));
switch(loc) {
case SeekOrigin.Begin:
if (offset < 0)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
Interlocked.Exchange(ref _position, offset);
break;
case SeekOrigin.Current:
long pos = Interlocked.Read(ref _position);
if (offset + pos < 0)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
Interlocked.Exchange(ref _position, offset + pos);
break;
case SeekOrigin.End:
long len = Interlocked.Read(ref _length);
if (len + offset < 0)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
Interlocked.Exchange(ref _position, len + offset);
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin"));
}
long finalPos = Interlocked.Read(ref _position);
Contract.Assert(finalPos >= 0, "_position >= 0");
return finalPos;
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void SetLength(long value) {
if (value < 0)
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (_buffer != null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
if (!_isOpen) __Error.StreamIsClosed();
if (!CanWrite) __Error.WriteNotSupported();
if (value > _capacity)
throw new IOException(Environment.GetResourceString("IO.IO_FixedCapacity"));
long pos = Interlocked.Read(ref _position);
long len = Interlocked.Read(ref _length);
if (value > len) {
unsafe {
Buffer.ZeroMemory(_mem+len, value-len);
}
}
Interlocked.Exchange(ref _length, value);
if (pos > value) {
Interlocked.Exchange(ref _position, value);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void Write(byte[] buffer, int offset, int count) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // Keep contract validation in [....] with WriteAsync(..)
if (!_isOpen) __Error.StreamIsClosed();
if (!CanWrite) __Error.WriteNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
long n = pos + count;
// Check for overflow
if (n < 0)
throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
if (n > _capacity) {
throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity"));
}
if (_buffer == null) {
// Check to see whether we are now expanding the stream and must
// zero any memory in the middle.
if (pos > len) {
unsafe {
Buffer.ZeroMemory(_mem+len, pos-len);
}
}
// set length after zeroing memory to avoid race condition of accessing unzeroed memory
if (n > len) {
Interlocked.Exchange(ref _length, n);
}
}
if (_buffer != null) {
long bytesLeft = _capacity - pos;
if (bytesLeft < count) {
throw new ArgumentException(Environment.GetResourceString("Arg_BufferTooSmall"));
}
unsafe {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
_buffer.AcquirePointer(ref pointer);
Buffer.Memcpy(pointer + pos + _offset, 0, buffer, offset, count);
}
finally {
if (pointer != null) {
_buffer.ReleasePointer();
}
}
}
}
else {
unsafe {
Buffer.Memcpy(_mem + pos, 0, buffer, offset, count);
}
}
Interlocked.Exchange(ref _position, n);
return;
}
#if !FEATURE_PAL && FEATURE_ASYNC_IO
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // contract validation copied from Write(..)
if (cancellationToken.IsCancellationRequested)
return Task.FromCancellation(cancellationToken);
try {
Write(buffer, offset, count);
return Task.CompletedTask;
} catch (Exception ex) {
Contract.Assert(! (ex is OperationCanceledException));
return Task.FromException<Int32>(ex);
}
}
#endif // !FEATURE_PAL && FEATURE_ASYNC_IO
[System.Security.SecuritySafeCritical] // auto-generated
public override void WriteByte(byte value) {
if (!_isOpen) __Error.StreamIsClosed();
if (!CanWrite) __Error.WriteNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
long n = pos + 1;
if (pos >= len) {
// Check for overflow
if (n < 0)
throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
if (n > _capacity)
throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity"));
// Check to see whether we are now expanding the stream and must
// zero any memory in the middle.
// don't do if created from SafeBuffer
if (_buffer == null) {
if (pos > len) {
unsafe {
Buffer.ZeroMemory(_mem+len, pos-len);
}
}
// set length after zeroing memory to avoid race condition of accessing unzeroed memory
Interlocked.Exchange(ref _length, n);
}
}
if (_buffer != null) {
unsafe {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
_buffer.AcquirePointer(ref pointer);
*(pointer + pos + _offset) = value;
}
finally {
if (pointer != null) {
_buffer.ReleasePointer();
}
}
}
}
else {
unsafe {
_mem[pos] = value;
}
}
Interlocked.Exchange(ref _position, n);
}
}
}
| |
#region License
// Pomona is open source software released under the terms of the LICENSE specified in the
// project's repository, or alternatively at http://pomona.io/
#endregion
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Pomona.Common.Internals;
namespace Pomona.Common.TypeSystem
{
public abstract class TypeResolver : ITypeResolver
{
private readonly Lazy<Dictionary<string, TypeSpec>> primitiveNameTypeMap;
private readonly IEnumerable<ITypeFactory> typeFactories;
public TypeResolver()
{
var typeSpecTypes = new[]
{
typeof(DictionaryTypeSpec),
typeof(EnumerableTypeSpec),
typeof(EnumTypeSpec),
typeof(RuntimeTypeSpec),
typeof(QueryResultType)
};
this.typeFactories =
typeSpecTypes
.SelectMany(
x =>
x.GetMethod("GetFactory", BindingFlags.Static | BindingFlags.Public)
.WrapAsEnumerable()
.Where(y => y != null && y.DeclaringType == x))
.Select(m => (ITypeFactory)m.Invoke(null, null))
.OrderBy(x => x.Priority)
.ToList();
this.primitiveNameTypeMap = new Lazy<Dictionary<string, TypeSpec>>(() =>
TypeUtils.GetNativeTypes()
.Select(FromType)
.ToDictionary(x => x.Name, x => x,
StringComparer.OrdinalIgnoreCase));
}
protected ConcurrentDictionary<Type, TypeSpec> TypeMap { get; } = new ConcurrentDictionary<Type, TypeSpec>();
protected virtual TypeSpec CreateType(Type type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
var typeSpec = this.typeFactories.Select(x => x.CreateFromType(this, type)).FirstOrDefault(x => x != null);
if (typeSpec == null)
throw new InvalidOperationException("Unable to find a TypeSpec factory for mapping type " + type);
return typeSpec;
}
/// <summary>
/// This method is responsible for mapping from a proxy or hidden clr type to an exposed type.
/// </summary>
/// <param name="type">The potentially hidden type.</param>
/// <returns>An exposed type, which will often be the same type as given in argument.</returns>
protected virtual Type MapExposedClrType(Type type)
{
return type;
}
public virtual PropertySpec FromProperty(Type reflectedType, PropertyInfo propertyInfo)
{
return FromType(reflectedType).GetPropertyByName(propertyInfo.Name, false);
}
public virtual TypeSpec FromType(string typeName)
{
TypeSpec typeSpec;
if (!TryGetTypeByName(typeName, out typeSpec))
throw new PomonaException("Type with name " + typeName + " not recognized.");
return typeSpec;
}
public virtual TypeSpec FromType(Type type)
{
type = MapExposedClrType(type);
var typeSpec = TypeMap.GetOrAdd(type, CreateType);
return typeSpec;
}
public virtual PropertySpec LoadBaseDefinition(PropertySpec propertySpec)
{
if (propertySpec == null)
throw new ArgumentNullException(nameof(propertySpec));
return propertySpec.OnLoadBaseDefinition();
}
public virtual TypeSpec LoadBaseType(TypeSpec typeSpec)
{
if (typeSpec == null)
throw new ArgumentNullException(nameof(typeSpec));
return typeSpec.OnLoadBaseType();
}
public virtual ConstructorSpec LoadConstructor(TypeSpec typeSpec)
{
if (typeSpec == null)
throw new ArgumentNullException(nameof(typeSpec));
return typeSpec.OnLoadConstructor();
}
public virtual IEnumerable<Attribute> LoadDeclaredAttributes(MemberSpec memberSpec)
{
if (memberSpec == null)
throw new ArgumentNullException(nameof(memberSpec));
return memberSpec.OnLoadDeclaredAttributes();
}
public virtual TypeSpec LoadDeclaringType(PropertySpec propertySpec)
{
if (propertySpec == null)
throw new ArgumentNullException(nameof(propertySpec));
return propertySpec.OnLoadDeclaringType();
}
public virtual IEnumerable<TypeSpec> LoadGenericArguments(TypeSpec typeSpec)
{
if (typeSpec == null)
throw new ArgumentNullException(nameof(typeSpec));
return typeSpec.OnLoadGenericArguments();
}
public virtual PropertyGetter LoadGetter(PropertySpec propertySpec)
{
if (propertySpec == null)
throw new ArgumentNullException(nameof(propertySpec));
return propertySpec.OnLoadGetter();
}
public virtual IEnumerable<TypeSpec> LoadInterfaces(TypeSpec typeSpec)
{
if (typeSpec == null)
throw new ArgumentNullException(nameof(typeSpec));
return typeSpec.OnLoadInterfaces();
}
public virtual string LoadName(MemberSpec memberSpec)
{
if (memberSpec == null)
throw new ArgumentNullException(nameof(memberSpec));
return memberSpec.OnLoadName();
}
public virtual string LoadNamespace(TypeSpec typeSpec)
{
if (typeSpec == null)
throw new ArgumentNullException(nameof(typeSpec));
return typeSpec.OnLoadNamespace();
}
public virtual IEnumerable<PropertySpec> LoadProperties(TypeSpec typeSpec)
{
if (typeSpec == null)
throw new ArgumentNullException(nameof(typeSpec));
return typeSpec.OnLoadProperties();
}
public virtual PropertyFlags LoadPropertyFlags(PropertySpec propertySpec)
{
if (propertySpec == null)
throw new ArgumentNullException(nameof(propertySpec));
return propertySpec.OnLoadPropertyFlags();
}
public virtual TypeSpec LoadPropertyType(PropertySpec propertySpec)
{
if (propertySpec == null)
throw new ArgumentNullException(nameof(propertySpec));
return propertySpec.OnLoadPropertyType();
}
public virtual IEnumerable<PropertySpec> LoadRequiredProperties(TypeSpec typeSpec)
{
if (typeSpec == null)
throw new ArgumentNullException(nameof(typeSpec));
return typeSpec.OnLoadRequiredProperties();
}
public virtual RuntimeTypeDetails LoadRuntimeTypeDetails(TypeSpec typeSpec)
{
if (typeSpec == null)
throw new ArgumentNullException(nameof(typeSpec));
return typeSpec.OnLoadRuntimeTypeDetails();
}
public virtual PropertySetter LoadSetter(PropertySpec propertySpec)
{
if (propertySpec == null)
throw new ArgumentNullException(nameof(propertySpec));
return propertySpec.OnLoadSetter();
}
public virtual ResourceType LoadUriBaseType(ResourceType resourceType)
{
if (resourceType == null)
throw new ArgumentNullException(nameof(resourceType));
return resourceType.OnLoadUriBaseType();
}
public virtual bool TryGetTypeByName(string typeName, out TypeSpec typeSpec)
{
return this.primitiveNameTypeMap.Value.TryGetValue(typeName, out typeSpec);
}
public virtual PropertySpec WrapProperty(TypeSpec typeSpec, PropertyInfo propertyInfo)
{
if (typeSpec == null)
throw new ArgumentNullException(nameof(typeSpec));
if (propertyInfo == null)
throw new ArgumentNullException(nameof(propertyInfo));
return typeSpec.OnWrapProperty(propertyInfo);
}
}
}
| |
// DirectXTK MakeSpriteFont tool
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Runtime.InteropServices;
namespace MakeSpriteFont
{
// Uses System.Drawing (aka GDI+) to rasterize TrueType fonts into a series of glyph bitmaps.
public class TrueTypeImporter : IFontImporter
{
// Properties hold the imported font data.
public IEnumerable<Glyph> Glyphs { get; private set; }
public float LineSpacing { get; private set; }
// Size of the temp surface used for GDI+ rasterization.
const int MaxGlyphSize = 1024;
public void Import(CommandLineOptions options)
{
// Create a bunch of GDI+ objects.
using (Font font = CreateFont(options))
using (Brush brush = new SolidBrush(Color.White))
using (StringFormat stringFormat = new StringFormat(StringFormatFlags.NoFontFallback))
using (Bitmap bitmap = new Bitmap(MaxGlyphSize, MaxGlyphSize, PixelFormat.Format32bppArgb))
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.PixelOffsetMode = options.Sharp ? PixelOffsetMode.None : PixelOffsetMode.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
// Which characters do we want to include?
var characters = CharacterRegion.Flatten(options.CharacterRegions);
var glyphList = new List<Glyph>();
// Rasterize each character in turn.
int count = 0;
foreach (char character in characters)
{
++count;
if (count == 500)
{
if (!options.FastPack)
{
Console.WriteLine("WARNING: capturing a large font. This may take a long time to complete and could result in too large a texture. Consider using /FastPack.");
}
Console.Write(".");
}
else if ((count % 500) == 0)
{
Console.Write(".");
}
Glyph glyph = ImportGlyph(character, font, brush, stringFormat, bitmap, graphics);
glyphList.Add(glyph);
}
if (count > 500)
{
Console.WriteLine();
}
Glyphs = glyphList;
// Store the font height.
LineSpacing = font.GetHeight();
}
}
// Attempts to instantiate the requested GDI+ font object.
static Font CreateFont(CommandLineOptions options)
{
Font font = new Font(options.SourceFont, PointsToPixels(options.FontSize), options.FontStyle, GraphicsUnit.Pixel);
try
{
// The font constructor automatically substitutes fonts if it can't find the one requested.
// But we prefer the caller to know if anything is wrong with their data. A simple string compare
// isn't sufficient because some fonts (eg. MS Mincho) change names depending on the locale.
// Early out: in most cases the name will match the current or invariant culture.
if (options.SourceFont.Equals(font.FontFamily.GetName(CultureInfo.CurrentCulture.LCID), StringComparison.OrdinalIgnoreCase) ||
options.SourceFont.Equals(font.FontFamily.GetName(CultureInfo.InvariantCulture.LCID), StringComparison.OrdinalIgnoreCase))
{
return font;
}
// Check the font name in every culture.
foreach (CultureInfo culture in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
if (options.SourceFont.Equals(font.FontFamily.GetName(culture.LCID), StringComparison.OrdinalIgnoreCase))
{
return font;
}
}
// A font substitution must have occurred.
throw new Exception(string.Format("Can't find font '{0}'.", options.SourceFont));
}
catch
{
font.Dispose();
throw;
}
}
// Converts a font size from points to pixels. Can't just let GDI+ do this for us,
// because we want identical results on every machine regardless of system DPI settings.
static float PointsToPixels(float points)
{
return points * 96 / 72;
}
// Rasterizes a single character glyph.
static Glyph ImportGlyph(char character, Font font, Brush brush, StringFormat stringFormat, Bitmap bitmap, Graphics graphics)
{
string characterString = character.ToString();
// Measure the size of this character.
SizeF size = graphics.MeasureString(characterString, font, Point.Empty, stringFormat);
int characterWidth = (int)Math.Ceiling(size.Width);
int characterHeight = (int)Math.Ceiling(size.Height);
// Pad to make sure we capture any overhangs (negative ABC spacing, etc.)
int padWidth = characterWidth;
int padHeight = characterHeight / 2;
int bitmapWidth = characterWidth + padWidth * 2;
int bitmapHeight = characterHeight + padHeight * 2;
if (bitmapWidth > MaxGlyphSize || bitmapHeight > MaxGlyphSize)
throw new Exception("Excessively large glyph won't fit in my lazily implemented fixed size temp surface.");
// Render the character.
graphics.Clear(Color.Black);
graphics.DrawString(characterString, font, brush, padWidth, padHeight, stringFormat);
graphics.Flush();
// Clone the newly rendered image.
Bitmap glyphBitmap = bitmap.Clone(new Rectangle(0, 0, bitmapWidth, bitmapHeight), PixelFormat.Format32bppArgb);
BitmapUtils.ConvertGreyToAlpha(glyphBitmap);
// Query its ABC spacing.
float? abc = GetCharacterWidth(character, font, graphics);
// Construct the output Glyph object.
return new Glyph(character, glyphBitmap)
{
XOffset = -padWidth,
XAdvance = abc.HasValue ? padWidth - bitmapWidth + abc.Value : -padWidth,
YOffset = -padHeight,
};
}
// Queries APC spacing for the specified character.
static float? GetCharacterWidth(char character, Font font, Graphics graphics)
{
// Look up the native device context and font handles.
IntPtr hdc = graphics.GetHdc();
try
{
IntPtr hFont = font.ToHfont();
try
{
// Select our font into the DC.
IntPtr oldFont = NativeMethods.SelectObject(hdc, hFont);
try
{
// Query the character spacing.
var result = new NativeMethods.ABCFloat[1];
if (NativeMethods.GetCharABCWidthsFloat(hdc, character, character, result))
{
return result[0].A +
result[0].B +
result[0].C;
}
else
{
return null;
}
}
finally
{
NativeMethods.SelectObject(hdc, oldFont);
}
}
finally
{
NativeMethods.DeleteObject(hFont);
}
}
finally
{
graphics.ReleaseHdc(hdc);
}
}
// Interop to the native GDI GetCharABCWidthsFloat method.
static class NativeMethods
{
[DllImport("gdi32.dll")]
public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hObject);
[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll", CharSet = CharSet.Unicode)]
public static extern bool GetCharABCWidthsFloat(IntPtr hdc, uint iFirstChar, uint iLastChar, [Out] ABCFloat[] lpABCF);
[StructLayout(LayoutKind.Sequential)]
public struct ABCFloat
{
public float A;
public float B;
public float C;
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.SS.Formula.Atp
{
using System;
using NPOI.SS.Formula.Eval;
/// <summary>
/// Internal calculation methods for Excel 'Analysis ToolPak' function YEARFRAC()
/// Algorithm inspired by www.dwheeler.com/yearfrac
/// @author Josh Micich
/// </summary>
/// <remarks>
/// Date Count convention
/// http://en.wikipedia.org/wiki/Day_count_convention
/// </remarks>
/// <remarks>
/// Office Online Help on YEARFRAC
/// http://office.microsoft.com/en-us/excel/HP052093441033.aspx
/// </remarks>
public class YearFracCalculator
{
/** use UTC time-zone to avoid daylight savings issues */
//private static readonly TimeZone UTC_TIME_ZONE = TimeZone.GetTimeZone("UTC");
private const int MS_PER_HOUR = 60 * 60 * 1000;
private const int MS_PER_DAY = 24 * MS_PER_HOUR;
private const int DAYS_PER_NORMAL_YEAR = 365;
private const int DAYS_PER_LEAP_YEAR = DAYS_PER_NORMAL_YEAR + 1;
/** the length of normal long months i.e. 31 */
private const int LONG_MONTH_LEN = 31;
/** the length of normal short months i.e. 30 */
private const int SHORT_MONTH_LEN = 30;
private const int SHORT_FEB_LEN = 28;
private const int LONG_FEB_LEN = SHORT_FEB_LEN + 1;
/// <summary>
/// Calculates YEARFRAC()
/// </summary>
/// <param name="pStartDateVal">The start date.</param>
/// <param name="pEndDateVal">The end date.</param>
/// <param name="basis">The basis value.</param>
/// <returns></returns>
public static double Calculate(double pStartDateVal, double pEndDateVal, int basis)
{
if (basis < 0 || basis >= 5)
{
// if basis is invalid the result is #NUM!
throw new EvaluationException(ErrorEval.NUM_ERROR);
}
// common logic for all bases
// truncate day values
int startDateVal = (int)Math.Floor(pStartDateVal);
int endDateVal = (int)Math.Floor(pEndDateVal);
if (startDateVal == endDateVal)
{
// when dates are equal, result is zero
return 0;
}
// swap start and end if out of order
if (startDateVal > endDateVal)
{
int temp = startDateVal;
startDateVal = endDateVal;
endDateVal = temp;
}
switch (basis)
{
case 0: return Basis0(startDateVal, endDateVal);
case 1: return Basis1(startDateVal, endDateVal);
case 2: return Basis2(startDateVal, endDateVal);
case 3: return Basis3(startDateVal, endDateVal);
case 4: return Basis4(startDateVal, endDateVal);
}
throw new InvalidOperationException("cannot happen");
}
/// <summary>
/// Basis 0, 30/360 date convention
/// </summary>
/// <param name="startDateVal">The start date value assumed to be less than or equal to endDateVal.</param>
/// <param name="endDateVal">The end date value assumed to be greater than or equal to startDateVal.</param>
/// <returns></returns>
public static double Basis0(int startDateVal, int endDateVal)
{
SimpleDate startDate = CreateDate(startDateVal);
SimpleDate endDate = CreateDate(endDateVal);
int date1day = startDate.day;
int date2day = endDate.day;
// basis zero has funny adjustments to the day-of-month fields when at end-of-month
if (date1day == LONG_MONTH_LEN && date2day == LONG_MONTH_LEN)
{
date1day = SHORT_MONTH_LEN;
date2day = SHORT_MONTH_LEN;
}
else if (date1day == LONG_MONTH_LEN)
{
date1day = SHORT_MONTH_LEN;
}
else if (date1day == SHORT_MONTH_LEN && date2day == LONG_MONTH_LEN)
{
date2day = SHORT_MONTH_LEN;
// Note: If date2day==31, it STAYS 31 if date1day < 30.
// Special fixes for February:
}
else if (startDate.month == 2 && IsLastDayOfMonth(startDate))
{
// Note - these assignments deliberately set Feb 30 date.
date1day = SHORT_MONTH_LEN;
if (endDate.month == 2 && IsLastDayOfMonth(endDate))
{
// only adjusted when first date is last day in Feb
date2day = SHORT_MONTH_LEN;
}
}
return CalculateAdjusted(startDate, endDate, date1day, date2day);
}
/// <summary>
/// Basis 1, Actual/Actual date convention
/// </summary>
/// <param name="startDateVal">The start date value assumed to be less than or equal to endDateVal.</param>
/// <param name="endDateVal">The end date value assumed to be greater than or equal to startDateVal.</param>
/// <returns></returns>
public static double Basis1(int startDateVal, int endDateVal)
{
SimpleDate startDate = CreateDate(startDateVal);
SimpleDate endDate = CreateDate(endDateVal);
double yearLength;
if (IsGreaterThanOneYear(startDate, endDate))
{
yearLength = AverageYearLength(startDate.year, endDate.year);
}
else if (ShouldCountFeb29(startDate, endDate))
{
yearLength = DAYS_PER_LEAP_YEAR;
}
else
{
yearLength = DAYS_PER_NORMAL_YEAR;
}
return DateDiff(startDate.ticks, endDate.ticks) / yearLength;
}
/// <summary>
/// Basis 2, Actual/360 date convention
/// </summary>
/// <param name="startDateVal">The start date value assumed to be less than or equal to endDateVal.</param>
/// <param name="endDateVal">The end date value assumed to be greater than or equal to startDateVal.</param>
/// <returns></returns>
public static double Basis2(int startDateVal, int endDateVal)
{
return (endDateVal - startDateVal) / 360.0;
}
/// <summary>
/// Basis 3, Actual/365 date convention
/// </summary>
/// <param name="startDateVal">The start date value assumed to be less than or equal to endDateVal.</param>
/// <param name="endDateVal">The end date value assumed to be greater than or equal to startDateVal.</param>
/// <returns></returns>
public static double Basis3(double startDateVal, double endDateVal)
{
return (endDateVal - startDateVal) / 365.0;
}
/// <summary>
/// Basis 4, European 30/360 date convention
/// </summary>
/// <param name="startDateVal">The start date value assumed to be less than or equal to endDateVal.</param>
/// <param name="endDateVal">The end date value assumed to be greater than or equal to startDateVal.</param>
/// <returns></returns>
public static double Basis4(int startDateVal, int endDateVal)
{
SimpleDate startDate = CreateDate(startDateVal);
SimpleDate endDate = CreateDate(endDateVal);
int date1day = startDate.day;
int date2day = endDate.day;
// basis four has funny adjustments to the day-of-month fields when at end-of-month
if (date1day == LONG_MONTH_LEN)
{
date1day = SHORT_MONTH_LEN;
}
if (date2day == LONG_MONTH_LEN)
{
date2day = SHORT_MONTH_LEN;
}
// Note - no adjustments for end of Feb
return CalculateAdjusted(startDate, endDate, date1day, date2day);
}
/// <summary>
/// Calculates the adjusted.
/// </summary>
/// <param name="startDate">The start date.</param>
/// <param name="endDate">The end date.</param>
/// <param name="date1day">The date1day.</param>
/// <param name="date2day">The date2day.</param>
/// <returns></returns>
private static double CalculateAdjusted(SimpleDate startDate, SimpleDate endDate, int date1day,
int date2day)
{
double dayCount
= (endDate.year - startDate.year) * 360
+ (endDate.month - startDate.month) * SHORT_MONTH_LEN
+ (date2day - date1day) * 1;
return dayCount / 360;
}
/// <summary>
/// Determines whether [is last day of month] [the specified date].
/// </summary>
/// <param name="date">The date.</param>
/// <returns>
/// <c>true</c> if [is last day of month] [the specified date]; otherwise, <c>false</c>.
/// </returns>
private static bool IsLastDayOfMonth(SimpleDate date)
{
if (date.day < SHORT_FEB_LEN)
{
return false;
}
return date.day == GetLastDayOfMonth(date);
}
/// <summary>
/// Gets the last day of month.
/// </summary>
/// <param name="date">The date.</param>
/// <returns></returns>
private static int GetLastDayOfMonth(SimpleDate date)
{
switch (date.month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return LONG_MONTH_LEN;
case 4:
case 6:
case 9:
case 11:
return SHORT_MONTH_LEN;
}
if (IsLeapYear(date.year))
{
return LONG_FEB_LEN;
}
return SHORT_FEB_LEN;
}
/// <summary>
/// Assumes dates are no more than 1 year apart.
/// </summary>
/// <param name="start">The start.</param>
/// <param name="end">The end.</param>
/// <returns><c>true</c>
/// if dates both within a leap year, or span a period including Feb 29</returns>
private static bool ShouldCountFeb29(SimpleDate start, SimpleDate end)
{
bool startIsLeapYear = IsLeapYear(start.year);
if (startIsLeapYear && start.year == end.year)
{
// note - dates may not actually span Feb-29, but it gets counted anyway in this case
return true;
}
bool endIsLeapYear = IsLeapYear(end.year);
if (!startIsLeapYear && !endIsLeapYear)
{
return false;
}
if (startIsLeapYear)
{
switch (start.month)
{
case SimpleDate.JANUARY:
case SimpleDate.FEBRUARY:
return true;
}
return false;
}
if (endIsLeapYear)
{
switch (end.month)
{
case SimpleDate.JANUARY:
return false;
case SimpleDate.FEBRUARY:
break;
default:
return true;
}
return end.day == LONG_FEB_LEN;
}
return false;
}
/// <summary>
/// return the whole number of days between the two time-stamps. Both time-stamps are
/// assumed to represent 12:00 midnight on the respective day.
/// </summary>
/// <param name="startDateTicks">The start date ticks.</param>
/// <param name="endDateTicks">The end date ticks.</param>
/// <returns></returns>
private static double DateDiff(long startDateTicks, long endDateTicks)
{
return new TimeSpan(endDateTicks - startDateTicks).TotalDays;
}
/// <summary>
/// Averages the length of the year.
/// </summary>
/// <param name="startYear">The start year.</param>
/// <param name="endYear">The end year.</param>
/// <returns></returns>
private static double AverageYearLength(int startYear, int endYear)
{
int dayCount = 0;
for (int i = startYear; i <= endYear; i++)
{
dayCount += DAYS_PER_NORMAL_YEAR;
if (IsLeapYear(i))
{
dayCount++;
}
}
double numberOfYears = endYear - startYear + 1;
return dayCount / numberOfYears;
}
/// <summary>
/// determine Leap Year
/// </summary>
/// <param name="i">the year</param>
/// <returns></returns>
private static bool IsLeapYear(int i)
{
// leap years are always divisible by 4
if (i % 4 != 0)
{
return false;
}
// each 4th century is a leap year
if (i % 400 == 0)
{
return true;
}
// all other centuries are *not* leap years
if (i % 100 == 0)
{
return false;
}
return true;
}
/// <summary>
/// Determines whether [is greater than one year] [the specified start].
/// </summary>
/// <param name="start">The start date.</param>
/// <param name="end">The end date.</param>
/// <returns>
/// <c>true</c> if [is greater than one year] [the specified start]; otherwise, <c>false</c>.
/// </returns>
private static bool IsGreaterThanOneYear(SimpleDate start, SimpleDate end)
{
if (start.year == end.year)
{
return false;
}
if (start.year + 1 != end.year)
{
return true;
}
if (start.month > end.month)
{
return false;
}
if (start.month < end.month)
{
return true;
}
return start.day < end.day;
}
/// <summary>
/// Creates the date.
/// </summary>
/// <param name="dayCount">The day count.</param>
/// <returns></returns>
private static SimpleDate CreateDate(int dayCount)
{
return new SimpleDate(NPOI.SS.UserModel.DateUtil.GetJavaDate(dayCount));
//DateTime dt = new DateTime(1900, 1, 1);
//return new SimpleDate(dt.AddDays(dayCount));
}
/// <summary>
/// Simple Date Wrapper
/// </summary>
private class SimpleDate
{
public const int JANUARY = 1;
public const int FEBRUARY = 2;
public int year;
/** 1-based month */
public int month;
/** day of month */
public int day;
/** milliseconds since 1970 */
public long ticks;
public SimpleDate(DateTime date)
{
year = date.Year;
month = date.Month;
day = date.Day;
ticks = date.Ticks;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime;
using System.Reflection.Runtime.General;
using Internal.Runtime;
using Internal.Runtime.TypeLoader;
using Internal.Runtime.Augments;
using Internal.Runtime.CompilerServices;
using Internal.Metadata.NativeFormat;
using Internal.NativeFormat;
using Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
namespace Internal.Runtime.TypeLoader
{
public sealed partial class TypeLoaderEnvironment
{
public bool CompareMethodSignatures(RuntimeSignature signature1, RuntimeSignature signature2)
{
if (signature1.IsNativeLayoutSignature && signature2.IsNativeLayoutSignature)
{
if(signature1.StructuralEquals(signature2))
return true;
NativeFormatModuleInfo module1 = ModuleList.GetModuleInfoByHandle(new TypeManagerHandle(signature1.ModuleHandle));
NativeReader reader1 = GetNativeLayoutInfoReader(signature1);
NativeParser parser1 = new NativeParser(reader1, signature1.NativeLayoutOffset);
NativeFormatModuleInfo module2 = ModuleList.GetModuleInfoByHandle(new TypeManagerHandle(signature2.ModuleHandle));
NativeReader reader2 = GetNativeLayoutInfoReader(signature2);
NativeParser parser2 = new NativeParser(reader2, signature2.NativeLayoutOffset);
return CompareMethodSigs(parser1, module1, parser2, module2);
}
else if (signature1.IsNativeLayoutSignature)
{
int token = signature2.Token;
MetadataReader metadataReader = ModuleList.Instance.GetMetadataReaderForModule(new TypeManagerHandle(signature2.ModuleHandle));
MethodSignatureComparer comparer = new MethodSignatureComparer(metadataReader, token.AsHandle().ToMethodHandle(metadataReader));
return comparer.IsMatchingNativeLayoutMethodSignature(signature1);
}
else if (signature2.IsNativeLayoutSignature)
{
int token = signature1.Token;
MetadataReader metadataReader = ModuleList.Instance.GetMetadataReaderForModule(new TypeManagerHandle(signature1.ModuleHandle));
MethodSignatureComparer comparer = new MethodSignatureComparer(metadataReader, token.AsHandle().ToMethodHandle(metadataReader));
return comparer.IsMatchingNativeLayoutMethodSignature(signature2);
}
else
{
// For now, RuntimeSignatures are only used to compare for method signature equality (along with their Name)
// So we can implement this with the simple equals check
if (signature1.Token != signature2.Token)
return false;
if (signature1.ModuleHandle != signature2.ModuleHandle)
return false;
return true;
}
}
public uint GetGenericArgumentCountFromMethodNameAndSignature(MethodNameAndSignature signature)
{
if (signature.Signature.IsNativeLayoutSignature)
{
NativeReader reader = GetNativeLayoutInfoReader(signature.Signature);
NativeParser parser = new NativeParser(reader, signature.Signature.NativeLayoutOffset);
return GetGenericArgCountFromSig(parser);
}
else
{
ModuleInfo module = signature.Signature.GetModuleInfo();
#if ECMA_METADATA_SUPPORT
if (module is NativeFormatModuleInfo)
#endif
{
NativeFormatModuleInfo nativeFormatModule = (NativeFormatModuleInfo)module;
var metadataReader = nativeFormatModule.MetadataReader;
var methodHandle = signature.Signature.Token.AsHandle().ToMethodHandle(metadataReader);
var method = methodHandle.GetMethod(metadataReader);
var methodSignature = method.Signature.GetMethodSignature(metadataReader);
return checked((uint)methodSignature.GenericParameterCount);
}
#if ECMA_METADATA_SUPPORT
else
{
EcmaModuleInfo ecmaModuleInfo = (EcmaModuleInfo)module;
var metadataReader = ecmaModuleInfo.MetadataReader;
var ecmaHandle = (System.Reflection.Metadata.MethodDefinitionHandle)System.Reflection.Metadata.Ecma335.MetadataTokens.Handle(signature.Signature.Token);
var method = metadataReader.GetMethodDefinition(ecmaHandle);
var blobHandle = method.Signature;
var blobReader = metadataReader.GetBlobReader(blobHandle);
byte sigByte = blobReader.ReadByte();
if ((sigByte & (byte)System.Reflection.Metadata.SignatureAttributes.Generic) == 0)
return 0;
uint genArgCount = checked((uint)blobReader.ReadCompressedInteger());
return genArgCount;
}
#endif
}
}
public bool TryGetMethodNameAndSignatureFromNativeLayoutSignature(RuntimeSignature signature, out MethodNameAndSignature nameAndSignature)
{
nameAndSignature = null;
NativeReader reader = GetNativeLayoutInfoReader(signature);
NativeParser parser = new NativeParser(reader, signature.NativeLayoutOffset);
if (parser.IsNull)
return false;
RuntimeSignature methodSig;
RuntimeSignature methodNameSig;
nameAndSignature = GetMethodNameAndSignature(ref parser, new TypeManagerHandle(signature.ModuleHandle), out methodNameSig, out methodSig);
return true;
}
public bool TryGetMethodNameAndSignaturePointersFromNativeLayoutSignature(TypeManagerHandle module, uint methodNameAndSigToken, out RuntimeSignature methodNameSig, out RuntimeSignature methodSig)
{
methodNameSig = default(RuntimeSignature);
methodSig = default(RuntimeSignature);
NativeReader reader = GetNativeLayoutInfoReader(module);
NativeParser parser = new NativeParser(reader, methodNameAndSigToken);
if (parser.IsNull)
return false;
methodNameSig = RuntimeSignature.CreateFromNativeLayoutSignature(module, parser.Offset);
string methodName = parser.GetString();
// Signatures are indirected to through a relative offset so that we don't have to parse them
// when not comparing signatures (parsing them requires resolving types and is tremendously
// expensive).
NativeParser sigParser = parser.GetParserFromRelativeOffset();
methodSig = RuntimeSignature.CreateFromNativeLayoutSignature(module, sigParser.Offset);
return true;
}
public bool TryGetMethodNameAndSignatureFromNativeLayoutOffset(TypeManagerHandle moduleHandle, uint nativeLayoutOffset, out MethodNameAndSignature nameAndSignature)
{
nameAndSignature = null;
NativeReader reader = GetNativeLayoutInfoReader(moduleHandle);
NativeParser parser = new NativeParser(reader, nativeLayoutOffset);
if (parser.IsNull)
return false;
RuntimeSignature methodSig;
RuntimeSignature methodNameSig;
nameAndSignature = GetMethodNameAndSignature(ref parser, moduleHandle, out methodNameSig, out methodSig);
return true;
}
internal MethodNameAndSignature GetMethodNameAndSignature(ref NativeParser parser, TypeManagerHandle moduleHandle, out RuntimeSignature methodNameSig, out RuntimeSignature methodSig)
{
methodNameSig = RuntimeSignature.CreateFromNativeLayoutSignature(moduleHandle, parser.Offset);
string methodName = parser.GetString();
// Signatures are indirected to through a relative offset so that we don't have to parse them
// when not comparing signatures (parsing them requires resolving types and is tremendously
// expensive).
NativeParser sigParser = parser.GetParserFromRelativeOffset();
methodSig = RuntimeSignature.CreateFromNativeLayoutSignature(moduleHandle, sigParser.Offset);
return new MethodNameAndSignature(methodName, methodSig);
}
internal bool IsStaticMethodSignature(RuntimeSignature methodSig)
{
if (methodSig.IsNativeLayoutSignature)
{
NativeReader reader = GetNativeLayoutInfoReader(methodSig);
NativeParser parser = new NativeParser(reader, methodSig.NativeLayoutOffset);
MethodCallingConvention callingConvention = (MethodCallingConvention)parser.GetUnsigned();
return callingConvention.HasFlag(MethodCallingConvention.Static);
}
else
{
ModuleInfo module = methodSig.GetModuleInfo();
#if ECMA_METADATA_SUPPORT
if (module is NativeFormatModuleInfo)
#endif
{
NativeFormatModuleInfo nativeFormatModule = (NativeFormatModuleInfo)module;
var metadataReader = nativeFormatModule.MetadataReader;
var methodHandle = methodSig.Token.AsHandle().ToMethodHandle(metadataReader);
var method = methodHandle.GetMethod(metadataReader);
return (method.Flags & MethodAttributes.Static) != 0;
}
#if ECMA_METADATA_SUPPORT
else
{
EcmaModuleInfo ecmaModuleInfo = (EcmaModuleInfo)module;
var metadataReader = ecmaModuleInfo.MetadataReader;
var ecmaHandle = (System.Reflection.Metadata.MethodDefinitionHandle)System.Reflection.Metadata.Ecma335.MetadataTokens.Handle(methodSig.Token);
var method = metadataReader.GetMethodDefinition(ecmaHandle);
var blobHandle = method.Signature;
var blobReader = metadataReader.GetBlobReader(blobHandle);
byte sigByte = blobReader.ReadByte();
return ((sigByte & (byte)System.Reflection.Metadata.SignatureAttributes.Instance) == 0);
}
#endif
}
}
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
// Create a TypeSystem.MethodSignature object from a RuntimeSignature that isn't a NativeLayoutSignature
private TypeSystem.MethodSignature TypeSystemSigFromRuntimeSignature(TypeSystemContext context, RuntimeSignature signature)
{
Debug.Assert(!signature.IsNativeLayoutSignature);
ModuleInfo module = signature.GetModuleInfo();
#if ECMA_METADATA_SUPPORT
if (module is NativeFormatModuleInfo)
#endif
{
NativeFormatModuleInfo nativeFormatModule = (NativeFormatModuleInfo)module;
var metadataReader = nativeFormatModule.MetadataReader;
var methodHandle = signature.Token.AsHandle().ToMethodHandle(metadataReader);
var metadataUnit = ((TypeLoaderTypeSystemContext)context).ResolveMetadataUnit(nativeFormatModule);
var parser = new Internal.TypeSystem.NativeFormat.NativeFormatSignatureParser(metadataUnit, metadataReader.GetMethod(methodHandle).Signature, metadataReader);
return parser.ParseMethodSignature();
}
#if ECMA_METADATA_SUPPORT
else
{
EcmaModuleInfo ecmaModuleInfo = (EcmaModuleInfo)module;
TypeSystem.Ecma.EcmaModule ecmaModule = context.ResolveEcmaModule(ecmaModuleInfo);
var ecmaHandle = System.Reflection.Metadata.Ecma335.MetadataTokens.EntityHandle(signature.Token);
MethodDesc ecmaMethod = ecmaModule.GetMethod(ecmaHandle);
return ecmaMethod.Signature;
}
#endif
}
#endif
internal bool GetCallingConverterDataFromMethodSignature(TypeSystemContext context, RuntimeSignature methodSig, Instantiation typeInstantiation, Instantiation methodInstantiation, out bool hasThis, out TypeDesc[] parameters, out bool[] parametersWithGenericDependentLayout)
{
if (methodSig.IsNativeLayoutSignature)
return GetCallingConverterDataFromMethodSignature_NativeLayout(context, methodSig, typeInstantiation, methodInstantiation, out hasThis, out parameters, out parametersWithGenericDependentLayout);
else
{
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
var sig = TypeSystemSigFromRuntimeSignature(context, methodSig);
return GetCallingConverterDataFromMethodSignature_MethodSignature(sig, typeInstantiation, methodInstantiation, out hasThis, out parameters, out parametersWithGenericDependentLayout);
#else
parametersWithGenericDependentLayout = null;
hasThis = false;
parameters = null;
return false;
#endif
}
}
internal bool GetCallingConverterDataFromMethodSignature_NativeLayout(TypeSystemContext context, RuntimeSignature methodSig, Instantiation typeInstantiation, Instantiation methodInstantiation, out bool hasThis, out TypeDesc[] parameters, out bool[] parametersWithGenericDependentLayout)
{
return GetCallingConverterDataFromMethodSignature_NativeLayout_Common(
context,
methodSig,
typeInstantiation,
methodInstantiation,
out hasThis,
out parameters,
out parametersWithGenericDependentLayout,
null,
null);
}
internal bool GetCallingConverterDataFromMethodSignature_NativeLayout_Common(
TypeSystemContext context,
RuntimeSignature methodSig,
Instantiation typeInstantiation,
Instantiation methodInstantiation,
out bool hasThis,
out TypeDesc[] parameters,
out bool[] parametersWithGenericDependentLayout,
NativeReader nativeReader,
ulong[] debuggerPreparedExternalReferences)
{
bool isNotDebuggerCall = debuggerPreparedExternalReferences == null ;
hasThis = false;
parameters = null;
NativeLayoutInfoLoadContext nativeLayoutContext = new NativeLayoutInfoLoadContext();
nativeLayoutContext._module = isNotDebuggerCall ? (NativeFormatModuleInfo)methodSig.GetModuleInfo() : null;
nativeLayoutContext._typeSystemContext = context;
nativeLayoutContext._typeArgumentHandles = typeInstantiation;
nativeLayoutContext._methodArgumentHandles = methodInstantiation;
nativeLayoutContext._debuggerPreparedExternalReferences = debuggerPreparedExternalReferences;
NativeFormatModuleInfo module = null;
NativeReader reader = null;
if (isNotDebuggerCall)
{
reader = GetNativeLayoutInfoReader(methodSig);
module = ModuleList.Instance.GetModuleInfoByHandle(new TypeManagerHandle(methodSig.ModuleHandle));
}
else
{
reader = nativeReader;
}
NativeParser parser = new NativeParser(reader, methodSig.NativeLayoutOffset);
MethodCallingConvention callingConvention = (MethodCallingConvention)parser.GetUnsigned();
hasThis = !callingConvention.HasFlag(MethodCallingConvention.Static);
uint numGenArgs = callingConvention.HasFlag(MethodCallingConvention.Generic) ? parser.GetUnsigned() : 0;
uint parameterCount = parser.GetUnsigned();
parameters = new TypeDesc[parameterCount + 1];
parametersWithGenericDependentLayout = new bool[parameterCount + 1];
// One extra parameter to account for the return type
for (uint i = 0; i <= parameterCount; i++)
{
// NativeParser is a struct, so it can be copied.
NativeParser parserCopy = parser;
// Parse the signature twice. The first time to find out the exact type of the signature
// The second time to identify if the parameter loaded via the signature should be forced to be
// passed byref as part of the universal generic calling convention.
parameters[i] = GetConstructedTypeFromParserAndNativeLayoutContext(ref parser, nativeLayoutContext);
parametersWithGenericDependentLayout[i] = TypeSignatureHasVarsNeedingCallingConventionConverter(ref parserCopy, module, context, HasVarsInvestigationLevel.Parameter);
if (parameters[i] == null)
return false;
}
return true;
}
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
private static bool GetCallingConverterDataFromMethodSignature_MethodSignature(TypeSystem.MethodSignature methodSignature, Instantiation typeInstantiation, Instantiation methodInstantiation, out bool hasThis, out TypeDesc[] parameters, out bool[] parametersWithGenericDependentLayout)
{
// Compute parameters dependent on generic instantiation for their layout
parametersWithGenericDependentLayout = new bool[methodSignature.Length + 1];
parametersWithGenericDependentLayout[0] = UniversalGenericParameterLayout.IsLayoutDependentOnGenericInstantiation(methodSignature.ReturnType);
for (int i = 0; i < methodSignature.Length; i++)
{
parametersWithGenericDependentLayout[i + 1] = UniversalGenericParameterLayout.IsLayoutDependentOnGenericInstantiation(methodSignature[i]);
}
// Compute hasThis-ness
hasThis = !methodSignature.IsStatic;
// Compute parameter exact types
parameters = new TypeDesc[methodSignature.Length + 1];
parameters[0] = methodSignature.ReturnType.InstantiateSignature(typeInstantiation, methodInstantiation);
for (int i = 0; i < methodSignature.Length; i++)
{
parameters[i + 1] = methodSignature[i].InstantiateSignature(typeInstantiation, methodInstantiation);
}
return true;
}
#endif
internal bool MethodSignatureHasVarsNeedingCallingConventionConverter(TypeSystemContext context, RuntimeSignature methodSig)
{
if (methodSig.IsNativeLayoutSignature)
return MethodSignatureHasVarsNeedingCallingConventionConverter_NativeLayout(context, methodSig);
else
{
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
var sig = TypeSystemSigFromRuntimeSignature(context, methodSig);
return UniversalGenericParameterLayout.MethodSignatureHasVarsNeedingCallingConventionConverter(sig);
#else
Environment.FailFast("Cannot parse signature");
return false;
#endif
}
}
private bool MethodSignatureHasVarsNeedingCallingConventionConverter_NativeLayout(TypeSystemContext context, RuntimeSignature methodSig)
{
NativeReader reader = GetNativeLayoutInfoReader(methodSig);
NativeParser parser = new NativeParser(reader, methodSig.NativeLayoutOffset);
NativeFormatModuleInfo module = ModuleList.Instance.GetModuleInfoByHandle(new TypeManagerHandle(methodSig.ModuleHandle));
MethodCallingConvention callingConvention = (MethodCallingConvention)parser.GetUnsigned();
uint numGenArgs = callingConvention.HasFlag(MethodCallingConvention.Generic) ? parser.GetUnsigned() : 0;
uint parameterCount = parser.GetUnsigned();
// Check the return type of the method
if (TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, module, context, HasVarsInvestigationLevel.Parameter))
return true;
// Check the parameters of the method
for (uint i = 0; i < parameterCount; i++)
{
if (TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, module, context, HasVarsInvestigationLevel.Parameter))
return true;
}
return false;
}
#region Private Helpers
private enum HasVarsInvestigationLevel
{
Parameter,
NotParameter,
Ignore
}
/// <summary>
/// IF THESE SEMANTICS EVER CHANGE UPDATE THE LOGIC WHICH DEFINES THIS BEHAVIOR IN
/// THE DYNAMIC TYPE LOADER AS WELL AS THE COMPILER.
/// (There is a version of this in UniversalGenericParameterLayout.cs that must be kept in sync with this.)
///
/// Parameter's are considered to have type layout dependent on their generic instantiation
/// if the type of the parameter in its signature is a type variable, or if the type is a generic
/// structure which meets 2 characteristics:
/// 1. Structure size/layout is affected by the size/layout of one or more of its generic parameters
/// 2. One or more of the generic parameters is a type variable, or a generic structure which also recursively
/// would satisfy constraint 2. (Note, that in the recursion case, whether or not the structure is affected
/// by the size/layout of its generic parameters is not investigated.)
///
/// Examples parameter types, and behavior.
///
/// T = true
/// List[T] = false
/// StructNotDependentOnArgsForSize[T] = false
/// GenStructDependencyOnArgsForSize[T] = true
/// StructNotDependentOnArgsForSize[GenStructDependencyOnArgsForSize[T]] = true
/// StructNotDependentOnArgsForSize[GenStructDependencyOnArgsForSize[List[T]]]] = false
///
/// Example non-parameter type behavior
/// T = true
/// List[T] = false
/// StructNotDependentOnArgsForSize[T] = *true*
/// GenStructDependencyOnArgsForSize[T] = true
/// StructNotDependentOnArgsForSize[GenStructDependencyOnArgsForSize[T]] = true
/// StructNotDependentOnArgsForSize[GenStructDependencyOnArgsForSize[List[T]]]] = false
/// </summary>
private bool TypeSignatureHasVarsNeedingCallingConventionConverter(ref NativeParser parser, NativeFormatModuleInfo moduleHandle, TypeSystemContext context, HasVarsInvestigationLevel investigationLevel)
{
uint data;
var kind = parser.GetTypeSignatureKind(out data);
switch (kind)
{
case TypeSignatureKind.External: return false;
case TypeSignatureKind.Variable: return true;
case TypeSignatureKind.BuiltIn: return false;
case TypeSignatureKind.Lookback:
{
var lookbackParser = parser.GetLookbackParser(data);
return TypeSignatureHasVarsNeedingCallingConventionConverter(ref lookbackParser, moduleHandle, context, investigationLevel);
}
case TypeSignatureKind.Instantiation:
{
RuntimeTypeHandle genericTypeDef;
if (!TryGetTypeFromSimpleTypeSignature(ref parser, moduleHandle, out genericTypeDef))
{
Debug.Assert(false);
return true; // Returning true will prevent further reading from the native parser
}
if (!RuntimeAugments.IsValueType(genericTypeDef))
{
// Reference types are treated like pointers. No calling convention conversion needed. Just consume the rest of the signature.
for (uint i = 0; i < data; i++)
TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, moduleHandle, context, HasVarsInvestigationLevel.Ignore);
return false;
}
else
{
bool result = false;
for (uint i = 0; i < data; i++)
result = TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, moduleHandle, context, HasVarsInvestigationLevel.NotParameter) || result;
if ((result == true) && (investigationLevel == HasVarsInvestigationLevel.Parameter))
{
if (!TryComputeHasInstantiationDeterminedSize(genericTypeDef, context, out result))
Environment.FailFast("Unable to setup calling convention converter correctly");
return result;
}
return result;
}
}
case TypeSignatureKind.Modifier:
{
// Arrays, pointers and byref types signatures are treated as pointers, not requiring calling convention conversion.
// Just consume the parameter type from the stream and return false;
TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, moduleHandle, context, HasVarsInvestigationLevel.Ignore);
return false;
}
case TypeSignatureKind.MultiDimArray:
{
// No need for a calling convention converter for this case. Just consume the signature from the stream.
TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, moduleHandle, context, HasVarsInvestigationLevel.Ignore);
uint boundCount = parser.GetUnsigned();
for (uint i = 0; i < boundCount; i++)
parser.GetUnsigned();
uint lowerBoundCount = parser.GetUnsigned();
for (uint i = 0; i < lowerBoundCount; i++)
parser.GetUnsigned();
}
return false;
case TypeSignatureKind.FunctionPointer:
{
// No need for a calling convention converter for this case. Just consume the signature from the stream.
uint argCount = parser.GetUnsigned();
for (uint i = 0; i < argCount; i++)
TypeSignatureHasVarsNeedingCallingConventionConverter(ref parser, moduleHandle, context, HasVarsInvestigationLevel.Ignore);
}
return false;
default:
parser.ThrowBadImageFormatException();
return true;
}
}
private bool TryGetTypeFromSimpleTypeSignature(ref NativeParser parser, NativeFormatModuleInfo moduleHandle, out RuntimeTypeHandle typeHandle)
{
uint data;
TypeSignatureKind kind = parser.GetTypeSignatureKind(out data);
if (kind == TypeSignatureKind.Lookback)
{
var lookbackParser = parser.GetLookbackParser(data);
return TryGetTypeFromSimpleTypeSignature(ref lookbackParser, moduleHandle, out typeHandle);
}
else if (kind == TypeSignatureKind.External)
{
typeHandle = GetExternalTypeHandle(moduleHandle, data);
return true;
}
else if (kind == TypeSignatureKind.BuiltIn)
{
typeHandle = ((WellKnownType)data).GetRuntimeTypeHandle();
return true;
}
// Not a simple type signature... requires more work to skip
typeHandle = default(RuntimeTypeHandle);
return false;
}
private RuntimeTypeHandle GetExternalTypeHandle(NativeFormatModuleInfo moduleHandle, uint typeIndex)
{
Debug.Assert(moduleHandle != null);
RuntimeTypeHandle result;
TypeSystemContext context = TypeSystemContextFactory.Create();
{
NativeLayoutInfoLoadContext nativeLayoutContext = new NativeLayoutInfoLoadContext();
nativeLayoutContext._module = moduleHandle;
nativeLayoutContext._typeSystemContext = context;
TypeDesc type = nativeLayoutContext.GetExternalType(typeIndex);
result = type.RuntimeTypeHandle;
}
TypeSystemContextFactory.Recycle(context);
Debug.Assert(!result.IsNull());
return result;
}
private uint GetGenericArgCountFromSig(NativeParser parser)
{
MethodCallingConvention callingConvention = (MethodCallingConvention)parser.GetUnsigned();
if ((callingConvention & MethodCallingConvention.Generic) == MethodCallingConvention.Generic)
{
return parser.GetUnsigned();
}
else
{
return 0;
}
}
private bool CompareMethodSigs(NativeParser parser1, NativeFormatModuleInfo moduleHandle1, NativeParser parser2, NativeFormatModuleInfo moduleHandle2)
{
MethodCallingConvention callingConvention1 = (MethodCallingConvention)parser1.GetUnsigned();
MethodCallingConvention callingConvention2 = (MethodCallingConvention)parser2.GetUnsigned();
if (callingConvention1 != callingConvention2)
return false;
if ((callingConvention1 & MethodCallingConvention.Generic) == MethodCallingConvention.Generic)
{
if (parser1.GetUnsigned() != parser2.GetUnsigned())
return false;
}
uint parameterCount1 = parser1.GetUnsigned();
uint parameterCount2 = parser2.GetUnsigned();
if (parameterCount1 != parameterCount2)
return false;
// Compare one extra parameter to account for the return type
for (uint i = 0; i <= parameterCount1; i++)
{
if (!CompareTypeSigs(ref parser1, moduleHandle1, ref parser2, moduleHandle2))
return false;
}
return true;
}
private bool CompareTypeSigs(ref NativeParser parser1, NativeFormatModuleInfo moduleHandle1, ref NativeParser parser2, NativeFormatModuleInfo moduleHandle2)
{
// startOffset lets us backtrack to the TypeSignatureKind for external types since the TypeLoader
// expects to read it in.
uint data1;
uint startOffset1 = parser1.Offset;
var typeSignatureKind1 = parser1.GetTypeSignatureKind(out data1);
// If the parser is at a lookback type, get a new parser for it and recurse.
// Since we haven't read the element type of parser2 yet, we just pass it in unchanged
if (typeSignatureKind1 == TypeSignatureKind.Lookback)
{
NativeParser lookbackParser1 = parser1.GetLookbackParser(data1);
return CompareTypeSigs(ref lookbackParser1, moduleHandle1, ref parser2, moduleHandle2);
}
uint data2;
uint startOffset2 = parser2.Offset;
var typeSignatureKind2 = parser2.GetTypeSignatureKind(out data2);
// If parser2 is a lookback type, we need to rewind parser1 to its startOffset1
// before recursing.
if (typeSignatureKind2 == TypeSignatureKind.Lookback)
{
NativeParser lookbackParser2 = parser2.GetLookbackParser(data2);
parser1 = new NativeParser(parser1.Reader, startOffset1);
return CompareTypeSigs(ref parser1, moduleHandle1, ref lookbackParser2, moduleHandle2);
}
if (typeSignatureKind1 != typeSignatureKind2)
return false;
switch (typeSignatureKind1)
{
case TypeSignatureKind.Lookback:
{
// Recursion above better have removed all lookbacks
Debug.Fail("Unexpected lookback type");
return false;
}
case TypeSignatureKind.Modifier:
{
// Ensure the modifier kind (vector, pointer, byref) is the same
if (data1 != data2)
return false;
return CompareTypeSigs(ref parser1, moduleHandle1, ref parser2, moduleHandle2);
}
case TypeSignatureKind.Variable:
{
// variable index is in data
if (data1 != data2)
return false;
break;
}
case TypeSignatureKind.MultiDimArray:
{
// rank is in data
if (data1 != data2)
return false;
if (!CompareTypeSigs(ref parser1, moduleHandle1, ref parser2, moduleHandle2))
return false;
uint boundCount1 = parser1.GetUnsigned();
uint boundCount2 = parser2.GetUnsigned();
if (boundCount1 != boundCount2)
return false;
for (uint i = 0; i < boundCount1; i++)
{
if (parser1.GetUnsigned() != parser2.GetUnsigned())
return false;
}
uint lowerBoundCount1 = parser1.GetUnsigned();
uint lowerBoundCount2 = parser2.GetUnsigned();
if (lowerBoundCount1 != lowerBoundCount2)
return false;
for (uint i = 0; i < lowerBoundCount1; i++)
{
if (parser1.GetUnsigned() != parser2.GetUnsigned())
return false;
}
break;
}
case TypeSignatureKind.FunctionPointer:
{
// callingConvention is in data
if (data1 != data2)
return false;
uint argCount1 = parser1.GetUnsigned();
uint argCount2 = parser2.GetUnsigned();
if (argCount1 != argCount2)
return false;
for (uint i = 0; i < argCount1; i++)
{
if (!CompareTypeSigs(ref parser1, moduleHandle1, ref parser2, moduleHandle2))
return false;
}
break;
}
case TypeSignatureKind.Instantiation:
{
// Type parameter count is in data
if (data1 != data2)
return false;
if (!CompareTypeSigs(ref parser1, moduleHandle1, ref parser2, moduleHandle2))
return false;
for (uint i = 0; i < data1; i++)
{
if (!CompareTypeSigs(ref parser1, moduleHandle1, ref parser2, moduleHandle2))
return false;
}
break;
}
case TypeSignatureKind.BuiltIn:
RuntimeTypeHandle typeHandle3 = ((WellKnownType)data1).GetRuntimeTypeHandle();
RuntimeTypeHandle typeHandle4 = ((WellKnownType)data2).GetRuntimeTypeHandle();
if (!typeHandle3.Equals(typeHandle4))
return false;
break;
case TypeSignatureKind.External:
{
RuntimeTypeHandle typeHandle1 = GetExternalTypeHandle(moduleHandle1, data1);
RuntimeTypeHandle typeHandle2 = GetExternalTypeHandle(moduleHandle2, data2);
if (!typeHandle1.Equals(typeHandle2))
return false;
break;
}
default:
return false;
}
return true;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection.Emit;
using System.Text;
using CSR.Parser;
namespace CSR.AST
{
/// <summary>
/// Abstract Statement class from which all statements inherit
/// </summary>
abstract class Statement
{
// Token is remembered for error reporting
public Token t;
/// <summary>
/// Creates a new Statement
/// </summary>
public Statement()
{
returns = false;
}
/// <summary>
/// Evaluates this node and all children recursively
/// </summary>
/// <param name="scope">The scope of this statement</param>
/// <returns>Statement object after evaluation</returns>
public abstract Statement Evaluate(Scope scope);
/// <summary>
/// True if this node or any of its children contains a return statement which will be executed in any
/// given context
/// </summary>
public bool returns;
/// <summary>
/// Emits code for this statement
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this statement</param>
public abstract void EmitCode(ILGenerator ilGen, Scope scope);
}
/// <summary>
/// BlockStatements wrap a list of inner statements
/// </summary>
class BlockStatement : Statement
{
// List of inner statements
public List<Statement> statements;
/// <summary>
/// Creates a new BlockStatement
/// </summary>
public BlockStatement()
: base()
{
statements = new List<Statement>();
}
/// <summary>
/// Adds a statement to the list of inner statements
/// </summary>
/// <param name="stmt">Statement to add</param>
public void AddStatement(Statement stmt)
{
statements.Add(stmt);
}
/// <summary>
/// Evaluates this node and all its children
/// </summary>
/// <param name="scope">The scope of this statement</param>
/// <returns></returns>
public override Statement Evaluate(Scope scope)
{
// Only evaluation needed for block statements is dead code elimination - statements following a return statement
// which will never be executed
int i = 0;
// Iterate through all inner statements
while (i < statements.Count)
{
// Evaluate inner statement
statements[i] = statements[i].Evaluate(scope);
// If statement is null after evaluation, drop it
if (statements[i] == null)
{
statements.RemoveAt(i);
continue;
}
// Check if this statment is or contains a return statement
if (statements[i].returns)
{
// If so, mark this statement as returning too
returns = true;
// Check for code beyond this statment
if (i < statements.Count - 1)
{
// Unreachable code detected - issue a warning
Compiler.Compiler.errors.Warning(statements[i + 1].t.line, statements[i + 1].t.col, "unreachable code detected");
// Remove unreachable code
while (i < statements.Count - 1)
{
statements.RemoveAt(i + 1);
}
}
}
i++;
}
return this;
}
/// <summary>
/// Emits code for this statement
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this statement</param>
public override void EmitCode(ILGenerator ilGen, Scope scope)
{
// Emit code for each inner statement
foreach (Statement stmt in statements)
{
stmt.EmitCode(ilGen, scope);
}
}
}
/// <summary>
/// CallStatement represents a method call expression for which the return value is ignored
/// </summary>
class CallStatement : Statement
{
// Contained call expression
public CallExpression expr;
/// <summary>
/// Creates a new CallStatement given a CallExpression
/// </summary>
/// <param name="expr">CallExpression object</param>
public CallStatement(Expression expr)
: base()
{
this.expr = expr as CallExpression;
}
/// <summary>
/// Evaluates this node and all of its children
/// </summary>
/// <param name="scope">The scope of this statement</param>
/// <returns></returns>
public override Statement Evaluate(Scope scope)
{
// Just evaluate inner call expression
expr = expr.Evaluate(scope) as CallExpression;
return this;
}
/// <summary>
/// Emits code for this statement
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this statement</param>
public override void EmitCode(ILGenerator ilGen, Scope scope)
{
// Emit cod for the inner call expression
expr.EmitCode(ilGen, scope);
// If call returns an unsupported type or a non-void value, pop it from the stack
if (expr.returnType.Equals(PrimitiveType.UNSUPPORTED) || !expr.returnType.Equals(PrimitiveType.VOID))
{
ilGen.Emit(OpCodes.Pop);
}
}
}
/// <summary>
/// ReturnStatement represents a return statement which imediately exists the current function
/// </summary>
class ReturnStatement : Statement
{
// Expression to return from the function
public Expression expr;
/// <summary>
/// Creates a new ReturnStatement
/// </summary>
public ReturnStatement()
: base()
{
returns = true;
}
/// <summary>
/// Evaluates this node and all of its children
/// </summary>
/// <param name="scope">The scope of this statement</param>
/// <returns></returns>
public override Statement Evaluate(Scope scope)
{
LocalScope localScope = scope as LocalScope;
// If expr is not null, we must match return value with function return type
if (expr != null)
{
// Evaluate inner expression
expr.Evaluate(scope);
// If return type is different than function return type
if (!expr.returnType.Equals(localScope.returnType))
{
// Check if an implicit typecast exists
if (expr.returnType.IsCompatible(localScope.returnType))
{
// Create typecast
CastExpression newExpr = new CastExpression(localScope.returnType);
newExpr.operand = expr;
this.expr = newExpr;
}
else
{
// Issue error
Compiler.Compiler.errors.SemErr(t.line, t.col, "invalid return type");
}
}
}
else
{
// If function returns void but we provide a different type
if (localScope.returnType.ToCLRType() != Type.GetType("System.Void"))
{
// Issue error
Compiler.Compiler.errors.SemErr(t.line, t.col, "function should return " + localScope.returnType);
}
}
return this;
}
/// <summary>
/// Emits code for this statement
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this statement</param>
public override void EmitCode(ILGenerator ilGen, Scope scope)
{
// If expression is not null, issue code for the expression
if (expr != null)
{
expr.EmitCode(ilGen, scope);
}
// Emit ret to exit current method
ilGen.Emit(OpCodes.Ret);
}
}
/// <summary>
/// AssignementStatements have a valid, assignable left-side expression and a right-side
/// expression to assign
/// </summary>
class AssignementStatement : Statement
{
// Expressions
public Expression leftSide;
public Expression rightSide;
/// <summary>
/// Creates a new AssignementExpression given a left-side expression and a right-side expression
/// </summary>
/// <param name="leftSide">Left-side expression</param>
/// <param name="rightSide">Right-side expression</param>
public AssignementStatement(Expression leftSide, Expression rightSide)
: base()
{
this.leftSide = leftSide;
this.rightSide = rightSide;
}
/// <summary>
/// Evaluates this node and all of its children
/// </summary>
/// <param name="scope">The scope of this statement</param>
/// <returns></returns>
public override Statement Evaluate(Scope scope)
{
// Check if left-side expression is assignable
if (!(leftSide is AssignableExpression))
{
// Issue error
Compiler.Compiler.errors.SemErr(t.line, t.col, "Left side cannot be assigned to");
return this;
}
// Evaluate both expressions
leftSide = leftSide.Evaluate(scope);
rightSide = rightSide.Evaluate(scope);
return this;
}
/// <summary>
/// Emits code for this statement
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this statement</param>
public override void EmitCode(ILGenerator ilGen, Scope scope)
{
// Call the EmitAssignement method of the AssignableExpression object
(leftSide as AssignableExpression).EmitAssignement(ilGen, scope, rightSide);
}
}
/// <summary>
/// IfStatements represent conditional statements defined by a condition expression, an if-branch statement and an
/// optional else-branch statement
/// </summary>
class IfStatement : Statement
{
// Condition expression and branch statements
public Expression condition;
public Statement ifBranch;
public Statement elseBranch;
/// <summary>
/// Creates a new IfStatement
/// </summary>
public IfStatement()
: base()
{
}
/// <summary>
/// Evaluates this node and all of its children
/// </summary>
/// <param name="scope">The scope of this statement</param>
/// <returns></returns>
public override Statement Evaluate(Scope scope)
{
// Evaluate the condition
condition = condition.Evaluate(scope);
// Evaluate the if branch
ifBranch = ifBranch.Evaluate(scope);
// Evaluate the else branch if it exists
if (elseBranch != null)
{
elseBranch = elseBranch.Evaluate(scope);
// Propagate return state if both branches return
// This is the only case in which we can make sure code following the statement won't be reached
returns = ifBranch.returns && elseBranch.returns;
}
// Perform dead code elimination if the value of the condition can be evaluated at compile time
if (condition is ConstantExpression)
{
// If condition always holds, replace statement with the if branch
if ((condition as ConstantExpression).IsTrue())
return ifBranch;
else
// If an else branch exists, replace statemnt with it, if not, drop statement
if (elseBranch != null)
return elseBranch;
else
return null;
}
return this;
}
/// <summary>
/// Emits code for this statement
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this statement</param>
public override void EmitCode(ILGenerator ilGen, Scope scope)
{
// Emit code for the condition expression
condition.EmitCode(ilGen, scope);
// Define labels
Label elseLabel = ilGen.DefineLabel();
Label endLabel = ilGen.DefineLabel();
if (elseBranch != null)
{
// If else branch exists, jump to it if top stack value is 0
ilGen.Emit(OpCodes.Brfalse, elseLabel);
}
else
{
// If not, jump at the end of the statement
ilGen.Emit(OpCodes.Brfalse, endLabel);
}
// Emit code for if branch
ifBranch.EmitCode(ilGen, scope);
if (elseBranch != null)
{
// If else branch exists, emit jump past it to the end of the statement
ilGen.Emit(OpCodes.Br, endLabel);
// Mark else branch label
ilGen.MarkLabel(elseLabel);
// Emit code for else branch
elseBranch.EmitCode(ilGen, scope);
}
// Mark end label
ilGen.MarkLabel(endLabel);
}
}
/// <summary>
/// WhileStatements represent a repetitive statement and a conditional expression, the condition being evaluated first
/// </summary>
class WhileStatement : Statement
{
// Condition expression and repetitive statement
public Expression condition;
public Statement body;
/// <summary>
/// Creates a new WhileStatement
/// </summary>
public WhileStatement()
: base()
{
}
/// <summary>
/// Evaluates this node and all of its children
/// </summary>
/// <param name="scope">The scope of this statement</param>
/// <returns></returns>
public override Statement Evaluate(Scope scope)
{
// Evaluate condition
condition = condition.Evaluate(scope);
// Evaluate repetitive statement
body = body.Evaluate(scope);
// Perform dead code elimination if the value of the condition can be evaluated at compile time
if (condition is ConstantExpression)
{
// If condition is always false, drop statement
if (!(condition as ConstantExpression).IsTrue())
return null;
}
return this;
}
/// <summary>
/// Emits code for this statement
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this statement</param>
public override void EmitCode(ILGenerator ilGen, Scope scope)
{
// Define labels
Label loopLabel = ilGen.DefineLabel();
Label endLabel = ilGen.DefineLabel();
// Mark the start of the loop
ilGen.MarkLabel(loopLabel);
// Emit code for the condition
condition.EmitCode(ilGen, scope);
// If the value on top of the stack evaluates to 0, jump to the end of the statement
ilGen.Emit(OpCodes.Brfalse, endLabel);
// Emit code for the repetitive statement
body.EmitCode(ilGen, scope);
// Jump to the beginning of the statement
ilGen.Emit(OpCodes.Br, loopLabel);
// Mark end label
ilGen.MarkLabel(endLabel);
}
}
/// <summary>
/// DoWhileStatements represent a repetitive statement and a conditional expression, the condition being evaluated
/// after the repetitive statement runs once
/// </summary>
class DoWhileStatement : Statement
{
// Condition expression and repetitive statement
public Expression condition;
public Statement body;
/// <summary>
/// Creates a new DoWhileStatement
/// </summary>
public DoWhileStatement()
: base()
{
}
/// <summary>
/// Evaluates this node and all of its children
/// </summary>
/// <param name="scope">The scope of this statement</param>
/// <returns></returns>
public override Statement Evaluate(Scope scope)
{
// Evaluate condition expression
condition = condition.Evaluate(scope);
// Evaluate repetitive statement
body = body.Evaluate(scope);
// Perform dead code elimination if the value of the condition can be evaluated at compile time
if (condition is ConstantExpression)
{
// If it is always false, replace the statement with the inner repetitive statement
if (!(condition as ConstantExpression).IsTrue())
return body;
}
// Propagate return state - if inner statement returns, no code following this statement
// will be reached
returns = body.returns;
return this;
}
/// <summary>
/// Emits code for this statement
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this statement</param>
public override void EmitCode(ILGenerator ilGen, Scope scope)
{
// Define label
Label loopLabel = ilGen.DefineLabel();
// Mark label at beginning of statement
ilGen.MarkLabel(loopLabel);
// Emit code for the inner statement
body.EmitCode(ilGen, scope);
// Emit code for the condition expression
condition.EmitCode(ilGen, scope);
// If the value on top of the stack is different than 0, jump to beginning of statement
ilGen.Emit(OpCodes.Brtrue, loopLabel);
}
}
/// <summary>
/// Specifies weather the parameter of the for loop is increased or decreased
/// </summary>
enum ForDirection
{
Up,
Down
}
/// <summary>
/// ForStatements represent a statement with an integer parameter starting at a given value, while the parameter
/// is different than another given value, a repetitive statement is executed then the parameter is increased
/// or decreased
/// </summary>
class ForStatement : Statement
{
// Parameter - must be an assignable expression
public Expression variable;
// Expressions representing the initial and final values
public Expression initial;
public Expression final;
// Repetitive statement
public Statement body;
// Specifies if the parameter is increased or decreased
public ForDirection direction;
/// <summary>
/// Creates a new ForStatement
/// </summary>
public ForStatement()
: base()
{
}
/// <summary>
/// Evaluates this node and all of its children
/// </summary>
/// <param name="scope">The scope of this statement</param>
/// <returns></returns>
public override Statement Evaluate(Scope scope)
{
if (!(variable is AssignableExpression))
{
// If variable is not assignable expression, issue error
Compiler.Compiler.errors.SemErr(t.line, t.col, "Invalid variable for FOR statement");
return this;
}
// Evaluate all child nodes
variable = variable.Evaluate(scope);
initial = initial.Evaluate(scope);
final = final.Evaluate(scope);
body = body.Evaluate(scope);
return this;
}
/// <summary>
/// Emits code for this statement
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this statement</param>
public override void EmitCode(ILGenerator ilGen, Scope scope)
{
// Define labels
Label loopLabel = ilGen.DefineLabel();
Label endLabel = ilGen.DefineLabel();
// Call EmitAssignement for parameter, assigning it the initial expression
(variable as AssignableExpression).EmitAssignement(ilGen, scope, initial);
// Mark beginning of loop
ilGen.MarkLabel(loopLabel);
// Emit parameter code (load value onto the stack)
variable.EmitCode(ilGen, scope);
// Emit final expression (load expression value onto the stack)
final.EmitCode(ilGen, scope);
// If parameter is increased
if (direction == ForDirection.Up)
{
// If parameter is greater than final, jump to the end of the statement
ilGen.Emit(OpCodes.Bgt, endLabel);
}
// If parameter is decreased
else
{
// If parameter is less than final, jump to the end of the statement
ilGen.Emit(OpCodes.Blt, endLabel);
}
// Emit code for repetitive statement
body.EmitCode(ilGen, scope);
// Increment or decrement parameter:
// Create a new binary expression with the parameter as left operand
BinaryExpression step = new BinaryExpression(variable);
// If parameter is increasing, operator is Add, if it is decreasing, operator is Sub
step.op = direction == ForDirection.Up ? BinaryOperator.Add : BinaryOperator.Sub;
// Right operand is 1
step.rightOperand = new ConstantExpression(Primitive.Int, "1");
// Emit assignement - parameter is assigned the result of the binary expression
(variable as AssignableExpression).EmitAssignement(ilGen, scope, step);
// Emit unconditional break to beginning of loop
ilGen.Emit(OpCodes.Br, loopLabel);
// Mark end label
ilGen.MarkLabel(endLabel);
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Logging;
using QuantConnect.Util;
namespace QuantConnect.ToolBox.DukascopyDownloader
{
/// <summary>
/// Dukascopy Data Downloader class
/// </summary>
public class DukascopyDataDownloader : IDataDownloader
{
private readonly DukascopySymbolMapper _symbolMapper = new DukascopySymbolMapper();
private const int DukascopyTickLength = 20;
/// <summary>
/// Checks if downloader can get the data for the symbol
/// </summary>
/// <param name="symbol"></param>
/// <returns>Returns true if the symbol is available</returns>
public bool HasSymbol(string symbol)
{
return _symbolMapper.IsKnownLeanSymbol(Symbol.Create(symbol, GetSecurityType(symbol), Market.Dukascopy));
}
/// <summary>
/// Gets the security type for the specified symbol
/// </summary>
/// <param name="symbol">The symbol</param>
/// <returns>The security type</returns>
public SecurityType GetSecurityType(string symbol)
{
return _symbolMapper.GetLeanSecurityType(symbol);
}
/// <summary>
/// Get historical data enumerable for a single symbol, type and resolution given this start and end time (in UTC).
/// </summary>
/// <param name="dataDownloaderGetParameters">model class for passing in parameters for historical data</param>
/// <returns>Enumerable of base data for this symbol</returns>
public IEnumerable<BaseData> Get(DataDownloaderGetParameters dataDownloaderGetParameters)
{
var symbol = dataDownloaderGetParameters.Symbol;
var resolution = dataDownloaderGetParameters.Resolution;
var startUtc = dataDownloaderGetParameters.StartUtc;
var endUtc = dataDownloaderGetParameters.EndUtc;
var tickType = dataDownloaderGetParameters.TickType;
if (tickType != TickType.Quote)
{
yield break;
}
if (!_symbolMapper.IsKnownLeanSymbol(symbol))
throw new ArgumentException("Invalid symbol requested: " + symbol.Value);
if (symbol.ID.SecurityType != SecurityType.Forex && symbol.ID.SecurityType != SecurityType.Cfd)
throw new NotSupportedException("SecurityType not available: " + symbol.ID.SecurityType);
if (endUtc < startUtc)
throw new ArgumentException("The end date must be greater or equal to the start date.");
// set the starting date
DateTime date = startUtc;
// loop until last date
while (date <= endUtc)
{
// request all ticks for a specific date
var ticks = DownloadTicks(symbol, date);
switch (resolution)
{
case Resolution.Tick:
foreach (var tick in ticks)
{
yield return new Tick(tick.Time, symbol, tick.BidPrice, tick.AskPrice);
}
break;
case Resolution.Second:
case Resolution.Minute:
case Resolution.Hour:
case Resolution.Daily:
foreach (var bar in LeanData.AggregateTicks(ticks, symbol, resolution.ToTimeSpan()))
{
yield return bar;
}
break;
}
date = date.AddDays(1);
}
}
/// <summary>
/// Downloads all ticks for the specified date
/// </summary>
/// <param name="symbol">The requested symbol</param>
/// <param name="date">The requested date</param>
/// <returns>An enumerable of ticks</returns>
private IEnumerable<Tick> DownloadTicks(Symbol symbol, DateTime date)
{
var dukascopySymbol = _symbolMapper.GetBrokerageSymbol(symbol);
var pointValue = _symbolMapper.GetPointValue(symbol);
for (var hour = 0; hour < 24; hour++)
{
var timeOffset = hour * 3600000;
var url = $"http://www.dukascopy.com/datafeed/{dukascopySymbol}/" +
$"{date.Year.ToStringInvariant("D4")}/{(date.Month - 1).ToStringInvariant("D2")}/" +
$"{date.Day.ToStringInvariant("D2")}/{hour.ToStringInvariant("D2")}h_ticks.bi5";
using (var client = new WebClient())
{
byte[] bytes;
try
{
bytes = client.DownloadData(url);
}
catch (Exception exception)
{
Log.Error(exception);
yield break;
}
if (bytes != null && bytes.Length > 0)
{
var ticks = AppendTicksToList(symbol, bytes, date, timeOffset, pointValue);
foreach (var tick in ticks)
{
yield return tick;
}
}
}
}
}
/// <summary>
/// Reads ticks from a Dukascopy binary buffer into a list
/// </summary>
/// <param name="symbol">The symbol</param>
/// <param name="bytesBi5">The buffer in binary format</param>
/// <param name="date">The date for the ticks</param>
/// <param name="timeOffset">The time offset in milliseconds</param>
/// <param name="pointValue">The price multiplier</param>
private static unsafe List<Tick> AppendTicksToList(Symbol symbol, byte[] bytesBi5, DateTime date, int timeOffset, double pointValue)
{
var ticks = new List<Tick>();
byte[] bytes;
var inputFile = $"{Guid.NewGuid()}.7z";
var outputDirectory = $"{Guid.NewGuid()}";
try
{
File.WriteAllBytes(inputFile, bytesBi5);
Compression.Extract7ZipArchive(inputFile, outputDirectory);
var outputFileInfo = Directory.CreateDirectory(outputDirectory).GetFiles("*").First();
bytes = File.ReadAllBytes(outputFileInfo.FullName);
}
catch (Exception err)
{
Log.Error(err, "Failed to read raw data into stream");
return new List<Tick>();
}
finally
{
if (File.Exists(inputFile))
{
File.Delete(inputFile);
}
if (Directory.Exists(outputDirectory))
{
Directory.Delete(outputDirectory, true);
}
}
int count = bytes.Length / DukascopyTickLength;
// Numbers are big-endian
// ii1 = milliseconds within the hour
// ii2 = AskPrice * point value
// ii3 = BidPrice * point value
// ff1 = AskVolume (not used)
// ff2 = BidVolume (not used)
fixed (byte* pBuffer = &bytes[0])
{
uint* p = (uint*)pBuffer;
for (int i = 0; i < count; i++)
{
ReverseBytes(p); uint time = *p++;
ReverseBytes(p); uint ask = *p++;
ReverseBytes(p); uint bid = *p++;
p++; p++;
if (bid > 0 && ask > 0)
{
ticks.Add(new Tick(
date.AddMilliseconds(timeOffset + time),
symbol,
Convert.ToDecimal(bid / pointValue),
Convert.ToDecimal(ask / pointValue)));
}
}
}
return ticks;
}
/// <summary>
/// Converts a 32-bit unsigned integer from big-endian to little-endian (and vice-versa)
/// </summary>
/// <param name="p">Pointer to the integer value</param>
private static unsafe void ReverseBytes(uint* p)
{
*p = (*p & 0x000000FF) << 24 | (*p & 0x0000FF00) << 8 | (*p & 0x00FF0000) >> 8 | (*p & 0xFF000000) >> 24;
}
}
}
| |
using System;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Banshee.Widgets;
using Banshee.Sources;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.Collection.Gui;
using Banshee.Gui;
using Banshee.Gui.Widgets;
using Banshee.Sources.Gui;
using Banshee.Web;
using Lastfm;
using Lastfm.Data;
namespace Banshee.Lastfm.Radio
{
public class LastfmSourceContents : Hyena.Widgets.ScrolledWindow, ISourceContents
{
private VBox main_box;
private LastfmSource lastfm;
private NumberedList recently_loved;
private NumberedList recently_played;
private NumberedList top_artists;
private Viewport viewport;
static LastfmSourceContents () {
DataCore.UserAgent = Banshee.Web.Browser.UserAgent;
DataCore.CachePath = System.IO.Path.Combine (Banshee.Base.Paths.ExtensionCacheRoot, "lastfm");
}
// "Coming Soon: Profile, Friends, Events etc")
public LastfmSourceContents () : base ()
{
HscrollbarPolicy = PolicyType.Never;
VscrollbarPolicy = PolicyType.Automatic;
viewport = new Viewport ();
viewport.ShadowType = ShadowType.None;
main_box = new VBox ();
main_box.Spacing = 6;
main_box.BorderWidth = 5;
main_box.ReallocateRedraws = true;
// Clamp the width, preventing horizontal scrolling
SizeAllocated += delegate (object o, SizeAllocatedArgs args) {
// TODO '- 10' worked for Nereid, but not for Cubano; properly calculate the right width we should request
main_box.WidthRequest = args.Allocation.Width - 30;
};
viewport.Add (main_box);
StyleSet += delegate {
viewport.ModifyBg (StateType.Normal, Style.Base (StateType.Normal));
viewport.ModifyFg (StateType.Normal, Style.Text (StateType.Normal));
};
AddWithFrame (viewport);
ShowAll ();
}
public bool SetSource (ISource src)
{
lastfm = src as LastfmSource;
if (lastfm == null) {
return false;
}
if (lastfm.Connection.Connected) {
UpdateForUser (lastfm.Account.UserName);
} else {
lastfm.Connection.StateChanged += HandleConnectionStateChanged;
}
return true;
}
public ISource Source {
get { return lastfm; }
}
public void ResetSource ()
{
lastfm = null;
}
public Widget Widget {
get { return this; }
}
public void Refresh ()
{
if (user != null) {
user.RecentLovedTracks.Refresh ();
user.RecentTracks.Refresh ();
user.GetTopArtists (TopType.Overall).Refresh ();
recently_loved.SetList (user.RecentLovedTracks);
recently_played.SetList (user.RecentTracks);
top_artists.SetList (user.GetTopArtists (TopType.Overall));
}
}
private string last_user;
private LastfmUserData user;
private void UpdateForUser (string username)
{
if (username == last_user) {
return;
}
last_user = username;
while (main_box.Children.Length != 0) {
main_box.Remove (main_box.Children[0]);
}
recently_loved = new NumberedList (lastfm, Catalog.GetString ("Recently Loved Tracks"));
recently_played = new NumberedList (lastfm, Catalog.GetString ("Recently Played Tracks"));
top_artists = new NumberedList (lastfm, Catalog.GetString ("My Top Artists"));
//recommended_artists = new NumberedList (Catalog.GetString ("Recommended Artists"));
main_box.PackStart (recently_loved, false, false, 0);
main_box.PackStart (new HSeparator (), false, false, 5);
main_box.PackStart (recently_played, false, false, 0);
main_box.PackStart (new HSeparator (), false, false, 5);
main_box.PackStart (top_artists, false, false, 0);
//PackStart (recommended_artists, true, true, 0);
user = new LastfmUserData (username);
recently_loved.SetList (user.RecentLovedTracks);
recently_played.SetList (user.RecentTracks);
top_artists.SetList (user.GetTopArtists (TopType.Overall));
ShowAll ();
}
private void HandleConnectionStateChanged (object sender, ConnectionStateChangedArgs args)
{
if (args.State == ConnectionState.Connected) {
Banshee.Base.ThreadAssist.ProxyToMain (delegate {
if (lastfm != null && lastfm.Account != null) {
UpdateForUser (lastfm.Account.UserName);
}
});
}
}
public class NumberedTileView : TileView
{
private int i = 1;
public NumberedTileView (int cols) : base (cols)
{
}
public new void ClearWidgets ()
{
i = 1;
base.ClearWidgets ();
}
public void AddNumberedWidget (Tile tile)
{
tile.PrimaryText = String.Format ("{0}. {1}", i++, tile.PrimaryText);
AddWidget (tile);
}
}
protected class NumberedList : TitledList
{
protected ArtworkManager artwork_manager = ServiceManager.Get<ArtworkManager> ();
protected LastfmSource lastfm;
protected NumberedTileView tile_view;
protected Dictionary<object, RecentTrack> widget_track_map = new Dictionary<object, RecentTrack> ();
public NumberedList (LastfmSource lastfm, string name) : base (name)
{
this.lastfm = lastfm;
tile_view = new NumberedTileView (1);
PackStart (tile_view, true, true, 0);
tile_view.Show ();
StyleSet += delegate {
tile_view.ModifyBg (StateType.Normal, Style.Base (StateType.Normal));
tile_view.ModifyFg (StateType.Normal, Style.Text (StateType.Normal));
};
}
// TODO generalize this
public void SetList (LastfmData<UserTopArtist> artists)
{
tile_view.ClearWidgets ();
foreach (UserTopArtist artist in artists) {
MenuTile tile = new MenuTile ();
tile.PrimaryText = artist.Name;
tile.SecondaryText = String.Format (Catalog.GetString ("{0} plays"), artist.PlayCount);
tile_view.AddNumberedWidget (tile);
}
tile_view.ShowAll ();
}
public void SetList (LastfmData<RecentTrack> tracks)
{
tile_view.ClearWidgets ();
foreach (RecentTrack track in tracks) {
MenuTile tile = new MenuTile ();
widget_track_map [tile] = track;
tile.PrimaryText = track.Name;
tile.SecondaryText = track.Artist;
tile.ButtonPressEvent += OnTileActivated;
// Unfortunately the recently loved list doesn't include what album the song is on
if (!String.IsNullOrEmpty (track.Album)) {
AlbumInfo album = new AlbumInfo (track.Album);
album.ArtistName = track.Artist;
Gdk.Pixbuf pb = artwork_manager == null ? null : artwork_manager.LookupScalePixbuf (album.ArtworkId, 40);
if (pb != null) {
tile.Pixbuf = pb;
}
}
tile_view.AddNumberedWidget (tile);
}
tile_view.ShowAll ();
}
private void OnTileActivated (object sender, EventArgs args)
{
(sender as Button).Relief = ReliefStyle.Normal;
RecentTrack track = widget_track_map [sender];
lastfm.Actions.CurrentArtist = track.Artist;
lastfm.Actions.CurrentAlbum = track.Album;
lastfm.Actions.CurrentTrack = track.Name;
Gtk.Menu menu = ServiceManager.Get<InterfaceActionService> ().UIManager.GetWidget ("/LastfmTrackPopup") as Menu;
// For an event
//menu.Append (new MenuItem ("Go to Last.fm Page"));
//menu.Append (new MenuItem ("Add to Google Calendar"));
// For a user
//menu.Append (new MenuItem ("Go to Last.fm Page"));
//menu.Append (new MenuItem ("Listen to Recommended Station"));
//menu.Append (new MenuItem ("Listen to Loved Station"));
//menu.Append (new MenuItem ("Listen to Neighbors Station"));
menu.ShowAll ();
menu.Popup (null, null, null, 0, Gtk.Global.CurrentEventTime);
menu.Deactivated += delegate {
(sender as Button).Relief = ReliefStyle.None;
};
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class FullNameTests : CSharpResultProviderTestBase
{
[Fact]
public void RootComment()
{
var source = @"
class C
{
public int F;
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(type.Instantiate());
var root = FormatResult("a // Comment", value);
Assert.Equal("a.F", GetChildren(root).Single().FullName);
root = FormatResult(" a // Comment", value);
Assert.Equal("a.F", GetChildren(root).Single().FullName);
root = FormatResult("a// Comment", value);
Assert.Equal("a.F", GetChildren(root).Single().FullName);
root = FormatResult("a /*b*/ +c /*d*/// Comment", value);
Assert.Equal("(a +c).F", GetChildren(root).Single().FullName);
root = FormatResult("a /*//*/+ c// Comment", value);
Assert.Equal("(a + c).F", GetChildren(root).Single().FullName);
root = FormatResult("a /*/**/+ c// Comment", value);
Assert.Equal("(a + c).F", GetChildren(root).Single().FullName);
root = FormatResult("/**/a// Comment", value);
Assert.Equal("a.F", GetChildren(root).Single().FullName);
}
[Fact]
public void RootFormatSpecifiers()
{
var source = @"
class C
{
public int F;
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(type.Instantiate());
var root = FormatResult("a, raw", value); // simple
Assert.Equal("a, raw", root.FullName);
Assert.Equal("a.F", GetChildren(root).Single().FullName);
root = FormatResult("a, raw, ac, h", value); // multiple specifiers
Assert.Equal("a, raw, ac, h", root.FullName);
Assert.Equal("a.F", GetChildren(root).Single().FullName);
root = FormatResult("M(a, b), raw", value); // non-specifier comma
Assert.Equal("M(a, b), raw", root.FullName);
Assert.Equal("(M(a, b)).F", GetChildren(root).Single().FullName); // parens not required
root = FormatResult("a, raw1", value); // alpha-numeric
Assert.Equal("a, raw1", root.FullName);
Assert.Equal("a.F", GetChildren(root).Single().FullName);
root = FormatResult("a, $raw", value); // other punctuation
Assert.Equal("a, $raw", root.FullName);
Assert.Equal("(a, $raw).F", GetChildren(root).Single().FullName); // not ideal
}
[Fact]
public void RootParentheses()
{
var source = @"
class C
{
public int F;
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(type.Instantiate());
var root = FormatResult("a + b", value);
Assert.Equal("(a + b).F", GetChildren(root).Single().FullName); // required
root = FormatResult("new C()", value);
Assert.Equal("(new C()).F", GetChildren(root).Single().FullName); // documentation
root = FormatResult("A.B", value);
Assert.Equal("A.B.F", GetChildren(root).Single().FullName); // desirable
root = FormatResult("A::B", value);
Assert.Equal("(A::B).F", GetChildren(root).Single().FullName); // documentation
}
[Fact]
public void RootTrailingSemicolons()
{
var source = @"
class C
{
public int F;
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(type.Instantiate());
var root = FormatResult("a;", value);
Assert.Equal("a.F", GetChildren(root).Single().FullName);
root = FormatResult("a + b;;", value);
Assert.Equal("(a + b).F", GetChildren(root).Single().FullName);
root = FormatResult(" M( ) ; ;", value);
Assert.Equal("(M( )).F", GetChildren(root).Single().FullName);
}
[Fact]
public void RootMixedExtras()
{
var source = @"
class C
{
public int F;
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(type.Instantiate());
// Semicolon, then comment.
var root = FormatResult("a; //", value);
Assert.Equal("a", root.FullName);
// Comment, then semicolon.
root = FormatResult("a // ;", value);
Assert.Equal("a", root.FullName);
// Semicolon, then format specifier.
root = FormatResult("a;, ac", value);
Assert.Equal("a, ac", root.FullName);
// Format specifier, then semicolon.
root = FormatResult("a, ac;", value);
Assert.Equal("a, ac", root.FullName);
// Comment, then format specifier.
root = FormatResult("a//, ac", value);
Assert.Equal("a", root.FullName);
// Format specifier, then comment.
root = FormatResult("a, ac //", value);
Assert.Equal("a, ac", root.FullName);
// Everything.
root = FormatResult("/*A*/ a /*B*/ + /*C*/ b /*D*/ ; ; , ac /*E*/, raw // ;, hidden", value);
Assert.Equal("a + b, ac, raw", root.FullName);
}
[Fact, WorkItem(1022165, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1022165")]
public void Keywords_Root()
{
var source = @"
class C
{
void M()
{
int @namespace = 3;
}
}
";
var assembly = GetAssembly(source);
var value = CreateDkmClrValue(3);
var root = FormatResult("@namespace", value);
Verify(root,
EvalResult("@namespace", "3", "int", "@namespace"));
value = CreateDkmClrValue(assembly.GetType("C").Instantiate());
root = FormatResult("this", value);
Verify(root,
EvalResult("this", "{C}", "C", "this"));
// Verify that keywords aren't escaped by the ResultProvider at the
// root level (we would never expect to see "namespace" passed as a
// resultName, but this check verifies that we leave them "as is").
root = FormatResult("namespace", CreateDkmClrValue(new object()));
Verify(root,
EvalResult("namespace", "{object}", "object", "namespace"));
}
[Fact]
public void Keywords_RuntimeType()
{
var source = @"
public class @struct
{
}
public class @namespace : @struct
{
@struct m = new @if();
}
public class @if : @struct
{
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("namespace");
var declaredType = assembly.GetType("struct");
var value = CreateDkmClrValue(type.Instantiate(), type);
var root = FormatResult("o", value, new DkmClrType((TypeImpl)declaredType));
Verify(GetChildren(root),
EvalResult("m", "{if}", "struct {if}", "((@namespace)o).m", DkmEvaluationResultFlags.None));
}
[Fact]
public void Keywords_ProxyType()
{
var source = @"
using System.Diagnostics;
[DebuggerTypeProxy(typeof(@class))]
public class @struct
{
public bool @true = false;
}
public class @class
{
public bool @false = true;
public @class(@struct s) { }
}
";
var assembly = GetAssembly(source);
var value = CreateDkmClrValue(assembly.GetType("struct").Instantiate());
var root = FormatResult("o", value);
var children = GetChildren(root);
Verify(children,
EvalResult("@false", "true", "bool", "new @class(o).@false", DkmEvaluationResultFlags.Boolean | DkmEvaluationResultFlags.BooleanTrue),
EvalResult("Raw View", null, "", "o, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
var grandChildren = GetChildren(children.Last());
Verify(grandChildren,
EvalResult("@true", "false", "bool", "o.@true", DkmEvaluationResultFlags.Boolean));
}
[Fact]
public void Keywords_MemberAccess()
{
var source = @"
public class @struct
{
public int @true;
}
";
var assembly = GetAssembly(source);
var value = CreateDkmClrValue(assembly.GetType("struct").Instantiate());
var root = FormatResult("o", value);
Verify(GetChildren(root),
EvalResult("@true", "0", "int", "o.@true"));
}
[Fact]
public void Keywords_StaticMembers()
{
var source = @"
public class @struct
{
public static int @true;
}
";
var assembly = GetAssembly(source);
var value = CreateDkmClrValue(assembly.GetType("struct").Instantiate());
var root = FormatResult("o", value);
var children = GetChildren(root);
Verify(children,
EvalResult("Static members", null, "", "@struct", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
Verify(GetChildren(children.Single()),
EvalResult("@true", "0", "int", "@struct.@true", DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Public));
}
[Fact]
public void Keywords_ExplicitInterfaceImplementation()
{
var source = @"
namespace @namespace
{
public interface @interface<T>
{
int @return { get; set; }
}
public class @class : @interface<@class>
{
int @interface<@class>.@return { get; set; }
}
}
";
var assembly = GetAssembly(source);
var value = CreateDkmClrValue(assembly.GetType("namespace.class").Instantiate());
var root = FormatResult("instance", value);
Verify(GetChildren(root),
EvalResult("@namespace.@interface<@namespace.@class>.@return", "0", "int", "((@namespace.@interface<@namespace.@class>)instance).@return"));
}
[Fact]
public void MangledNames_CastRequired()
{
var il = @"
.class public auto ansi beforefieldinit '<>Mangled' extends [mscorlib]System.Object
{
.field public int32 x
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
.class public auto ansi beforefieldinit 'NotMangled' extends '<>Mangled'
{
.field public int32 x
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0
call instance void '<>Mangled'::.ctor()
ret
}
}
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var value = CreateDkmClrValue(assembly.GetType("NotMangled").Instantiate());
var root = FormatResult("o", value);
Verify(GetChildren(root),
EvalResult("x (<>Mangled)", "0", "int", null),
EvalResult("x", "0", "int", "o.x"));
}
[Fact]
public void MangledNames_StaticMembers()
{
var il = @"
.class public auto ansi beforefieldinit '<>Mangled' extends [mscorlib]System.Object
{
.field public static int32 x
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
.class public auto ansi beforefieldinit 'NotMangled' extends '<>Mangled'
{
.field public static int32 y
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0
call instance void '<>Mangled'::.ctor()
ret
}
}
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var baseValue = CreateDkmClrValue(assembly.GetType("<>Mangled").Instantiate());
var root = FormatResult("o", baseValue);
var children = GetChildren(root);
Verify(children,
EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
Verify(GetChildren(children.Single()),
EvalResult("x", "0", "int", null));
var derivedValue = CreateDkmClrValue(assembly.GetType("NotMangled").Instantiate());
root = FormatResult("o", derivedValue);
children = GetChildren(root);
Verify(children,
EvalResult("Static members", null, "", "NotMangled", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
Verify(GetChildren(children.Single()),
EvalResult("x", "0", "int", null, DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Public),
EvalResult("y", "0", "int", "NotMangled.y", DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Public));
}
[Fact]
public void MangledNames_ExplicitInterfaceImplementation()
{
var il = @"
.class interface public abstract auto ansi 'I<>Mangled'
{
.method public hidebysig newslot specialname abstract virtual
instance int32 get_P() cil managed
{
}
.property instance int32 P()
{
.get instance int32 'I<>Mangled'::get_P()
}
} // end of class 'I<>Mangled'
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
implements 'I<>Mangled'
{
.method private hidebysig newslot specialname virtual final
instance int32 'I<>Mangled.get_P'() cil managed
{
.override 'I<>Mangled'::get_P
ldc.i4.1
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 'I<>Mangled.P'()
{
.get instance int32 C::'I<>Mangled.get_P'()
}
.property instance int32 P()
{
.get instance int32 C::'I<>Mangled.get_P'()
}
} // end of class C
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var value = CreateDkmClrValue(assembly.GetType("C").Instantiate());
var root = FormatResult("instance", value);
Verify(GetChildren(root),
EvalResult("I<>Mangled.P", "1", "int", null, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Private),
EvalResult("P", "1", "int", "instance.P", DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Private));
}
[Fact]
public void MangledNames_ArrayElement()
{
var il = @"
.class public auto ansi beforefieldinit '<>Mangled'
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
.class public auto ansi beforefieldinit NotMangled
extends [mscorlib]System.Object
{
.field public class [mscorlib]System.Collections.Generic.IEnumerable`1<class '<>Mangled'> 'array'
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
ldc.i4.1
newarr '<>Mangled'
stfld class [mscorlib]System.Collections.Generic.IEnumerable`1<class '<>Mangled'> NotMangled::'array'
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var value = CreateDkmClrValue(assembly.GetType("NotMangled").Instantiate());
var root = FormatResult("o", value);
var children = GetChildren(root);
Verify(children,
EvalResult("array", "{<>Mangled[1]}", "System.Collections.Generic.IEnumerable<<>Mangled> {<>Mangled[]}", "o.array", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(children.Single()),
EvalResult("[0]", "null", "<>Mangled", null));
}
[Fact]
public void MangledNames_Namespace()
{
var il = @"
.class public auto ansi beforefieldinit '<>Mangled.C' extends [mscorlib]System.Object
{
.field public static int32 x
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var baseValue = CreateDkmClrValue(assembly.GetType("<>Mangled.C").Instantiate());
var root = FormatResult("o", baseValue);
var children = GetChildren(root);
Verify(children,
EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
Verify(GetChildren(children.Single()),
EvalResult("x", "0", "int", null));
}
[Fact]
public void MangledNames_PointerDereference()
{
var il = @"
.class public auto ansi beforefieldinit '<>Mangled'
extends [mscorlib]System.Object
{
.field private static int32* p
.method assembly hidebysig specialname rtspecialname
instance void .ctor(int64 arg) cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0008: ldarg.1
IL_0009: conv.u
IL_000a: stsfld int32* '<>Mangled'::p
IL_0010: ret
}
} // end of class '<>Mangled'
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
unsafe
{
int i = 4;
long p = (long)&i;
var type = assembly.GetType("<>Mangled");
var rootExpr = "m";
var value = CreateDkmClrValue(type.Instantiate(p));
var evalResult = FormatResult(rootExpr, value);
Verify(evalResult,
EvalResult(rootExpr, "{<>Mangled}", "<>Mangled", rootExpr, DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
children = GetChildren(children.Single());
Verify(children,
EvalResult("p", PointerToString(new IntPtr(p)), "int*", null, DkmEvaluationResultFlags.Expandable));
children = GetChildren(children.Single());
Verify(children,
EvalResult("*p", "4", "int", null));
}
}
[Fact]
public void MangledNames_DebuggerTypeProxy()
{
var il = @"
.class public auto ansi beforefieldinit Type
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Diagnostics.DebuggerTypeProxyAttribute::.ctor(class [mscorlib]System.Type)
= {type('<>Mangled')}
.field public bool x
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
ldc.i4.0
stfld bool Type::x
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
} // end of method Type::.ctor
} // end of class Type
.class public auto ansi beforefieldinit '<>Mangled'
extends [mscorlib]System.Object
{
.field public bool y
.method public hidebysig specialname rtspecialname
instance void .ctor(class Type s) cil managed
{
ldarg.0
ldc.i4.1
stfld bool '<>Mangled'::y
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
} // end of method '<>Mangled'::.ctor
} // end of class '<>Mangled'
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var value = CreateDkmClrValue(assembly.GetType("Type").Instantiate());
var root = FormatResult("o", value);
var children = GetChildren(root);
Verify(children,
EvalResult("y", "true", "bool", null, DkmEvaluationResultFlags.Boolean | DkmEvaluationResultFlags.BooleanTrue),
EvalResult("Raw View", null, "", "o, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
var grandChildren = GetChildren(children.Last());
Verify(grandChildren,
EvalResult("x", "false", "bool", "o.x", DkmEvaluationResultFlags.Boolean));
}
[Fact]
public void GenericTypeWithoutBacktick()
{
var il = @"
.class public auto ansi beforefieldinit C<T> extends [mscorlib]System.Object
{
.field public static int32 'x'
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var value = CreateDkmClrValue(assembly.GetType("C").MakeGenericType(typeof(int)).Instantiate());
var root = FormatResult("o", value);
var children = GetChildren(root);
Verify(children,
EvalResult("Static members", null, "", "C<int>", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
Verify(GetChildren(children.Single()),
EvalResult("x", "0", "int", "C<int>.x"));
}
[Fact]
public void BackTick_NonGenericType()
{
var il = @"
.class public auto ansi beforefieldinit 'C`1' extends [mscorlib]System.Object
{
.field public static int32 'x'
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var value = CreateDkmClrValue(assembly.GetType("C`1").Instantiate());
var root = FormatResult("o", value);
var children = GetChildren(root);
Verify(children,
EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
Verify(GetChildren(children.Single()),
EvalResult("x", "0", "int", null));
}
[Fact]
public void BackTick_GenericType()
{
var il = @"
.class public auto ansi beforefieldinit 'C`1'<T> extends [mscorlib]System.Object
{
.field public static int32 'x'
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var value = CreateDkmClrValue(assembly.GetType("C`1").MakeGenericType(typeof(int)).Instantiate());
var root = FormatResult("o", value);
var children = GetChildren(root);
Verify(children,
EvalResult("Static members", null, "", "C<int>", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
Verify(GetChildren(children.Single()),
EvalResult("x", "0", "int", "C<int>.x"));
}
[Fact]
public void BackTick_Member()
{
// IL doesn't support using generic methods as property accessors so
// there's no way to test a "legitimate" backtick in a member name.
var il = @"
.class public auto ansi beforefieldinit C extends [mscorlib]System.Object
{
.field public static int32 'x`1'
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var value = CreateDkmClrValue(assembly.GetType("C").Instantiate());
var root = FormatResult("o", value);
var children = GetChildren(root);
Verify(children,
EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
Verify(GetChildren(children.Single()),
EvalResult("x`1", "0", "int", fullName: null));
}
[Fact]
public void BackTick_FirstCharacter()
{
var il = @"
.class public auto ansi beforefieldinit '`1'<T> extends [mscorlib]System.Object
{
.field public static int32 'x'
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var assembly = ReflectionUtilities.Load(assemblyBytes);
var value = CreateDkmClrValue(assembly.GetType("`1").MakeGenericType(typeof(int)).Instantiate());
var root = FormatResult("o", value);
var children = GetChildren(root);
Verify(children,
EvalResult("Static members", null, "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
Verify(GetChildren(children.Single()),
EvalResult("x", "0", "int", fullName: null));
}
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.Util;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Responses;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace Google.Ads.GoogleAds.Config
{
/// <summary>
/// This class reads the configuration keys from App.config.
/// </summary>
public class GoogleAdsConfig : ConfigBase
{
/// <summary>
/// The default timeout for API calls in milliseconds.
/// </summary>
private static readonly int DEFAULT_TIMEOUT = (int) new TimeSpan(1, 0, 0).TotalMilliseconds;
/// <summary>
/// Default value of the maximum size in bytes of the message that can be received by the
/// service client (64 MB).
/// </summary>
private const int DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH_IN_BYTES = 64 * 1024 * 1024;
/// <summary>
/// Default value for the maximum size in bytes of the metadata that can be received by the
/// service client (16 MB).
/// </summary>
private const int DEFAULT_MAX_METADATA_SIZE_IN_BYTES = 16 * 1024 * 1024;
/// <summary>
/// The default value of OAuth2 server URL.
/// </summary>
private const string DEFAULT_OAUTH2_SERVER = "https://accounts.google.com";
/// <summary>
/// The default user ID when creating a <see cref="GoogleAuthorizationCodeFlow"/> instance.
/// </summary>
private const string DEFAULT_USER_ID = "user";
/// <summary>
/// The Google Ads API server URL.
/// </summary>
private const string GOOGLE_ADS_API_SERVER_URL = "https://googleads.googleapis.com";
/// <summary>
/// OAuth scope for Google Ads API.
/// </summary>
private const string DEFAULT_OAUTH_SCOPE = "https://www.googleapis.com/auth/adwords";
/// <summary>
/// The configuration section name in App.config file.
/// </summary>
/// <remarks>This is kept as such to provide backwards compatibility with the SOAP client
/// libraries.</remarks>
protected const string CONFIG_SECTION_NAME = "GoogleAdsApi";
/// <summary>
/// OAuth2 client ID.
/// </summary>
private StringConfigSetting oAuth2ClientId =
new StringConfigSetting("OAuth2ClientId", "");
/// <summary>
/// OAuth2 client secret.
/// </summary>
private StringConfigSetting oAuth2ClientSecret = new StringConfigSetting(
"OAuth2ClientSecret", "");
/// <summary>
/// OAuth2 refresh token.
/// </summary>
private StringConfigSetting oAuth2RefreshToken = new StringConfigSetting(
"OAuth2RefreshToken", "");
/// <summary>
/// OAuth2 prn email.
/// </summary>
private StringConfigSetting oAuth2PrnEmail = new StringConfigSetting(
"OAuth2PrnEmail", "");
/// <summary>
/// OAuth2 service account email loaded from secrets JSON file.
/// </summary>
private StringConfigSetting oAuth2ServiceAccountEmail = new StringConfigSetting(
"client_email", null);
/// <summary>
/// OAuth2 private key loaded from secrets JSON file.
/// </summary>
private StringConfigSetting oAuth2PrivateKey = new StringConfigSetting(
"private_key", "");
/// <summary>
/// OAuth2 secrets JSON file path.
/// </summary>
private StringConfigSetting oAuth2SecretsJsonPath = new StringConfigSetting(
"OAuth2SecretsJsonPath", "");
/// <summary>
/// OAuth2 scope.
/// </summary>
private StringConfigSetting oAuth2Scope = new StringConfigSetting("OAuth2Scope",
DEFAULT_OAUTH_SCOPE);
/// <summary>
/// OAuth2 mode.
/// </summary>
private ConfigSetting<OAuth2Flow> oAuth2Mode = new ConfigSetting<OAuth2Flow>("OAuth2Mode",
OAuth2Flow.APPLICATION);
/// <summary>
/// Authorization method.
/// </summary>
/// <remarks>
/// This setting is only for testing purposes.
/// </remarks>
private ConfigSetting<AuthorizationMethod> authorizationMethod =
new ConfigSetting<AuthorizationMethod>("AuthorizationMethod",
AuthorizationMethod.OAuth);
/// <summary>
/// The client customer ID.
/// </summary>
/// <remarks>
/// This setting is only for testing purposes.
/// </remarks>
private ConfigSetting<long> clientCustomerId =
new ConfigSetting<long>("ClientCustomerId", 0);
/// <summary>
/// A flag to determine whether or not to enable profiling.
/// </summary>
/// <remarks>
/// This setting is only for testing purposes.
/// </remarks>
private ConfigSetting<bool> enableProfiling =
new ConfigSetting<bool>("EnableProfiling", false);
/// <summary>
/// A flag to determine whether or not to use channel caching.
/// </summary>
/// <remarks>
/// This setting may be used to disable channel caching in advanced use cases
/// where the library's default credential management is manually overridden.
/// </remarks>
private ConfigSetting<bool> useChannelCache =
new ConfigSetting<bool>("UseChannelCache", true);
/// <summary>
/// The maximum message length in bytes that the client library can receive (64 MB).
/// </summary>
private ConfigSetting<int> maxReceiveMessageLengthInBytes =
new ConfigSetting<int>("MaxReceiveMessageLengthInBytes",
DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH_IN_BYTES);
/// <summary>
/// The maximum size in bytes of the metadata that can be received by the
/// service client.
/// </summary>
private ConfigSetting<int> maxMetadataSizeInBytes =
new ConfigSetting<int>("MaxMetadataSizeInBytes",
DEFAULT_MAX_METADATA_SIZE_IN_BYTES);
/// <summary>
/// Web proxy to be used with the services.
/// </summary>
private ConfigSetting<WebProxy> proxy = new ConfigSetting<WebProxy>("Proxy", null);
/// <summary>
/// The timeout for individual API calls.
/// </summary>
private readonly ConfigSetting<int> timeout = new ConfigSetting<int>(
"Timeout", DEFAULT_TIMEOUT);
/// <summary>
/// The Google Ads API server URL.
/// </summary>
/// <remarks>This setting is used only for testing purposes.</remarks>
private readonly StringConfigSetting serverUrl = new StringConfigSetting(
"GoogleAds.Server", GOOGLE_ADS_API_SERVER_URL);
/// <summary>
/// The developer token.
/// </summary>
private readonly StringConfigSetting developerToken = new StringConfigSetting(
"DeveloperToken", "");
/// <summary>
/// The Login Customer ID.
/// </summary>
private readonly StringConfigSetting loginCustomerId = new StringConfigSetting(
"LoginCustomerId", "");
/// <summary>
/// The linked Customer ID.
/// </summary>
private readonly StringConfigSetting linkedCustomerId = new StringConfigSetting(
"LinkedCustomerId", "");
/// <summary>
/// The library identifier override.
/// </summary>
private readonly StringConfigSetting libraryIdentifierOverride =
new StringConfigSetting("LibraryIdentifierOverride", "");
/// <summary>
/// A map between the environment variable key names and configuration key names.
/// </summary>
protected readonly Dictionary<string, string> ENV_VAR_TO_CONFIG_KEY_MAP;
/// <summary>
/// Gets or sets the timeout for individual API calls.
/// </summary>
public int Timeout
{
get => timeout.Value;
set => SetPropertyAndNotify(timeout, value);
}
/// <summary>
/// Gets or sets the maximum size in bytes of the message that can be received by the
/// service client.
/// </summary>
public int MaxReceiveMessageSizeInBytes
{
get => maxReceiveMessageLengthInBytes.Value;
set => SetPropertyAndNotify(maxReceiveMessageLengthInBytes, value);
}
/// <summary>
/// Gets or sets the maximum size in bytes of the metadata that can be received by the
/// service client.
/// </summary>
public int MaxMetadataSizeInBytes
{
get => maxMetadataSizeInBytes.Value;
set => SetPropertyAndNotify(maxMetadataSizeInBytes, value);
}
/// <summary>
/// Gets or sets the library identifier override.
/// </summary>
/// <value>
/// The library identifier override.
/// </value>
/// <remarks>This setting is only for testing purposes.</remarks>
internal string LibraryIdentifierOverride
{
get => libraryIdentifierOverride.Value;
set => SetPropertyAndNotify(libraryIdentifierOverride, value);
}
/// <summary>
/// Gets or sets the web proxy to be used with the services.
/// </summary>
public WebProxy Proxy
{
get => proxy.Value;
set => SetPropertyAndNotify(proxy, value);
}
/// <summary>
/// Gets or sets the Google Ads API server URL.
/// </summary>
/// <remarks>This setting is used only for testing purposes.</remarks>
public string ServerUrl
{
get => serverUrl.Value;
set => SetPropertyAndNotify(serverUrl, value);
}
/// <summary>
/// Gets or sets the developer token.
/// </summary>
public string DeveloperToken
{
get => developerToken.Value;
set => SetPropertyAndNotify(developerToken, value);
}
/// <summary>
/// Gets or sets the login customer id.
/// </summary>
/// <remarks>
/// Required for manager accounts only. When authenticating as a Google Ads
/// manager account, specifies the customer ID of the authenticating manager account.
/// If your OAuth credentials are for a user with access to multiple manager accounts you
/// must create a separate GoogleAdsClient instance for each manager account.
/// </remarks>
public string LoginCustomerId
{
get => loginCustomerId.Value;
set => SetPropertyAndNotify(loginCustomerId, value);
}
/// <summary>
/// Gets or sets the linked customer ID.
/// </summary>
/// <remarks>
/// This header is only required for methods that update the resources of an entity when
/// permissioned via Linked Accounts in the Google Ads UI(AccountLink resource in the
/// Google Ads API). Set this value to the customer ID of the data provider that updates the
/// resources of the specified customer ID. It should be set without dashes, for example:
/// 1234567890 instead of 123-456-7890. Read https://support.google.com/google-ads/answer/7365001
/// to learn more about Linked Accounts.
/// </remarks>
public string LinkedCustomerId
{
get => linkedCustomerId.Value;
set => SetPropertyAndNotify(linkedCustomerId, value);
}
/// <summary>
/// Gets or sets the OAuth2 client ID.
/// </summary>
public string OAuth2ClientId
{
get => oAuth2ClientId.Value;
set
{
SetPropertyAndNotify(oAuth2ClientId, value);
credential = null;
}
}
/// <summary>
/// Gets or sets the OAuth2 client secret.
/// </summary>
public string OAuth2ClientSecret
{
get => oAuth2ClientSecret.Value;
set
{
SetPropertyAndNotify(oAuth2ClientSecret, value);
credential = null;
}
}
/// <summary>
/// Gets or sets the OAuth2 access token.
/// </summary>
public string OAuth2AccessToken
{
get
{
Task<string> task = this.Credentials.GetAccessTokenForRequestAsync();
task.Wait();
return task.Result;
}
}
/// <summary>
/// Gets or sets the OAuth2 refresh token.
/// </summary>
/// <remarks>This setting is applicable only when using OAuth2 web / application
/// flow in offline mode.</remarks>
public string OAuth2RefreshToken
{
get => oAuth2RefreshToken.Value;
set
{
SetPropertyAndNotify(oAuth2RefreshToken, value);
credential = null;
}
}
/// <summary>
/// Gets or sets the OAuth2 scope. This is a comma separated string of
/// all the scopes you want to use. This property has the default value
/// <code>https://www.googleapis.com/auth/adwords</code>
/// </summary>
public string OAuth2Scope
{
get => oAuth2Scope.Value;
set
{
SetPropertyAndNotify(oAuth2Scope, value);
credential = null;
}
}
/// <summary>
/// Gets or sets the OAuth2 mode.
/// </summary>
public OAuth2Flow OAuth2Mode
{
get => oAuth2Mode.Value;
set
{
SetPropertyAndNotify(oAuth2Mode, value);
credential = null;
}
}
/// <summary>
/// Gets or sets the authorization method.
/// </summary>
/// <remarks>This setting is only for testing purposes.</remarks>
internal AuthorizationMethod AuthorizationMethod
{
get => authorizationMethod.Value;
set => SetPropertyAndNotify(authorizationMethod, value);
}
/// <summary>
/// Gets or sets the client customerId.
/// </summary>
/// <remarks>This setting is only for testing purposes.</remarks>
internal long ClientCustomerId
{
get => clientCustomerId.Value;
set => SetPropertyAndNotify(clientCustomerId, value);
}
/// <summary>
/// A flag to determine whether or not to turn on profiling in the client library.
/// </summary>
/// <remarks>This setting is only for testing purposes.</remarks>
public bool EnableProfiling
{
get => enableProfiling.Value;
set => SetPropertyAndNotify(enableProfiling, value);
}
/// <summary>
/// A flag to determine whether or not to enable channel cache in the client library.
/// </summary>
/// <remarks>
/// This setting may be used to disable channel caching in advanced use cases
/// where the library's default credential management is manually overridden.
/// </remarks>
public bool UseChannelCache
{
get => useChannelCache.Value;
set => SetPropertyAndNotify(useChannelCache, value);
}
/// <summary>
/// Gets or sets the OAuth2 prn email.
/// </summary>
/// <remarks>This setting is applicable only when using OAuth2 service accounts.
/// </remarks>
public string OAuth2PrnEmail
{
get => oAuth2PrnEmail.Value;
set
{
SetPropertyAndNotify(oAuth2PrnEmail, value);
credential = null;
}
}
/// <summary>
/// Gets the OAuth2 service account email.
/// </summary>
/// <remarks>
/// This setting is applicable only when using OAuth2 service accounts.
/// This setting is read directly from the file referred to in
/// <see cref="OAuth2SecretsJsonPath"/> setting.
/// </remarks>
public string OAuth2ServiceAccountEmail
{
get => oAuth2ServiceAccountEmail.Value;
private set
{
SetPropertyAndNotify(oAuth2ServiceAccountEmail, value);
credential = null;
}
}
/// <summary>
/// Gets the OAuth2 private key for service account flow.
/// </summary>
/// <remarks>
/// This setting is applicable only when using OAuth2 service accounts.
/// This setting is read directly from the file referred to in
/// <see cref="OAuth2SecretsJsonPath"/> setting.
/// </remarks>
public string OAuth2PrivateKey
{
get => oAuth2PrivateKey.Value;
private set
{
SetPropertyAndNotify(oAuth2PrivateKey, value);
credential = null;
}
}
/// <summary>
/// Gets or sets the OAuth2 secrets JSON file path.
/// </summary>
/// <remarks>
/// This setting is applicable only when using OAuth2 service accounts.
/// </remarks>
public string OAuth2SecretsJsonPath
{
get => oAuth2SecretsJsonPath.Value;
set
{
SetPropertyAndNotify(oAuth2SecretsJsonPath, value);
LoadOAuth2SecretsFromFile();
}
}
/// <summary>
/// Public constructor. Loads the configuration from the <code>GoogleAdsApi</code> section
/// of the App.config / Web.config.
/// </summary>
public GoogleAdsConfig() : base()
{
ENV_VAR_TO_CONFIG_KEY_MAP = new Dictionary<string, string>() {
{ EnvironmentVariableNames.OAUTH2_MODE, oAuth2Mode.Name},
{ EnvironmentVariableNames.OAUTH2_CLIENT_ID, oAuth2ClientId.Name},
{ EnvironmentVariableNames.OAUTH2_CLIENT_SECRET, oAuth2ClientSecret.Name},
{ EnvironmentVariableNames.OAUTH2_REFRESH_TOKEN, oAuth2RefreshToken.Name},
{ EnvironmentVariableNames.OAUTH2_JSON_KEY_FILE_PATH, oAuth2SecretsJsonPath.Name},
{ EnvironmentVariableNames.OAUTH2_IMPERSONATED_EMAIL, oAuth2PrnEmail.Name},
{ EnvironmentVariableNames.DEVELOPER_TOKEN, developerToken.Name},
{ EnvironmentVariableNames.LOGIN_CUSTOMER_ID, loginCustomerId.Name},
{ EnvironmentVariableNames.LINKED_CUSTOMER_ID, linkedCustomerId.Name},
{ EnvironmentVariableNames.ENDPOINT, serverUrl.Name},
};
if (!LoadFromAppConfigSection(CONFIG_SECTION_NAME))
{
TryLoadFromEnvironmentFilePath(EnvironmentVariableNames.CONFIG_FILE_PATH,
CONFIG_SECTION_NAME);
}
}
/// <summary>
/// Public constructor. Loads the configuration from an <see cref="IConfigurationRoot"/>.
/// </summary>
/// <param name="configurationRoot">The configuration root.</param>
public GoogleAdsConfig(IConfigurationRoot configurationRoot) : base(configurationRoot)
{
}
/// <summary>
/// Public constructor. Loads the configuration from a <see cref="IConfigurationSection"/>.
/// </summary>
/// <param name="configurationSection">The configuration section.</param>
public GoogleAdsConfig(IConfigurationSection configurationSection)
: base(configurationSection)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="GoogleAdsConfig"/> class.
/// </summary>
/// <param name="settings">The settings.</param>
public GoogleAdsConfig(Dictionary<string, string> settings) : base(settings) { }
/// <summary>
/// Loads the configuration from environment variables.
/// </summary>
public void LoadFromEnvironmentVariables()
{
Dictionary<string, string> settings = new Dictionary<string, string>();
foreach (string key in ENV_VAR_TO_CONFIG_KEY_MAP.Keys)
{
string value = Environment.GetEnvironmentVariable(key);
if (!string.IsNullOrEmpty(value))
{
settings[ENV_VAR_TO_CONFIG_KEY_MAP[key]] = value;
}
}
ReadSettings(settings);
}
/// <summary>
/// Read all settings from App.config.
/// </summary>
/// <param name="settings">The parsed App.config settings.</param>
protected override void ReadSettings(Dictionary<string, string> settings)
{
ReadSetting(settings, timeout);
ReadSetting(settings, maxReceiveMessageLengthInBytes);
ReadSetting(settings, maxMetadataSizeInBytes);
ReadSetting(settings, serverUrl);
ReadSetting(settings, developerToken);
ReadSetting(settings, loginCustomerId);
ReadSetting(settings, linkedCustomerId);
ReadSetting(settings, clientCustomerId);
ReadSetting(settings, oAuth2Mode);
ReadSetting(settings, oAuth2ClientId);
ReadSetting(settings, oAuth2ClientSecret);
ReadSetting(settings, oAuth2RefreshToken);
ReadSetting(settings, oAuth2Scope);
// Read and parse the OAuth2 JSON secrets file if applicable.
ReadSetting(settings, oAuth2SecretsJsonPath);
if (!string.IsNullOrEmpty(oAuth2SecretsJsonPath.Value))
{
LoadOAuth2SecretsFromFile();
}
ReadSetting(settings, oAuth2PrnEmail);
ReadProxySettings(settings);
}
/// <summary>
/// Reads the proxy settings.
/// </summary>
/// <param name="settings">The parsed app.config settings.</param>
private void ReadProxySettings(Dictionary<string, string> settings)
{
StringConfigSetting proxyServer = new StringConfigSetting("ProxyServer", null);
StringConfigSetting proxyUser = new StringConfigSetting("ProxyUser", null);
StringConfigSetting proxyPassword = new StringConfigSetting("ProxyPassword", null);
StringConfigSetting proxyDomain = new StringConfigSetting("ProxyDomain", null);
ReadSetting(settings, proxyServer);
if (!string.IsNullOrEmpty(proxyServer.Value))
{
WebProxy proxy = new WebProxy()
{
Address = new Uri(proxyServer.Value)
};
ReadSetting(settings, proxyUser);
ReadSetting(settings, proxyPassword);
ReadSetting(settings, proxyDomain);
if (!string.IsNullOrEmpty(proxyUser.Value))
{
proxy.Credentials = new NetworkCredential(proxyUser.Value,
proxyPassword.Value, proxyDomain.Value);
}
this.proxy.Value = proxy;
}
else
{
// System.Net.WebRequest will find a proxy if needed.
this.proxy.Value = null;
}
}
/// <summary>
/// The credential object that was created from settings.
/// </summary>
private ICredential credential = null;
/// <summary>
/// Gets the credentials.
/// </summary>
public ICredential Credentials
{
get
{
if (credential == null)
{
credential = CreateCredentials();
}
return credential;
}
}
/// <summary>
/// Creates a credentials object from settings.
/// </summary>
/// <returns>The configuration settings.</returns>
protected virtual ICredential CreateCredentials()
{
ICredential retval = null;
string[] scopes = OAuth2Scope.Split(new char[] { ',' },
StringSplitOptions.RemoveEmptyEntries)
.Select(t => t.Trim())
.ToArray();
switch (OAuth2Mode)
{
case OAuth2Flow.APPLICATION:
retval = new UserCredential(
new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets()
{
ClientId = OAuth2ClientId,
ClientSecret = OAuth2ClientSecret,
},
Scopes = scopes,
HttpClientFactory = new AdsHttpClientFactory(this)
}),
DEFAULT_USER_ID,
new TokenResponse()
{
RefreshToken = OAuth2RefreshToken,
});
break;
case OAuth2Flow.SERVICE_ACCOUNT:
retval = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(OAuth2ServiceAccountEmail)
{
User = OAuth2PrnEmail,
Scopes = new string[] { OAuth2Scope },
HttpClientFactory = new AdsHttpClientFactory(this)
}.FromPrivateKey(OAuth2PrivateKey));
break;
default:
throw new ApplicationException("Unrecognized json file format.");
}
return retval;
}
/// <summary>
/// Loads the OAuth2 private key and service account email settings from the
/// secrets JSON file.
/// </summary>
private void LoadOAuth2SecretsFromFile()
{
try
{
using (StreamReader reader = new StreamReader(OAuth2SecretsJsonPath))
{
string contents = reader.ReadToEnd();
Dictionary<string, string> config =
JsonConvert.DeserializeObject<Dictionary<string, string>>(contents);
ReadSetting(config, oAuth2ServiceAccountEmail);
if (string.IsNullOrEmpty(this.OAuth2ServiceAccountEmail))
{
throw new ApplicationException(ErrorMessages.ClientEmailIsMissingInJsonFile);
}
ReadSetting(config, oAuth2PrivateKey);
if (string.IsNullOrEmpty(this.OAuth2PrivateKey))
{
throw new ApplicationException(ErrorMessages.PrivateKeyIsMissingInJsonFile);
}
}
}
catch (Exception e)
{
throw new ArgumentException(ErrorMessages.FailedToLoadJsonSecretsFile, e);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.CommandLine;
using System.Runtime.InteropServices;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using Internal.CommandLine;
namespace ILCompiler
{
internal class Program
{
private Dictionary<string, string> _inputFilePaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private Dictionary<string, string> _referenceFilePaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private string _outputFilePath;
private bool _isCppCodegen;
private bool _isVerbose;
private string _dgmlLogFileName;
private bool _generateFullDgmlLog;
private TargetArchitecture _targetArchitecture;
private string _targetArchitectureStr;
private TargetOS _targetOS;
private string _targetOSStr;
private OptimizationMode _optimizationMode;
private bool _enableDebugInfo;
private string _systemModuleName = "System.Private.CoreLib";
private bool _multiFile;
private bool _useSharedGenerics;
private string _mapFileName;
private string _metadataLogFileName;
private string _singleMethodTypeName;
private string _singleMethodName;
private IReadOnlyList<string> _singleMethodGenericArgs;
private IReadOnlyList<string> _codegenOptions = Array.Empty<string>();
private IReadOnlyList<string> _rdXmlFilePaths = Array.Empty<string>();
private bool _help;
private Program()
{
}
private void Help(string helpText)
{
Console.WriteLine();
Console.Write("Microsoft (R) .NET Native IL Compiler");
Console.Write(" ");
Console.Write(typeof(Program).GetTypeInfo().Assembly.GetName().Version);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine(helpText);
}
private void InitializeDefaultOptions()
{
#if FXCORE
// We could offer this as a command line option, but then we also need to
// load a different RyuJIT, so this is a future nice to have...
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
_targetOS = TargetOS.Windows;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
_targetOS = TargetOS.Linux;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
_targetOS = TargetOS.OSX;
else
throw new NotImplementedException();
switch (RuntimeInformation.ProcessArchitecture)
{
case Architecture.X86:
_targetArchitecture = TargetArchitecture.X86;
break;
case Architecture.X64:
_targetArchitecture = TargetArchitecture.X64;
break;
case Architecture.Arm:
_targetArchitecture = TargetArchitecture.ARM;
break;
case Architecture.Arm64:
_targetArchitecture = TargetArchitecture.ARM64;
break;
default:
throw new NotImplementedException();
}
#else
_targetOS = TargetOS.Windows;
_targetArchitecture = TargetArchitecture.X64;
#endif
}
private ArgumentSyntax ParseCommandLine(string[] args)
{
IReadOnlyList<string> inputFiles = Array.Empty<string>();
IReadOnlyList<string> referenceFiles = Array.Empty<string>();
bool optimize = false;
bool waitForDebugger = false;
AssemblyName name = typeof(Program).GetTypeInfo().Assembly.GetName();
ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax =>
{
syntax.ApplicationName = name.Name.ToString();
// HandleHelp writes to error, fails fast with crash dialog and lacks custom formatting.
syntax.HandleHelp = false;
syntax.HandleErrors = true;
syntax.DefineOption("h|help", ref _help, "Help message for ILC");
syntax.DefineOptionList("r|reference", ref referenceFiles, "Reference file(s) for compilation");
syntax.DefineOption("o|out", ref _outputFilePath, "Output file path");
syntax.DefineOption("O", ref optimize, "Enable optimizations");
syntax.DefineOption("g", ref _enableDebugInfo, "Emit debugging information");
syntax.DefineOption("cpp", ref _isCppCodegen, "Compile for C++ code-generation");
syntax.DefineOption("dgmllog", ref _dgmlLogFileName, "Save result of dependency analysis as DGML");
syntax.DefineOption("fulllog", ref _generateFullDgmlLog, "Save detailed log of dependency analysis");
syntax.DefineOption("verbose", ref _isVerbose, "Enable verbose logging");
syntax.DefineOption("systemmodule", ref _systemModuleName, "System module name (default: System.Private.CoreLib)");
syntax.DefineOption("multifile", ref _multiFile, "Compile only input files (do not compile referenced assemblies)");
syntax.DefineOption("waitfordebugger", ref waitForDebugger, "Pause to give opportunity to attach debugger");
syntax.DefineOption("usesharedgenerics", ref _useSharedGenerics, "Enable shared generics");
syntax.DefineOptionList("codegenopt", ref _codegenOptions, "Define a codegen option");
syntax.DefineOptionList("rdxml", ref _rdXmlFilePaths, "RD.XML file(s) for compilation");
syntax.DefineOption("map", ref _mapFileName, "Generate a map file");
syntax.DefineOption("metadatalog", ref _metadataLogFileName, "Generate a metadata log file");
syntax.DefineOption("targetarch", ref _targetArchitectureStr, "Target architecture for cross compilation");
syntax.DefineOption("targetos", ref _targetOSStr, "Target OS for cross compilation");
syntax.DefineOption("singlemethodtypename", ref _singleMethodTypeName, "Single method compilation: name of the owning type");
syntax.DefineOption("singlemethodname", ref _singleMethodName, "Single method compilation: name of the method");
syntax.DefineOptionList("singlemethodgenericarg", ref _singleMethodGenericArgs, "Single method compilation: generic arguments to the method");
syntax.DefineParameterList("in", ref inputFiles, "Input file(s) to compile");
});
if (waitForDebugger)
{
Console.WriteLine("Waiting for debugger to attach. Press ENTER to continue");
Console.ReadLine();
}
_optimizationMode = optimize ? OptimizationMode.Blended : OptimizationMode.None;
foreach (var input in inputFiles)
Helpers.AppendExpandedPaths(_inputFilePaths, input, true);
foreach (var reference in referenceFiles)
Helpers.AppendExpandedPaths(_referenceFilePaths, reference, false);
return argSyntax;
}
private int Run(string[] args)
{
InitializeDefaultOptions();
ArgumentSyntax syntax = ParseCommandLine(args);
if (_help)
{
Help(syntax.GetHelpText());
return 1;
}
if (_outputFilePath == null)
throw new CommandLineException("Output filename must be specified (/out <file>)");
//
// Set target Architecture and OS
//
if (_targetArchitectureStr != null)
{
if (_targetArchitectureStr.Equals("x86", StringComparison.OrdinalIgnoreCase))
_targetArchitecture = TargetArchitecture.X86;
else if (_targetArchitectureStr.Equals("x64", StringComparison.OrdinalIgnoreCase))
_targetArchitecture = TargetArchitecture.X64;
else if (_targetArchitectureStr.Equals("arm", StringComparison.OrdinalIgnoreCase))
_targetArchitecture = TargetArchitecture.ARM;
else if (_targetArchitectureStr.Equals("armel", StringComparison.OrdinalIgnoreCase))
_targetArchitecture = TargetArchitecture.ARMEL;
else if (_targetArchitectureStr.Equals("arm64", StringComparison.OrdinalIgnoreCase))
_targetArchitecture = TargetArchitecture.ARM64;
else
throw new CommandLineException("Target architecture is not supported");
}
if (_targetOSStr != null)
{
if (_targetOSStr.Equals("windows", StringComparison.OrdinalIgnoreCase))
_targetOS = TargetOS.Windows;
else if (_targetOSStr.Equals("linux", StringComparison.OrdinalIgnoreCase))
_targetOS = TargetOS.Linux;
else if (_targetOSStr.Equals("osx", StringComparison.OrdinalIgnoreCase))
_targetOS = TargetOS.OSX;
else
throw new CommandLineException("Target OS is not supported");
}
//
// Initialize type system context
//
SharedGenericsMode genericsMode = _useSharedGenerics || !_isCppCodegen ?
SharedGenericsMode.CanonicalReferenceTypes : SharedGenericsMode.Disabled;
var typeSystemContext = new CompilerTypeSystemContext(new TargetDetails(_targetArchitecture, _targetOS, TargetAbi.CoreRT), genericsMode);
//
// TODO: To support our pre-compiled test tree, allow input files that aren't managed assemblies since
// some tests contain a mixture of both managed and native binaries.
//
// See: https://github.com/dotnet/corert/issues/2785
//
// When we undo this this hack, replace this foreach with
// typeSystemContext.InputFilePaths = _inputFilePaths;
//
Dictionary<string, string> inputFilePaths = new Dictionary<string, string>();
foreach (var inputFile in _inputFilePaths)
{
try
{
var module = typeSystemContext.GetModuleFromPath(inputFile.Value);
inputFilePaths.Add(inputFile.Key, inputFile.Value);
}
catch (TypeSystemException.BadImageFormatException)
{
// Keep calm and carry on.
}
}
typeSystemContext.InputFilePaths = inputFilePaths;
typeSystemContext.ReferenceFilePaths = _referenceFilePaths;
typeSystemContext.SetSystemModule(typeSystemContext.GetModuleForSimpleName(_systemModuleName));
if (typeSystemContext.InputFilePaths.Count == 0)
throw new CommandLineException("No input files specified");
//
// Initialize compilation group and compilation roots
//
// Single method mode?
MethodDesc singleMethod = CheckAndParseSingleMethodModeArguments(typeSystemContext);
CompilationModuleGroup compilationGroup;
List<ICompilationRootProvider> compilationRoots = new List<ICompilationRootProvider>();
if (singleMethod != null)
{
// Compiling just a single method
compilationGroup = new SingleMethodCompilationModuleGroup(singleMethod);
compilationRoots.Add(new SingleMethodRootProvider(singleMethod));
}
else
{
// Either single file, or multifile library, or multifile consumption.
EcmaModule entrypointModule = null;
foreach (var inputFile in typeSystemContext.InputFilePaths)
{
EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value);
if (module.PEReader.PEHeaders.IsExe)
{
if (entrypointModule != null)
throw new Exception("Multiple EXE modules");
entrypointModule = module;
}
compilationRoots.Add(new ExportedMethodsRootProvider(module));
}
if (entrypointModule != null)
{
LibraryInitializers libraryInitializers =
new LibraryInitializers(typeSystemContext, _isCppCodegen);
compilationRoots.Add(new MainMethodRootProvider(entrypointModule, libraryInitializers.LibraryInitializerMethods));
}
if (_multiFile)
{
List<EcmaModule> inputModules = new List<EcmaModule>();
foreach (var inputFile in typeSystemContext.InputFilePaths)
{
EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value);
if (entrypointModule == null)
{
// This is a multifile production build - we need to root all methods
compilationRoots.Add(new LibraryRootProvider(module));
}
inputModules.Add(module);
}
compilationGroup = new MultiFileSharedCompilationModuleGroup(typeSystemContext, inputModules);
}
else
{
if (entrypointModule == null)
throw new Exception("No entrypoint module");
compilationRoots.Add(new ExportedMethodsRootProvider((EcmaModule)typeSystemContext.SystemModule));
compilationGroup = new SingleFileCompilationModuleGroup(typeSystemContext);
}
foreach (var rdXmlFilePath in _rdXmlFilePaths)
{
compilationRoots.Add(new RdXmlRootProvider(typeSystemContext, rdXmlFilePath));
}
}
//
// Compile
//
CompilationBuilder builder;
if (_isCppCodegen)
builder = new CppCodegenCompilationBuilder(typeSystemContext, compilationGroup);
else
builder = new RyuJitCompilationBuilder(typeSystemContext, compilationGroup);
var logger = _isVerbose ? new Logger(Console.Out, true) : Logger.Null;
DependencyTrackingLevel trackingLevel = _dgmlLogFileName == null ?
DependencyTrackingLevel.None : (_generateFullDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First);
CompilerGeneratedMetadataManager metadataManager = new CompilerGeneratedMetadataManager(compilationGroup, typeSystemContext, _metadataLogFileName);
ICompilation compilation = builder
.UseBackendOptions(_codegenOptions)
.UseMetadataManager(metadataManager)
.UseLogger(logger)
.UseDependencyTracking(trackingLevel)
.UseCompilationRoots(compilationRoots)
.UseOptimizationMode(_optimizationMode)
.UseDebugInfo(_enableDebugInfo)
.ToCompilation();
ObjectDumper dumper = _mapFileName != null ? new ObjectDumper(_mapFileName) : null;
compilation.Compile(_outputFilePath, dumper);
if (_dgmlLogFileName != null)
compilation.WriteDependencyLog(_dgmlLogFileName);
return 0;
}
private TypeDesc FindType(CompilerTypeSystemContext context, string typeName)
{
ModuleDesc systemModule = context.SystemModule;
TypeDesc foundType = systemModule.GetTypeByCustomAttributeTypeName(typeName);
if (foundType == null)
throw new CommandLineException($"Type '{typeName}' not found");
TypeDesc classLibCanon = systemModule.GetType("System", "__Canon", false);
TypeDesc classLibUniCanon = systemModule.GetType("System", "__UniversalCanon", false);
return foundType.ReplaceTypesInConstructionOfType(
new TypeDesc[] { classLibCanon, classLibUniCanon },
new TypeDesc[] { context.CanonType, context.UniversalCanonType });
}
private MethodDesc CheckAndParseSingleMethodModeArguments(CompilerTypeSystemContext context)
{
if (_singleMethodName == null && _singleMethodTypeName == null && _singleMethodGenericArgs == null)
return null;
if (_singleMethodName == null || _singleMethodTypeName == null)
throw new CommandLineException("Both method name and type name are required parameters for single method mode");
TypeDesc owningType = FindType(context, _singleMethodTypeName);
// TODO: allow specifying signature to distinguish overloads
MethodDesc method = owningType.GetMethod(_singleMethodName, null);
if (method == null)
throw new CommandLineException($"Method '{_singleMethodName}' not found in '{_singleMethodTypeName}'");
if (method.HasInstantiation != (_singleMethodGenericArgs != null) ||
(method.HasInstantiation && (method.Instantiation.Length != _singleMethodGenericArgs.Count)))
{
throw new CommandLineException(
$"Expected {method.Instantiation.Length} generic arguments for method '{_singleMethodName}' on type '{_singleMethodTypeName}'");
}
if (method.HasInstantiation)
{
List<TypeDesc> genericArguments = new List<TypeDesc>();
foreach (var argString in _singleMethodGenericArgs)
genericArguments.Add(FindType(context, argString));
method = method.MakeInstantiatedMethod(genericArguments.ToArray());
}
return method;
}
private static int Main(string[] args)
{
#if DEBUG
return new Program().Run(args);
#else
try
{
return new Program().Run(args);
}
catch (Exception e)
{
Console.Error.WriteLine("Error: " + e.Message);
Console.Error.WriteLine(e.ToString());
return 1;
}
#endif
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Reflection;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
// Name used for AGGDECLs in the symbol table.
// AggregateSymbol - a symbol representing an aggregate type. These are classes,
// interfaces, and structs. Parent is a namespace or class. Children are methods,
// properties, and member variables, and types (including its own AGGTYPESYMs).
internal class AggregateSymbol : NamespaceOrAggregateSymbol
{
public Type AssociatedSystemType;
public Assembly AssociatedAssembly;
// The instance type. Created when first needed.
private AggregateType _atsInst;
private AggregateType _pBaseClass; // For a class/struct/enum, the base class. For iface: unused.
private AggregateType _pUnderlyingType; // For enum, the underlying type. For iface, the resolved CoClass. Not used for class/struct.
private TypeArray _ifaces; // The explicit base interfaces for a class or interface.
private TypeArray _ifacesAll; // Recursive closure of base interfaces ordered so an iface appears before all of its base ifaces.
private TypeArray _typeVarsThis; // Type variables for this generic class, as declarations.
private TypeArray _typeVarsAll; // The type variables for this generic class and all containing classes.
// First UD conversion operator. This chain is for this type only (not base types).
// The hasConversion flag indicates whether this or any base types have UD conversions.
private MethodSymbol _pConvFirst;
// ------------------------------------------------------------------------
//
// Put members that are bits under here in a contiguous section.
//
// ------------------------------------------------------------------------
private AggKindEnum _aggKind;
// Where this came from - fabricated, source, import
// Fabricated AGGs have isSource == true but hasParseTree == false.
// N.B.: in incremental builds, it is quite possible for
// isSource==TRUE and hasParseTree==FALSE. Be
// sure you use the correct variable for what you are trying to do!
// Predefined
private bool _isPredefined; // A special predefined type.
private PredefinedType _iPredef; // index of the predefined type, if isPredefined.
// Flags
private bool _isAbstract; // Can it be instantiated?
private bool _isSealed; // Can it be derived from?
// Constructors
private bool _hasPubNoArgCtor; // Whether it has a public instance constructor taking no args
// User defined operators
private bool _isSkipUDOps; // Never check for user defined operators on this type (eg, decimal, string, delegate).
// When this is unset we don't know if we have conversions. When this
// is set it indicates if this type or any base type has user defined
// conversion operators
private bool? _hasConversion;
// ----------------------------------------------------------------------------
// AggregateSymbol
// ----------------------------------------------------------------------------
public AggregateSymbol GetBaseAgg()
{
return _pBaseClass?.OwningAggregate;
}
public AggregateType getThisType()
{
if (_atsInst == null)
{
Debug.Assert(GetTypeVars() == GetTypeVarsAll() || isNested());
AggregateType pOuterType = isNested() ? GetOuterAgg().getThisType() : null;
_atsInst = TypeManager.GetAggregate(this, pOuterType, GetTypeVars());
}
//Debug.Assert(GetTypeVars().Size == atsInst.GenericArguments.Count);
return _atsInst;
}
public bool FindBaseAgg(AggregateSymbol agg)
{
for (AggregateSymbol aggT = this; aggT != null; aggT = aggT.GetBaseAgg())
{
if (aggT == agg)
return true;
}
return false;
}
public NamespaceOrAggregateSymbol Parent => parent as NamespaceOrAggregateSymbol;
public bool isNested() => parent is AggregateSymbol;
public AggregateSymbol GetOuterAgg() => parent as AggregateSymbol;
public bool isPredefAgg(PredefinedType pt)
{
return _isPredefined && (PredefinedType)_iPredef == pt;
}
// ----------------------------------------------------------------------------
// The following are the Accessor functions for AggregateSymbol.
// ----------------------------------------------------------------------------
public AggKindEnum AggKind()
{
return (AggKindEnum)_aggKind;
}
public void SetAggKind(AggKindEnum aggKind)
{
// NOTE: When importing can demote types:
// - enums with no underlying type go to struct
// - delegates which are abstract or have no .ctor/Invoke method goto class
_aggKind = aggKind;
//An interface is always abstract
if (aggKind == AggKindEnum.Interface)
{
SetAbstract(true);
}
}
public bool IsClass()
{
return AggKind() == AggKindEnum.Class;
}
public bool IsDelegate()
{
return AggKind() == AggKindEnum.Delegate;
}
public bool IsInterface()
{
return AggKind() == AggKindEnum.Interface;
}
public bool IsStruct()
{
return AggKind() == AggKindEnum.Struct;
}
public bool IsEnum()
{
return AggKind() == AggKindEnum.Enum;
}
public bool IsValueType()
{
return AggKind() == AggKindEnum.Struct || AggKind() == AggKindEnum.Enum;
}
public bool IsRefType()
{
return AggKind() == AggKindEnum.Class ||
AggKind() == AggKindEnum.Interface || AggKind() == AggKindEnum.Delegate;
}
public bool IsStatic()
{
return (_isAbstract && _isSealed);
}
public bool IsAbstract()
{
return _isAbstract;
}
public void SetAbstract(bool @abstract)
{
_isAbstract = @abstract;
}
public bool IsPredefined()
{
return _isPredefined;
}
public void SetPredefined(bool predefined)
{
_isPredefined = predefined;
}
public PredefinedType GetPredefType()
{
return (PredefinedType)_iPredef;
}
public void SetPredefType(PredefinedType predef)
{
_iPredef = predef;
}
public bool IsSealed()
{
return _isSealed == true;
}
public void SetSealed(bool @sealed)
{
_isSealed = @sealed;
}
////////////////////////////////////////////////////////////////////////////////
public bool HasConversion()
{
SymbolTable.AddConversionsForType(AssociatedSystemType);
if (!_hasConversion.HasValue)
{
// ok, we tried defining all the conversions, and we didn't get anything
// for this type. However, we will still think this type has conversions
// if it's base type has conversions.
_hasConversion = GetBaseAgg() != null && GetBaseAgg().HasConversion();
}
return _hasConversion.Value;
}
////////////////////////////////////////////////////////////////////////////////
public void SetHasConversion()
{
_hasConversion = true;
}
////////////////////////////////////////////////////////////////////////////////
public bool HasPubNoArgCtor()
{
return _hasPubNoArgCtor == true;
}
public void SetHasPubNoArgCtor(bool hasPubNoArgCtor)
{
_hasPubNoArgCtor = hasPubNoArgCtor;
}
public bool IsSkipUDOps()
{
return _isSkipUDOps == true;
}
public void SetSkipUDOps(bool skipUDOps)
{
_isSkipUDOps = skipUDOps;
}
public TypeArray GetTypeVars()
{
return _typeVarsThis;
}
public void SetTypeVars(TypeArray typeVars)
{
if (typeVars == null)
{
_typeVarsThis = null;
_typeVarsAll = null;
}
else
{
TypeArray outerTypeVars;
if (GetOuterAgg() != null)
{
Debug.Assert(GetOuterAgg().GetTypeVars() != null);
Debug.Assert(GetOuterAgg().GetTypeVarsAll() != null);
outerTypeVars = GetOuterAgg().GetTypeVarsAll();
}
else
{
outerTypeVars = TypeArray.Empty;
}
_typeVarsThis = typeVars;
_typeVarsAll = TypeArray.Concat(outerTypeVars, typeVars);
}
}
public TypeArray GetTypeVarsAll()
{
return _typeVarsAll;
}
public AggregateType GetBaseClass()
{
return _pBaseClass;
}
public void SetBaseClass(AggregateType baseClass)
{
_pBaseClass = baseClass;
}
public AggregateType GetUnderlyingType()
{
return _pUnderlyingType;
}
public void SetUnderlyingType(AggregateType underlyingType)
{
_pUnderlyingType = underlyingType;
}
public TypeArray GetIfaces()
{
return _ifaces;
}
public void SetIfaces(TypeArray ifaces)
{
_ifaces = ifaces;
}
public TypeArray GetIfacesAll()
{
return _ifacesAll;
}
public void SetIfacesAll(TypeArray ifacesAll)
{
_ifacesAll = ifacesAll;
}
public MethodSymbol GetFirstUDConversion()
{
return _pConvFirst;
}
public void SetFirstUDConversion(MethodSymbol conv)
{
_pConvFirst = conv;
}
public bool InternalsVisibleTo(Assembly assembly) => TypeManager.InternalsVisibleTo(AssociatedAssembly, assembly);
}
}
| |
// 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.AcceptanceTestsRequiredOptional
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
/// <summary>
/// ExplicitModel operations.
/// </summary>
public partial interface IExplicitModel
{
/// <summary>
/// Test explicitly required integer. Please put null and the client
/// library should throw before the request is sent.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<HttpOperationResponse<Error>> PostRequiredIntegerParameterWithHttpMessagesAsync(int bodyParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional integer. Please put null.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<HttpOperationResponse> PostOptionalIntegerParameterWithHttpMessagesAsync(int? bodyParameter = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly required integer. Please put a valid int-wrapper
/// with 'value' = null and the client library should throw before
/// the request is sent.
/// </summary>
/// <param name='value'>
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<HttpOperationResponse<Error>> PostRequiredIntegerPropertyWithHttpMessagesAsync(int value, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional integer. Please put a valid int-wrapper
/// with 'value' = null.
/// </summary>
/// <param name='value'>
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<HttpOperationResponse> PostOptionalIntegerPropertyWithHttpMessagesAsync(int? value = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly required integer. Please put a header
/// 'headerParameter' => null and the client library should throw
/// before the request is sent.
/// </summary>
/// <param name='headerParameter'>
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<HttpOperationResponse<Error>> PostRequiredIntegerHeaderWithHttpMessagesAsync(int headerParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional integer. Please put a header
/// 'headerParameter' => null.
/// </summary>
/// <param name='headerParameter'>
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<HttpOperationResponse> PostOptionalIntegerHeaderWithHttpMessagesAsync(int? headerParameter = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly required string. Please put null and the client
/// library should throw before the request is sent.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// The 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="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<Error>> PostRequiredStringParameterWithHttpMessagesAsync(string bodyParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional string. Please put null.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<HttpOperationResponse> PostOptionalStringParameterWithHttpMessagesAsync(string bodyParameter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly required string. Please put a valid string-wrapper
/// with 'value' = null and the client library should throw before
/// the request is sent.
/// </summary>
/// <param name='value'>
/// </param>
/// <param name='customHeaders'>
/// The 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="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<Error>> PostRequiredStringPropertyWithHttpMessagesAsync(string value, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional integer. Please put a valid
/// string-wrapper with 'value' = null.
/// </summary>
/// <param name='value'>
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<HttpOperationResponse> PostOptionalStringPropertyWithHttpMessagesAsync(string value = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly required string. Please put a header
/// 'headerParameter' => null and the client library should throw
/// before the request is sent.
/// </summary>
/// <param name='headerParameter'>
/// </param>
/// <param name='customHeaders'>
/// The 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="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<Error>> PostRequiredStringHeaderWithHttpMessagesAsync(string headerParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional string. Please put a header
/// 'headerParameter' => null.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<HttpOperationResponse> PostOptionalStringHeaderWithHttpMessagesAsync(string bodyParameter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly required complex object. Please put null and the
/// client library should throw before the request is sent.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// The 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="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<Error>> PostRequiredClassParameterWithHttpMessagesAsync(Product bodyParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional complex object. Please put null.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<HttpOperationResponse> PostOptionalClassParameterWithHttpMessagesAsync(Product bodyParameter = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly required complex object. Please put a valid
/// class-wrapper with 'value' = null and the client library should
/// throw before the request is sent.
/// </summary>
/// <param name='value'>
/// </param>
/// <param name='customHeaders'>
/// The 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="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<Error>> PostRequiredClassPropertyWithHttpMessagesAsync(Product value, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional complex object. Please put a valid
/// class-wrapper with 'value' = null.
/// </summary>
/// <param name='value'>
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<HttpOperationResponse> PostOptionalClassPropertyWithHttpMessagesAsync(Product value = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly required array. Please put null and the client
/// library should throw before the request is sent.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// The 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="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<Error>> PostRequiredArrayParameterWithHttpMessagesAsync(IList<string> bodyParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional array. Please put null.
/// </summary>
/// <param name='bodyParameter'>
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<HttpOperationResponse> PostOptionalArrayParameterWithHttpMessagesAsync(IList<string> bodyParameter = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly required array. Please put a valid array-wrapper
/// with 'value' = null and the client library should throw before
/// the request is sent.
/// </summary>
/// <param name='value'>
/// </param>
/// <param name='customHeaders'>
/// The 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="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<Error>> PostRequiredArrayPropertyWithHttpMessagesAsync(IList<string> value, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional array. Please put a valid array-wrapper
/// with 'value' = null.
/// </summary>
/// <param name='value'>
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<HttpOperationResponse> PostOptionalArrayPropertyWithHttpMessagesAsync(IList<string> value = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly required array. Please put a header
/// 'headerParameter' => null and the client library should throw
/// before the request is sent.
/// </summary>
/// <param name='headerParameter'>
/// </param>
/// <param name='customHeaders'>
/// The 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="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<Error>> PostRequiredArrayHeaderWithHttpMessagesAsync(IList<string> headerParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Test explicitly optional integer. Please put a header
/// 'headerParameter' => null.
/// </summary>
/// <param name='headerParameter'>
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<HttpOperationResponse> PostOptionalArrayHeaderWithHttpMessagesAsync(IList<string> headerParameter = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace WebApiHelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.ComponentModel.Composition;
using System.Linq;
using EnvDTE;
using Microsoft.VisualStudio.Shell.Interop;
namespace NuGet.VisualStudio
{
[PartCreationPolicy(CreationPolicy.Shared)]
[Export(typeof(IVsPackageManagerFactory))]
public class VsPackageManagerFactory : IVsPackageManagerFactory
{
private readonly IPackageRepositoryFactory _repositoryFactory;
private readonly ISolutionManager _solutionManager;
private readonly IFileSystemProvider _fileSystemProvider;
private readonly IRepositorySettings _repositorySettings;
private readonly IVsPackageSourceProvider _packageSourceProvider;
private readonly VsPackageInstallerEvents _packageEvents;
private readonly IPackageRepository _activePackageSourceRepository;
private readonly IVsFrameworkMultiTargeting _frameworkMultiTargeting;
private RepositoryInfo _repositoryInfo;
[ImportingConstructor]
public VsPackageManagerFactory(ISolutionManager solutionManager,
IPackageRepositoryFactory repositoryFactory,
IVsPackageSourceProvider packageSourceProvider,
IFileSystemProvider fileSystemProvider,
IRepositorySettings repositorySettings,
VsPackageInstallerEvents packageEvents,
IPackageRepository activePackageSourceRepository) :
this(solutionManager,
repositoryFactory,
packageSourceProvider,
fileSystemProvider,
repositorySettings,
packageEvents,
activePackageSourceRepository,
ServiceLocator.GetGlobalService<SVsFrameworkMultiTargeting, IVsFrameworkMultiTargeting>())
{
}
public VsPackageManagerFactory(ISolutionManager solutionManager,
IPackageRepositoryFactory repositoryFactory,
IVsPackageSourceProvider packageSourceProvider,
IFileSystemProvider fileSystemProvider,
IRepositorySettings repositorySettings,
VsPackageInstallerEvents packageEvents,
IPackageRepository activePackageSourceRepository,
IVsFrameworkMultiTargeting frameworkMultiTargeting)
{
if (solutionManager == null)
{
throw new ArgumentNullException("solutionManager");
}
if (repositoryFactory == null)
{
throw new ArgumentNullException("repositoryFactory");
}
if (packageSourceProvider == null)
{
throw new ArgumentNullException("packageSourceProvider");
}
if (fileSystemProvider == null)
{
throw new ArgumentNullException("fileSystemProvider");
}
if (repositorySettings == null)
{
throw new ArgumentNullException("repositorySettings");
}
if (packageEvents == null)
{
throw new ArgumentNullException("packageEvents");
}
if (activePackageSourceRepository == null)
{
throw new ArgumentNullException("activePackageSourceRepository");
}
_fileSystemProvider = fileSystemProvider;
_repositorySettings = repositorySettings;
_solutionManager = solutionManager;
_repositoryFactory = repositoryFactory;
_packageSourceProvider = packageSourceProvider;
_packageEvents = packageEvents;
_activePackageSourceRepository = activePackageSourceRepository;
_frameworkMultiTargeting = frameworkMultiTargeting;
_solutionManager.SolutionClosing += (sender, e) =>
{
_repositoryInfo = null;
};
}
/// <summary>
/// Creates an VsPackageManagerInstance that uses the Active Repository (the repository selected in the console drop down) and uses a fallback repository for dependencies.
/// </summary>
public IVsPackageManager CreatePackageManager()
{
return CreatePackageManager(_activePackageSourceRepository, useFallbackForDependencies: true);
}
public IVsPackageManager CreatePackageManager(IPackageRepository repository, bool useFallbackForDependencies)
{
if (useFallbackForDependencies)
{
repository = CreateFallbackRepository(repository);
}
RepositoryInfo info = GetRepositoryInfo();
return new VsPackageManager(_solutionManager,
repository,
_fileSystemProvider,
info.FileSystem,
info.Repository,
// We ensure DeleteOnRestartManager is initialized with a PhysicalFileSystem so the
// .deleteme marker files that get created don't get checked into version control
new DeleteOnRestartManager(() => new PhysicalFileSystem(info.FileSystem.Root)),
_packageEvents,
_frameworkMultiTargeting);
}
public IVsPackageManager CreatePackageManagerWithAllPackageSources()
{
return CreatePackageManagerWithAllPackageSources(_activePackageSourceRepository);
}
internal IVsPackageManager CreatePackageManagerWithAllPackageSources(IPackageRepository repository)
{
if (IsAggregateRepository(repository))
{
return CreatePackageManager(repository, false);
}
var priorityRepository = _packageSourceProvider.CreatePriorityPackageRepository(_repositoryFactory, repository);
return CreatePackageManager(priorityRepository, useFallbackForDependencies: false);
}
/// <summary>
/// Creates a FallbackRepository with an aggregate repository that also contains the primaryRepository.
/// </summary>
internal IPackageRepository CreateFallbackRepository(IPackageRepository primaryRepository)
{
if (IsAggregateRepository(primaryRepository))
{
// If we're using the aggregate repository, we don't need to create a fall back repo.
return primaryRepository;
}
var aggregateRepository = _packageSourceProvider.CreateAggregateRepository(_repositoryFactory, ignoreFailingRepositories: true);
aggregateRepository.ResolveDependenciesVertically = true;
return new FallbackRepository(primaryRepository, aggregateRepository);
}
private static bool IsAggregateRepository(IPackageRepository repository)
{
if (repository is AggregateRepository)
{
// This test should be ok as long as any aggregate repository that we encounter here means the true Aggregate repository
// of all repositories in the package source.
// Since the repository created here comes from the UI, this holds true.
return true;
}
var vsPackageSourceRepository = repository as VsPackageSourceRepository;
if (vsPackageSourceRepository != null)
{
return IsAggregateRepository(vsPackageSourceRepository.GetActiveRepository());
}
return false;
}
private RepositoryInfo GetRepositoryInfo()
{
// Update the path if it needs updating
string path = _repositorySettings.RepositoryPath;
string configFolderPath = _repositorySettings.ConfigFolderPath;
if (_repositoryInfo == null ||
!_repositoryInfo.Path.Equals(path, StringComparison.OrdinalIgnoreCase) ||
!_repositoryInfo.ConfigFolderPath.Equals(configFolderPath, StringComparison.OrdinalIgnoreCase) ||
_solutionManager.IsSourceControlBound != _repositoryInfo.IsSourceControlBound)
{
IFileSystem fileSystem = _fileSystemProvider.GetFileSystem(path);
IFileSystem configSettingsFileSystem = GetConfigSettingsFileSystem(configFolderPath);
// this file system is used to access the repositories.config file. We want to use Source Control-bound
// file system to access it even if the 'disableSourceControlIntegration' setting is set.
IFileSystem storeFileSystem = _fileSystemProvider.GetFileSystem(path, ignoreSourceControlSetting: true);
ISharedPackageRepository repository = new SharedPackageRepository(
new DefaultPackagePathResolver(fileSystem),
fileSystem,
storeFileSystem,
configSettingsFileSystem);
_repositoryInfo = new RepositoryInfo(path, configFolderPath, fileSystem, repository);
}
return _repositoryInfo;
}
protected internal virtual IFileSystem GetConfigSettingsFileSystem(string configFolderPath)
{
return new SolutionFolderFileSystem(ServiceLocator.GetInstance<DTE>().Solution, VsConstants.NuGetSolutionSettingsFolder, configFolderPath);
}
private class RepositoryInfo
{
public RepositoryInfo(string path, string configFolderPath, IFileSystem fileSystem, ISharedPackageRepository repository)
{
Path = path;
FileSystem = fileSystem;
Repository = repository;
ConfigFolderPath = configFolderPath;
}
public bool IsSourceControlBound
{
get
{
return FileSystem is ISourceControlFileSystem;
}
}
public IFileSystem FileSystem { get; private set; }
public string Path { get; private set; }
public string ConfigFolderPath { get; private set; }
public ISharedPackageRepository Repository { get; private set; }
}
}
}
| |
using System.Collections.Generic;
using System;
using System.Linq;
using System.Threading;
using UnityEngine;
namespace UnityThreading
{
public abstract class DispatcherBase : IDisposable
{
protected int lockCount = 0;
protected object taskListSyncRoot = new object();
protected Queue<Task> taskList = new Queue<Task>();
protected Queue<Task> delayedTaskList = new Queue<Task>();
protected ManualResetEvent dataEvent = new ManualResetEvent(false);
public DispatcherBase()
{
}
public bool IsWorking
{
get
{
return dataEvent.InterWaitOne(0);
}
}
public bool AllowAccessLimitationChecks;
/// <summary>
/// Set the task reordering system
/// </summary>
public TaskSortingSystem TaskSortingSystem;
/// <summary>
/// Returns the currently existing task count. Early aborted tasks will count too.
/// </summary>
public virtual int TaskCount
{
get
{
lock (taskListSyncRoot)
return taskList.Count;
}
}
public void Lock()
{
lock (taskListSyncRoot)
{
lockCount++;
}
}
public void Unlock()
{
lock (taskListSyncRoot)
{
lockCount--;
if (lockCount == 0 && delayedTaskList.Count > 0)
{
while (delayedTaskList.Count > 0)
taskList.Enqueue(delayedTaskList.Dequeue());
if (TaskSortingSystem == UnityThreading.TaskSortingSystem.ReorderWhenAdded ||
TaskSortingSystem == UnityThreading.TaskSortingSystem.ReorderWhenExecuted)
ReorderTasks();
TasksAdded();
}
}
}
/// <summary>
/// Creates a new Task based upon the given action.
/// </summary>
/// <typeparam name="T">The return value of the task.</typeparam>
/// <param name="function">The function to process at the dispatchers thread.</param>
/// <returns>The new task.</returns>
public Task<T> Dispatch<T>(Func<T> function)
{
CheckAccessLimitation();
var task = new Task<T>(function);
AddTask(task);
return task;
}
/// <summary>
/// Creates a new Task based upon the given action.
/// </summary>
/// <param name="action">The action to process at the dispatchers thread.</param>
/// <returns>The new task.</returns>
public Task Dispatch(Action action)
{
CheckAccessLimitation();
var task = Task.Create(action);
AddTask(task);
return task;
}
/// <summary>
/// Dispatches a given Task.
/// </summary>
/// <param name="action">The action to process at the dispatchers thread.</param>
/// <returns>The new task.</returns>
public Task Dispatch(Task task)
{
CheckAccessLimitation();
AddTask(task);
return task;
}
internal virtual void AddTask(Task task)
{
lock (taskListSyncRoot)
{
if (lockCount > 0)
{
delayedTaskList.Enqueue(task);
return;
}
taskList.Enqueue(task);
if (TaskSortingSystem == UnityThreading.TaskSortingSystem.ReorderWhenAdded ||
TaskSortingSystem == UnityThreading.TaskSortingSystem.ReorderWhenExecuted)
ReorderTasks();
}
TasksAdded();
}
internal void AddTasks(IEnumerable<Task> tasks)
{
lock (taskListSyncRoot)
{
if (lockCount > 0)
{
foreach (var task in tasks)
delayedTaskList.Enqueue(task);
return;
}
foreach (var task in tasks)
taskList.Enqueue(task);
if (TaskSortingSystem == UnityThreading.TaskSortingSystem.ReorderWhenAdded || TaskSortingSystem == UnityThreading.TaskSortingSystem.ReorderWhenExecuted)
ReorderTasks();
}
TasksAdded();
}
internal virtual void TasksAdded()
{
dataEvent.Set();
}
protected void ReorderTasks()
{
taskList = new Queue<Task>(taskList.OrderBy(t => t.Priority));
}
internal IEnumerable<Task> SplitTasks(int divisor)
{
if (divisor == 0)
divisor = 2;
var count = TaskCount / divisor;
return IsolateTasks(count);
}
internal IEnumerable<Task> IsolateTasks(int count)
{
Queue<Task> newTasks = new Queue<Task>();
if (count == 0)
count = taskList.Count;
lock (taskListSyncRoot)
{
for (int i = 0; i < count && i < taskList.Count; ++i)
newTasks.Enqueue(taskList.Dequeue());
//if (TaskSortingSystem == TaskSortingSystem.ReorderWhenExecuted)
// taskList = ReorderTasks(taskList);
if (TaskCount == 0)
dataEvent.Reset();
}
return newTasks;
}
protected abstract void CheckAccessLimitation();
#region IDisposable Members
public virtual void Dispose()
{
while (true)
{
Task currentTask;
lock (taskListSyncRoot)
{
if (taskList.Count != 0)
currentTask = taskList.Dequeue();
else
break;
}
currentTask.Dispose();
}
dataEvent.Close();
dataEvent = null;
}
#endregion
}
public class NullDispatcher : DispatcherBase
{
public static NullDispatcher Null = new NullDispatcher();
protected override void CheckAccessLimitation()
{
}
internal override void AddTask(Task task)
{
task.DoInternal();
}
}
public class Dispatcher : DispatcherBase
{
[ThreadStatic]
private static Task currentTask;
[ThreadStatic]
internal static Dispatcher currentDispatcher;
protected static Dispatcher mainDispatcher;
/// <summary>
/// Returns the task which is currently being processed. Use this only inside a task operation.
/// </summary>
public static Task CurrentTask
{
get
{
if (currentTask == null)
throw new InvalidOperationException("No task is currently running.");
return currentTask;
}
}
/// <summary>
/// Returns the Dispatcher instance of the current thread. When no instance has been created an exception will be thrown.
/// </summary>
///
public static Dispatcher Current
{
get
{
if (currentDispatcher == null)
throw new InvalidOperationException("No Dispatcher found for the current thread, please create a new Dispatcher instance before calling this property.");
return currentDispatcher;
}
set
{
if (currentDispatcher != null)
currentDispatcher.Dispose();
currentDispatcher = value;
}
}
/// <summary>
/// Returns the Dispatcher instance of the current thread.
/// </summary>
///
public static Dispatcher CurrentNoThrow
{
get
{
return currentDispatcher;
}
}
/// <summary>
/// Returns the first created Dispatcher instance, in most cases this will be the Dispatcher for the main thread. When no instance has been created an exception will be thrown.
/// </summary>
public static Dispatcher Main
{
get
{
if (mainDispatcher == null)
throw new InvalidOperationException("No Dispatcher found for the main thread, please create a new Dispatcher instance before calling this property.");
return mainDispatcher;
}
}
/// <summary>
/// Returns the first created Dispatcher instance.
/// </summary>
public static Dispatcher MainNoThrow
{
get
{
return mainDispatcher;
}
}
/// <summary>
/// Creates a new function based upon an other function which will handle exceptions. Use this to wrap safe functions for tasks.
/// </summary>
/// <typeparam name="T">The return type of the function.</typeparam>
/// <param name="function">The orignal function.</param>
/// <returns>The safe function.</returns>
public static Func<T> CreateSafeFunction<T>(Func<T> function)
{
return () =>
{
try
{
return function();
}
catch
{
CurrentTask.Abort();
return default(T);
}
};
}
/// <summary>
/// Creates a new action based upon an other action which will handle exceptions. Use this to wrap safe action for tasks.
/// </summary>
/// <param name="function">The orignal action.</param>
/// <returns>The safe action.</returns>
public static Action CreateSafeAction<T>(Action action)
{
return () =>
{
try
{
action();
}
catch
{
CurrentTask.Abort();
}
};
}
/// <summary>
/// Creates a Dispatcher, if a Dispatcher has been created in the current thread an exception will be thrown.
/// </summary>
public Dispatcher()
: this(true)
{
}
/// <summary>
/// Creates a Dispatcher, if a Dispatcher has been created when setThreadDefaults is set to true in the current thread an exception will be thrown.
/// </summary>
/// <param name="setThreadDefaults">If set to true the new dispatcher will be set as threads default dispatcher.</param>
public Dispatcher(bool setThreadDefaults)
{
if (!setThreadDefaults)
return;
if (currentDispatcher != null)
throw new InvalidOperationException("Only one Dispatcher instance allowed per thread.");
currentDispatcher = this;
if (mainDispatcher == null)
mainDispatcher = this;
}
/// <summary>
/// Processes all remaining tasks. Call this periodically to allow the Dispatcher to handle dispatched tasks.
/// Only call this inside the thread you want the tasks to process to be processed.
/// </summary>
public void ProcessTasks()
{
if (dataEvent.InterWaitOne(0))
ProcessTasksInternal();
}
/// <summary>
/// Processes all remaining tasks and returns true when something has been processed and false otherwise.
/// This method will block until th exitHandle has been set or tasks should be processed.
/// Only call this inside the thread you want the tasks to process to be processed.
/// </summary>
/// <param name="exitHandle">The handle to indicate an early abort of the wait process.</param>
/// <returns>False when the exitHandle has been set, true otherwise.</returns>
public bool ProcessTasks(WaitHandle exitHandle)
{
var result = WaitHandle.WaitAny(new WaitHandle[] { exitHandle, dataEvent });
if (result == 0)
return false;
ProcessTasksInternal();
return true;
}
/// <summary>
/// Processed the next available task.
/// Only call this inside the thread you want the tasks to process to be processed.
/// </summary>
/// <returns>True when a task to process has been processed, false otherwise.</returns>
public bool ProcessNextTask()
{
Task task;
lock (taskListSyncRoot)
{
if (taskList.Count == 0)
return false;
task = taskList.Dequeue();
}
ProcessSingleTask(task);
if (TaskCount == 0)
dataEvent.Reset();
return true;
}
/// <summary>
/// Processes the next available tasks and returns true when it has been processed and false otherwise.
/// This method will block until th exitHandle has been set or a task should be processed.
/// Only call this inside the thread you want the tasks to process to be processed.
/// </summary>
/// <param name="exitHandle">The handle to indicate an early abort of the wait process.</param>
/// <returns>False when the exitHandle has been set, true otherwise.</returns>
public bool ProcessNextTask(WaitHandle exitHandle)
{
var result = WaitHandle.WaitAny(new WaitHandle[] { exitHandle, dataEvent });
if (result == 0)
return false;
Task task;
lock (taskListSyncRoot)
{
if (taskList.Count == 0)
return false;
task = taskList.Dequeue();
}
ProcessSingleTask(task);
if (TaskCount == 0)
dataEvent.Reset();
return true;
}
private void ProcessTasksInternal()
{
List<Task> tmpCopy;
lock (taskListSyncRoot)
{
tmpCopy = new List<Task>(taskList);
taskList.Clear();
}
while (tmpCopy.Count != 0)
{
var task = tmpCopy[0];
tmpCopy.RemoveAt(0);
ProcessSingleTask(task);
}
if (TaskCount == 0)
dataEvent.Reset();
}
private void ProcessSingleTask(Task task)
{
RunTask(task);
if (TaskSortingSystem == TaskSortingSystem.ReorderWhenExecuted)
lock (taskListSyncRoot)
ReorderTasks();
}
internal void RunTask(Task task)
{
var oldTask = currentTask;
currentTask = task;
currentTask.DoInternal();
currentTask = oldTask;
}
protected override void CheckAccessLimitation()
{
if (AllowAccessLimitationChecks && currentDispatcher == this)
throw new InvalidOperationException("Dispatching a Task with the Dispatcher associated to the current thread is prohibited. You can run these Tasks without the need of a Dispatcher.");
}
#region IDisposable Members
/// <summary>
/// Disposes all dispatcher resources and remaining tasks.
/// </summary>
public override void Dispose()
{
while (true)
{
lock (taskListSyncRoot)
{
if (taskList.Count != 0)
currentTask = taskList.Dequeue();
else
break;
}
currentTask.Dispose();
}
dataEvent.Close();
dataEvent = null;
if (currentDispatcher == this)
currentDispatcher = null;
if (mainDispatcher == this)
mainDispatcher = null;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Text
{
using System.Runtime.Serialization;
using System.Text;
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
// A Decoder is used to decode a sequence of blocks of bytes into a
// sequence of blocks of characters. Following instantiation of a decoder,
// sequential blocks of bytes are converted into blocks of characters through
// calls to the GetChars method. The decoder maintains state between the
// conversions, allowing it to correctly decode byte sequences that span
// adjacent blocks.
//
// Instances of specific implementations of the Decoder abstract base
// class are typically obtained through calls to the GetDecoder method
// of Encoding objects.
//
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public abstract class Decoder
{
internal DecoderFallback m_fallback = null;
[NonSerialized]
internal DecoderFallbackBuffer m_fallbackBuffer = null;
internal void SerializeDecoder(SerializationInfo info)
{
info.AddValue("m_fallback", this.m_fallback);
}
protected Decoder( )
{
// We don't call default reset because default reset probably isn't good if we aren't initialized.
}
[System.Runtime.InteropServices.ComVisible(false)]
public DecoderFallback Fallback
{
get
{
return m_fallback;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
// Can't change fallback if buffer is wrong
if (m_fallbackBuffer != null && m_fallbackBuffer.Remaining > 0)
throw new ArgumentException(
Environment.GetResourceString("Argument_FallbackBufferNotEmpty"), nameof(value));
m_fallback = value;
m_fallbackBuffer = null;
}
}
// Note: we don't test for threading here because async access to Encoders and Decoders
// doesn't work anyway.
[System.Runtime.InteropServices.ComVisible(false)]
public DecoderFallbackBuffer FallbackBuffer
{
get
{
if (m_fallbackBuffer == null)
{
if (m_fallback != null)
m_fallbackBuffer = m_fallback.CreateFallbackBuffer();
else
m_fallbackBuffer = DecoderFallback.ReplacementFallback.CreateFallbackBuffer();
}
return m_fallbackBuffer;
}
}
internal bool InternalHasFallbackBuffer
{
get
{
return m_fallbackBuffer != null;
}
}
// Reset the Decoder
//
// Normally if we call GetChars() and an error is thrown we don't change the state of the Decoder. This
// would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.)
//
// If the caller doesn't want to try again after GetChars() throws an error, then they need to call Reset().
//
// Virtual implimentation has to call GetChars with flush and a big enough buffer to clear a 0 byte string
// We avoid GetMaxCharCount() because a) we can't call the base encoder and b) it might be really big.
[System.Runtime.InteropServices.ComVisible(false)]
public virtual void Reset()
{
byte[] byteTemp = Array.Empty<byte>();
char[] charTemp = new char[GetCharCount(byteTemp, 0, 0, true)];
GetChars(byteTemp, 0, 0, charTemp, 0, true);
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
// Returns the number of characters the next call to GetChars will
// produce if presented with the given range of bytes. The returned value
// takes into account the state in which the decoder was left following the
// last call to GetChars. The state of the decoder is not affected
// by a call to this method.
//
public abstract int GetCharCount(byte[] bytes, int index, int count);
[System.Runtime.InteropServices.ComVisible(false)]
public virtual int GetCharCount(byte[] bytes, int index, int count, bool flush)
{
return GetCharCount(bytes, index, count);
}
// We expect this to be the workhorse for NLS Encodings, but for existing
// ones we need a working (if slow) default implimentation)
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe int GetCharCount(byte* bytes, int count, bool flush)
{
// Validate input parameters
if (bytes == null)
throw new ArgumentNullException(nameof(bytes),
Environment.GetResourceString("ArgumentNull_Array"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
byte[] arrbyte = new byte[count];
int index;
for (index = 0; index < count; index++)
arrbyte[index] = bytes[index];
return GetCharCount(arrbyte, 0, count);
}
// Decodes a range of bytes in a byte array into a range of characters
// in a character array. The method decodes byteCount bytes from
// bytes starting at index byteIndex, storing the resulting
// characters in chars starting at index charIndex. The
// decoding takes into account the state in which the decoder was left
// following the last call to this method.
//
// An exception occurs if the character array is not large enough to
// hold the complete decoding of the bytes. The GetCharCount method
// can be used to determine the exact number of characters that will be
// produced for a given range of bytes. Alternatively, the
// GetMaxCharCount method of the Encoding that produced this
// decoder can be used to determine the maximum number of characters that
// will be produced for a given number of bytes, regardless of the actual
// byte values.
//
public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex);
public virtual int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, bool flush)
{
return GetChars(bytes, byteIndex, byteCount, chars, charIndex);
}
// We expect this to be the workhorse for NLS Encodings, but for existing
// ones we need a working (if slow) default implimentation)
//
// WARNING WARNING WARNING
//
// WARNING: If this breaks it could be a security threat. Obviously we
// call this internally, so you need to make sure that your pointers, counts
// and indexes are correct when you call this method.
//
// In addition, we have internal code, which will be marked as "safe" calling
// this code. However this code is dependent upon the implimentation of an
// external GetChars() method, which could be overridden by a third party and
// the results of which cannot be guaranteed. We use that result to copy
// the char[] to our char* output buffer. If the result count was wrong, we
// could easily overflow our output buffer. Therefore we do an extra test
// when we copy the buffer so that we don't overflow charCount either.
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, bool flush)
{
// Validate input parameters
if (chars == null || bytes == null)
throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes),
Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Get the byte array to convert
byte[] arrByte = new byte[byteCount];
int index;
for (index = 0; index < byteCount; index++)
arrByte[index] = bytes[index];
// Get the char array to fill
char[] arrChar = new char[charCount];
// Do the work
int result = GetChars(arrByte, 0, byteCount, arrChar, 0, flush);
Debug.Assert(result <= charCount, "Returned more chars than we have space for");
// Copy the char array
// WARNING: We MUST make sure that we don't copy too many chars. We can't
// rely on result because it could be a 3rd party implimentation. We need
// to make sure we never copy more than charCount chars no matter the value
// of result
if (result < charCount)
charCount = result;
// We check both result and charCount so that we don't accidentally overrun
// our pointer buffer just because of an issue in GetChars
for (index = 0; index < charCount; index++)
chars[index] = arrChar[index];
return charCount;
}
// This method is used when the output buffer might not be large enough.
// It will decode until it runs out of bytes, and then it will return
// true if it the entire input was converted. In either case it
// will also return the number of converted bytes and output characters used.
// It will only throw a buffer overflow exception if the entire lenght of chars[] is
// too small to store the next char. (like 0 or maybe 1 or 4 for some encodings)
// We're done processing this buffer only if completed returns true.
//
// Might consider checking Max...Count to avoid the extra counting step.
//
// Note that if all of the input bytes are not consumed, then we'll do a /2, which means
// that its likely that we didn't consume as many bytes as we could have. For some
// applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream)
[System.Runtime.InteropServices.ComVisible(false)]
public virtual void Convert(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
// Validate parameters
if (bytes == null || chars == null)
throw new ArgumentNullException((bytes == null ? nameof(bytes) : nameof(chars)),
Environment.GetResourceString("ArgumentNull_Array"));
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
Contract.EndContractBlock();
bytesUsed = byteCount;
// Its easy to do if it won't overrun our buffer.
while (bytesUsed > 0)
{
if (GetCharCount(bytes, byteIndex, bytesUsed, flush) <= charCount)
{
charsUsed = GetChars(bytes, byteIndex, bytesUsed, chars, charIndex, flush);
completed = (bytesUsed == byteCount &&
(m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0));
return;
}
// Try again with 1/2 the count, won't flush then 'cause won't read it all
flush = false;
bytesUsed /= 2;
}
// Oops, we didn't have anything, we'll have to throw an overflow
throw new ArgumentException(Environment.GetResourceString("Argument_ConversionOverflow"));
}
// This is the version that uses *.
// We're done processing this buffer only if completed returns true.
//
// Might consider checking Max...Count to avoid the extra counting step.
//
// Note that if all of the input bytes are not consumed, then we'll do a /2, which means
// that its likely that we didn't consume as many bytes as we could have. For some
// applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream)
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe void Convert(byte* bytes, int byteCount,
char* chars, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
// Validate input parameters
if (chars == null || bytes == null)
throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes),
Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Get ready to do it
bytesUsed = byteCount;
// Its easy to do if it won't overrun our buffer.
while (bytesUsed > 0)
{
if (GetCharCount(bytes, bytesUsed, flush) <= charCount)
{
charsUsed = GetChars(bytes, bytesUsed, chars, charCount, flush);
completed = (bytesUsed == byteCount &&
(m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0));
return;
}
// Try again with 1/2 the count, won't flush then 'cause won't read it all
flush = false;
bytesUsed /= 2;
}
// Oops, we didn't have anything, we'll have to throw an overflow
throw new ArgumentException(Environment.GetResourceString("Argument_ConversionOverflow"));
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web;
using System.Xml;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.web;
using umbraco.DataLayer;
using umbraco.presentation.nodeFactory;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Profiling;
using Umbraco.Core.Scoping;
using Umbraco.Web;
using Umbraco.Web.PublishedCache.XmlPublishedCache;
using Umbraco.Web.Scheduling;
using File = System.IO.File;
using Node = umbraco.NodeFactory.Node;
namespace umbraco
{
/// <summary>
/// Represents the Xml storage for the Xml published cache.
/// </summary>
public class content
{
private readonly IScopeProviderInternal _scopeProvider = (IScopeProviderInternal) ApplicationContext.Current.ScopeProvider;
private XmlCacheFilePersister _persisterTask;
private volatile bool _released;
#region Constructors
private content()
{
if (SyncToXmlFile)
{
var logger = LoggerResolver.HasCurrent ? LoggerResolver.Current.Logger : new DebugDiagnosticsLogger();
var profingLogger = new ProfilingLogger(
logger,
ProfilerResolver.HasCurrent ? ProfilerResolver.Current.Profiler : new LogProfiler(logger));
// prepare the persister task
// there's always be one task keeping a ref to the runner
// so it's safe to just create it as a local var here
var runner = new BackgroundTaskRunner<XmlCacheFilePersister>("XmlCacheFilePersister", new BackgroundTaskRunnerOptions
{
LongRunning = true,
KeepAlive = true,
Hosted = false // main domain will take care of stopping the runner (see below)
}, logger);
// create (and add to runner)
_persisterTask = new XmlCacheFilePersister(runner, this, profingLogger);
var registered = ApplicationContext.Current.MainDom.Register(
null,
() =>
{
// once released, the cache still works but does not write to file anymore,
// which is OK with database server messenger but will cause data loss with
// another messenger...
runner.Shutdown(false, true); // wait until flushed
_released = true;
});
// failed to become the main domain, we will never use the file
if (registered == false)
runner.Shutdown(false, true);
_released = (registered == false);
}
// initialize content - populate the cache
using (var safeXml = GetSafeXmlWriter())
{
bool registerXmlChange;
// if we don't use the file then LoadXmlLocked will not even
// read from the file and will go straight to database
LoadXmlLocked(safeXml, out registerXmlChange);
// if we use the file and registerXmlChange is true this will
// write to file, else it will not
safeXml.AcceptChanges(registerXmlChange);
}
}
#endregion
#region Singleton
private static readonly Lazy<content> LazyInstance = new Lazy<content>(() => new content());
public static content Instance
{
get
{
return LazyInstance.Value;
}
}
#endregion
#region Legacy & Stuff
// sync database access
// (not refactoring that part at the moment)
private static readonly object DbReadSyncLock = new object();
internal const string XmlContextContentItemKey = "UmbracoXmlContextContent";
private static string _umbracoXmlDiskCacheFileName = string.Empty;
// internal for SafeXmlReaderWriter
internal volatile XmlDocument _xmlContent;
/// <summary>
/// Gets the path of the umbraco XML disk cache file.
/// </summary>
/// <value>The name of the umbraco XML disk cache file.</value>
public static string GetUmbracoXmlDiskFileName()
{
if (string.IsNullOrEmpty(_umbracoXmlDiskCacheFileName))
{
_umbracoXmlDiskCacheFileName = IOHelper.MapPath(SystemFiles.ContentCacheXml);
}
return _umbracoXmlDiskCacheFileName;
}
[Obsolete("Use the safer static GetUmbracoXmlDiskFileName() method instead to retrieve this value")]
public string UmbracoXmlDiskCacheFileName
{
get { return GetUmbracoXmlDiskFileName(); }
set { _umbracoXmlDiskCacheFileName = value; }
}
//NOTE: We CANNOT use this for a double check lock because it is a property, not a field and to do double
// check locking in c# you MUST have a volatile field. Even thoug this wraps a volatile field it will still
// not work as expected for a double check lock because properties are treated differently in the clr.
public virtual bool isInitializing
{
get
{
// ok to access _xmlContent here
return _xmlContent == null;
}
}
/// <summary>
/// Unused, please do not use
/// </summary>
[Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)]
protected static ISqlHelper SqlHelper
{
get { return Application.SqlHelper; }
}
#endregion
#region Public Methods
[Obsolete("This is no longer used and will be removed in future versions, if you use this method it will not refresh 'async' it will perform the refresh on the current thread which is how it should be doing it")]
public virtual void RefreshContentFromDatabaseAsync()
{
RefreshContentFromDatabase();
}
/// <summary>
/// Load content from database and replaces active content when done.
/// </summary>
public virtual void RefreshContentFromDatabase()
{
var e = new RefreshContentEventArgs();
FireBeforeRefreshContent(e);
if (e.Cancel) return;
using (var safeXml = GetSafeXmlWriter())
{
safeXml.Xml = LoadContentFromDatabase();
safeXml.AcceptChanges();
}
}
internal static bool TestingUpdateSitemapProvider = true;
/// <summary>
/// Used by all overloaded publish methods to do the actual "noderepresentation to xml"
/// </summary>
/// <param name="d"></param>
/// <param name="xmlContentCopy"></param>
/// <param name="updateSitemapProvider"></param>
public static XmlDocument PublishNodeDo(Document d, XmlDocument xmlContentCopy, bool updateSitemapProvider)
{
updateSitemapProvider &= TestingUpdateSitemapProvider;
// check if document *is* published, it could be unpublished by an event
if (d.Published)
{
var parentId = d.Level == 1 ? -1 : d.ParentId;
// fix sortOrder - see note in UpdateSortOrder
var node = GetPreviewOrPublishedNode(d, xmlContentCopy, false);
var attr = ((XmlElement)node).GetAttributeNode("sortOrder");
attr.Value = d.sortOrder.ToString();
xmlContentCopy = GetAddOrUpdateXmlNode(xmlContentCopy, d.Id, d.Level, parentId, node);
// update sitemapprovider
if (updateSitemapProvider && SiteMap.Provider is UmbracoSiteMapProvider)
{
try
{
var prov = (UmbracoSiteMapProvider)SiteMap.Provider;
var n = new Node(d.Id, true);
if (string.IsNullOrEmpty(n.Url) == false && n.Url != "/#")
{
prov.UpdateNode(n);
}
else
{
LogHelper.Debug<content>(string.Format("Can't update Sitemap Provider due to empty Url in node id: {0}", d.Id));
}
}
catch (Exception ee)
{
LogHelper.Error<content>(string.Format("Error adding node to Sitemap Provider in PublishNodeDo(): {0}", d.Id), ee);
}
}
}
return xmlContentCopy;
}
private static XmlNode GetPreviewOrPublishedNode(Document d, XmlDocument xmlContentCopy, bool isPreview)
{
if (isPreview)
{
return d.ToPreviewXml(xmlContentCopy);
}
else
{
return d.ToXml(xmlContentCopy, false);
}
}
/// <summary>
/// Sorts the documents.
/// </summary>
/// <param name="parentId">The parent node identifier.</param>
public void SortNodes(int parentId)
{
using (var safeXml = GetSafeXmlWriter())
{
var parentNode = parentId == -1
? safeXml.Xml.DocumentElement
: safeXml.Xml.GetElementById(parentId.ToString(CultureInfo.InvariantCulture));
if (parentNode == null) return;
var sorted = XmlHelper.SortNodesIfNeeded(
parentNode,
ChildNodesXPath,
x => x.AttributeValue<int>("sortOrder"));
if (sorted == false) return;
safeXml.AcceptChanges();
}
}
/// <summary>
/// Updates the document cache.
/// </summary>
/// <param name="pageId">The page id.</param>
public virtual void UpdateDocumentCache(int pageId)
{
var d = new Document(pageId);
UpdateDocumentCache(d);
}
/// <summary>
/// Updates the document cache.
/// </summary>
/// <param name="d">The d.</param>
public virtual void UpdateDocumentCache(Document d)
{
var e = new DocumentCacheEventArgs();
FireBeforeUpdateDocumentCache(d, e);
if (e.Cancel) return;
// lock the xml cache so no other thread can write to it at the same time
// note that some threads could read from it while we hold the lock, though
using (var safeXml = GetSafeXmlWriter())
{
safeXml.Xml = PublishNodeDo(d, safeXml.Xml, true);
safeXml.AcceptChanges();
}
var cachedFieldKeyStart = string.Format("{0}{1}_", CacheKeys.ContentItemCacheKey, d.Id);
ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheByKeySearch(cachedFieldKeyStart);
FireAfterUpdateDocumentCache(d, e);
}
internal virtual void UpdateSortOrder(int contentId)
{
var content = ApplicationContext.Current.Services.ContentService.GetById(contentId);
if (content == null) return;
UpdateSortOrder(content);
}
internal virtual void UpdateSortOrder(IContent c)
{
if (c == null) throw new ArgumentNullException("c");
// the XML in database is updated only when content is published, and then
// it contains the sortOrder value at the time the XML was generated. when
// a document with unpublished changes is sorted, then it is simply saved
// (see ContentService) and so the sortOrder has changed but the XML has
// not been updated accordingly.
// this updates the published cache to take care of the situation
// without ContentService having to ... what exactly?
// no need to do it if
// - the content is published without unpublished changes (XML will be re-gen anyways)
// - the content has no published version (not in XML)
// - the sort order has not changed
// note that
// - if it is a new entity is has not published version
// - if Published is dirty and false it's getting unpublished and has no published version
//
if (c.Published) return;
if (c.HasPublishedVersion == false) return;
if (c.WasPropertyDirty("SortOrder") == false) return;
using (var safeXml = GetSafeXmlWriter())
{
//TODO: This can be null: safeXml.Xml!!!!
var node = safeXml.Xml.GetElementById(c.Id.ToString(CultureInfo.InvariantCulture));
if (node == null) return;
var attr = node.GetAttributeNode("sortOrder");
if (attr == null) return;
var sortOrder = c.SortOrder.ToString(CultureInfo.InvariantCulture);
if (attr.Value == sortOrder) return;
// only if node was actually modified
attr.Value = sortOrder;
safeXml.AcceptChanges();
}
}
/// <summary>
/// Updates the document cache for multiple documents
/// </summary>
/// <param name="Documents">The documents.</param>
[Obsolete("This is not used and will be removed from the codebase in future versions")]
public virtual void UpdateDocumentCache(List<Document> Documents)
{
using (var safeXml = GetSafeXmlWriter())
{
foreach (var d in Documents)
{
safeXml.Xml = PublishNodeDo(d, safeXml.Xml, true);
}
safeXml.AcceptChanges();
}
}
[Obsolete("Method obsolete in version 4.1 and later, please use UpdateDocumentCache", true)]
public virtual void UpdateDocumentCacheAsync(int documentId)
{
UpdateDocumentCache(documentId);
}
[Obsolete("Method obsolete in version 4.1 and later, please use ClearDocumentCache", true)]
public virtual void ClearDocumentCacheAsync(int documentId)
{
ClearDocumentCache(documentId);
}
public virtual void ClearDocumentCache(int documentId)
{
ClearDocumentCache(documentId, true);
}
internal virtual void ClearDocumentCache(int documentId, bool removeDbXmlEntry)
{
// Get the document
Document d;
try
{
d = new Document(documentId);
}
catch
{
// if we need the document to remove it... this cannot be LB?!
// shortcut everything here
ClearDocumentXmlCache(documentId);
return;
}
ClearDocumentCache(d, removeDbXmlEntry);
}
/// <summary>
/// Clears the document cache and removes the document from the xml db cache.
/// This means the node gets unpublished from the website.
/// </summary>
/// <param name="doc">The document</param>
/// <param name="removeDbXmlEntry"></param>
internal void ClearDocumentCache(Document doc, bool removeDbXmlEntry)
{
var e = new DocumentCacheEventArgs();
FireBeforeClearDocumentCache(doc, e);
if (!e.Cancel)
{
//Hack: this is here purely for backwards compat if someone for some reason is using the
// ClearDocumentCache(int documentId) method and expecting it to remove the xml
if (removeDbXmlEntry)
{
// remove from xml db cache
doc.XmlRemoveFromDB();
}
// clear xml cache
ClearDocumentXmlCache(doc.Id);
//SD: changed to fire event BEFORE running the sitemap!! argh.
FireAfterClearDocumentCache(doc, e);
// update sitemapprovider
if (SiteMap.Provider is UmbracoSiteMapProvider)
{
var prov = (UmbracoSiteMapProvider)SiteMap.Provider;
prov.RemoveNode(doc.Id);
}
}
}
internal void ClearDocumentXmlCache(int id)
{
// We need to lock content cache here, because we cannot allow other threads
// making changes at the same time, they need to be queued
using (var safeXml = GetSafeXmlReader())
{
// Check if node present, before cloning
var x = safeXml.Xml.GetElementById(id.ToString());
if (x == null)
return;
if (safeXml.IsWriter == false)
safeXml.UpgradeToWriter();
// Find the document in the xml cache
x = safeXml.Xml.GetElementById(id.ToString());
if (x != null)
{
// The document already exists in cache, so repopulate it
x.ParentNode.RemoveChild(x);
safeXml.AcceptChanges();
}
}
}
/// <summary>
/// Unpublishes the node.
/// </summary>
/// <param name="documentId">The document id.</param>
[Obsolete("Please use: umbraco.content.ClearDocumentCache", true)]
public virtual void UnPublishNode(int documentId)
{
ClearDocumentCache(documentId);
}
#endregion
#region Protected & Private methods
// this is for tests exclusively until we have a proper accessor in v8
internal static Func<IDictionary> HttpContextItemsGetter { get; set; }
private static IDictionary HttpContextItems
{
get
{
return HttpContextItemsGetter == null
? (HttpContext.Current == null ? null : HttpContext.Current.Items)
: HttpContextItemsGetter();
}
}
// clear the current xml capture in http context
// used when applying changes from SafeXmlReaderWriter,
// to force a new capture - so that changes become
// visible for the current request
private void ClearContextCache()
{
var items = HttpContextItems;
if (items == null || items.Contains(XmlContextContentItemKey) == false) return;
items.Remove(XmlContextContentItemKey);
}
// replaces the current xml capture in http context
// used for temp changes from SafeXmlReaderWriter
// so the current request immediately sees changes
private void SetContextCache(XmlDocument xml)
{
var items = HttpContextItems;
if (items == null) return;
items[XmlContextContentItemKey] = xml;
}
/// <summary>
/// Load content from database
/// </summary>
private XmlDocument LoadContentFromDatabase()
{
try
{
LogHelper.Info<content>("Loading content from database...");
lock (DbReadSyncLock)
{
var xmlDoc = ApplicationContext.Current.Services.ContentService.BuildXmlCache();
LogHelper.Debug<content>("Done republishing Xml Index");
return xmlDoc;
}
}
catch (Exception ee)
{
LogHelper.Error<content>("Error Republishing", ee);
}
// An error of some sort must have stopped us from successfully generating
// the content tree, so lets return null signifying there is no content available
return null;
}
[Obsolete("This method should not be used and does nothing, xml file persistence is done in a queue using a BackgroundTaskRunner")]
public void PersistXmlToFile()
{
}
internal DateTime GetCacheFileUpdateTime()
{
//TODO: Should there be a try/catch here in case the file is being written to while this is trying to be executed?
if (File.Exists(GetUmbracoXmlDiskFileName()))
{
return new FileInfo(GetUmbracoXmlDiskFileName()).LastWriteTimeUtc;
}
return DateTime.MinValue;
}
#endregion
#region Configuration
// gathering configuration options here to document what they mean
private readonly bool _xmlFileEnabled = true;
// whether the disk cache is enabled
private bool XmlFileEnabled
{
get { return _xmlFileEnabled && UmbracoConfig.For.UmbracoSettings().Content.XmlCacheEnabled; }
}
// whether the disk cache is enabled and to update the disk cache when xml changes
private bool SyncToXmlFile
{
get { return XmlFileEnabled && UmbracoConfig.For.UmbracoSettings().Content.ContinouslyUpdateXmlDiskCache; }
}
// whether the disk cache is enabled and to reload from disk cache if it changes
private bool SyncFromXmlFile
{
get { return XmlFileEnabled && UmbracoConfig.For.UmbracoSettings().Content.XmlContentCheckForDiskChanges; }
}
// whether to use the legacy schema
private static bool UseLegacySchema
{
get { return UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema; }
}
#endregion
#region Xml
// internal for SafeXmlReaderWriter
internal readonly AsyncLock _xmlLock = new AsyncLock(); // protects _xml
/// <remarks>
/// Get content. First call to this property will initialize xmldoc
/// subsequent calls will be blocked until initialization is done
/// Further we cache (in context) xmlContent for each request to ensure that
/// we always have the same XmlDoc throughout the whole request.
/// </remarks>
public virtual XmlDocument XmlContent
{
get
{
// if there's a current enlisted reader/writer, use its xml
var safeXml = SafeXmlReaderWriter.Get(_scopeProvider);
if (safeXml != null) return safeXml.Xml;
var items = HttpContextItems;
if (items == null)
return XmlContentInternal;
// capture or return the current xml in http context
// so that it remains stable over the entire request
var content = (XmlDocument) items[XmlContextContentItemKey];
if (content == null)
{
content = XmlContentInternal;
items[XmlContextContentItemKey] = content;
}
return content;
}
}
[Obsolete("Please use: content.Instance.XmlContent")]
public static XmlDocument xmlContent
{
get { return Instance.XmlContent; }
}
// to be used by content.Instance
// ok to access _xmlContent here - just capturing
protected internal virtual XmlDocument XmlContentInternal
{
get
{
ReloadXmlFromFileIfChanged();
return _xmlContent;
}
}
// assumes xml lock
// ok to access _xmlContent here since this is called from the safe reader/writer
// internal for SafeXmlReaderWriter
internal void SetXmlLocked(XmlDocument xml, bool registerXmlChange)
{
// this is the ONLY place where we write to _xmlContent
_xmlContent = xml;
if (registerXmlChange == false || SyncToXmlFile == false)
return;
//_lastXmlChange = DateTime.UtcNow;
_persisterTask = _persisterTask.Touch(); // _persisterTask != null because SyncToXmlFile == true
}
private static XmlDocument EnsureSchema(string contentTypeAlias, XmlDocument xml)
{
string subset = null;
// get current doctype
var n = xml.FirstChild;
while (n.NodeType != XmlNodeType.DocumentType && n.NextSibling != null)
n = n.NextSibling;
if (n.NodeType == XmlNodeType.DocumentType)
subset = ((XmlDocumentType)n).InternalSubset;
// ensure it contains the content type
if (subset != null && subset.Contains(string.Format("<!ATTLIST {0} id ID #REQUIRED>", contentTypeAlias)))
return xml;
// alas, that does not work, replacing a doctype is ignored and GetElementById fails
//
//// remove current doctype, set new doctype
//xml.RemoveChild(n);
//subset = string.Format("<!ELEMENT {1} ANY>{0}<!ATTLIST {1} id ID #REQUIRED>{0}{2}", Environment.NewLine, contentTypeAlias, subset);
//var doctype = xml.CreateDocumentType("root", null, null, subset);
//xml.InsertAfter(doctype, xml.FirstChild);
var xml2 = new XmlDocument();
subset = string.Format("<!ELEMENT {1} ANY>{0}<!ATTLIST {1} id ID #REQUIRED>{0}{2}", Environment.NewLine, contentTypeAlias, subset);
var doctype = xml2.CreateDocumentType("root", null, null, subset);
xml2.AppendChild(doctype);
xml2.AppendChild(xml2.ImportNode(xml.DocumentElement, true));
return xml2;
}
// try to load from file, otherwise database
// assumes xml lock (file is always locked)
private void LoadXmlLocked(SafeXmlReaderWriter safeXml, out bool registerXmlChange)
{
LogHelper.Debug<content>("Loading Xml...");
// try to get it from the file
if (XmlFileEnabled && (safeXml.Xml = LoadXmlFromFile()) != null)
{
registerXmlChange = false; // loaded from disk, do NOT write back to disk!
return;
}
// get it from the database, and register
safeXml.Xml = LoadContentFromDatabase();
registerXmlChange = true;
}
// NOTE
// - this is NOT a reader/writer lock and each lock is exclusive
// - these locks are NOT reentrant / recursive
// gets a locked safe read access to the main xml
private SafeXmlReaderWriter GetSafeXmlReader()
{
return SafeXmlReaderWriter.Get(_scopeProvider, _xmlLock, _xmlContent,
SetContextCache,
(xml, registerXmlChange) =>
{
SetXmlLocked(xml, registerXmlChange);
ClearContextCache();
}, false);
}
// gets a locked safe write access to the main xml (cloned)
private SafeXmlReaderWriter GetSafeXmlWriter()
{
return SafeXmlReaderWriter.Get(_scopeProvider, _xmlLock, _xmlContent,
SetContextCache,
(xml, registerXmlChange) =>
{
SetXmlLocked(xml, registerXmlChange);
ClearContextCache();
}, true);
}
private static string ChildNodesXPath
{
get
{
return UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema
? "./node"
: "./* [@id]";
}
}
private static string DataNodesXPath
{
get
{
return UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema
? "./data"
: "./* [not(@id)]";
}
}
#endregion
#region File
private readonly string _xmlFileName = IOHelper.MapPath(SystemFiles.ContentCacheXml);
private DateTime _lastFileRead; // last time the file was read
private DateTime _nextFileCheck; // last time we checked whether the file was changed
// not used - just try to read the file
//private bool XmlFileExists
//{
// get
// {
// // check that the file exists and has content (is not empty)
// var fileInfo = new FileInfo(_xmlFileName);
// return fileInfo.Exists && fileInfo.Length > 0;
// }
//}
private DateTime XmlFileLastWriteTime
{
get
{
var fileInfo = new FileInfo(_xmlFileName);
return fileInfo.Exists ? fileInfo.LastWriteTimeUtc : DateTime.MinValue;
}
}
// invoked by XmlCacheFilePersister ONLY and that one manages the MainDom, ie it
// will NOT try to save once the current app domain is not the main domain anymore
// (no need to test _released)
internal void SaveXmlToFile()
{
LogHelper.Info<content>("Save Xml to file...");
try
{
// ok to access _xmlContent here - capture (atomic + volatile), immutable anyway
var xml = _xmlContent;
if (xml == null) return;
// delete existing file, if any
DeleteXmlFile();
// ensure cache directory exists
var directoryName = Path.GetDirectoryName(_xmlFileName);
if (directoryName == null)
throw new Exception(string.Format("Invalid XmlFileName \"{0}\".", _xmlFileName));
if (File.Exists(_xmlFileName) == false && Directory.Exists(directoryName) == false)
Directory.CreateDirectory(directoryName);
// save
using (var fs = new FileStream(_xmlFileName, FileMode.Create, FileAccess.Write, FileShare.Read))
{
SaveXmlToStream(xml, fs);
}
LogHelper.Info<content>("Saved Xml to file.");
}
catch (Exception e)
{
// if something goes wrong remove the file
try
{
DeleteXmlFile();
}
catch
{
// don't make it worse: could be that we failed to write because we cannot
// access the file, in which case we won't be able to delete it either
}
LogHelper.Error<content>("Failed to save Xml to file.", e);
}
}
private void SaveXmlToStream(XmlDocument xml, Stream writeStream)
{
// using that one method because we want to have proper indent
// and in addition, writing async is never fully async because
// althouth the writer is async, xml.WriteTo() will not async
// that one almost works but... "The elements are indented as long as the element
// does not contain mixed content. Once the WriteString or WriteWhitespace method
// is called to write out a mixed element content, the XmlWriter stops indenting.
// The indenting resumes once the mixed content element is closed." - says MSDN
// about XmlWriterSettings.Indent
// so ImportContent must also make sure of ignoring whitespaces!
if (writeStream.CanSeek)
{
writeStream.Position = 0;
}
using (var xmlWriter = XmlWriter.Create(writeStream, new XmlWriterSettings
{
Indent = true,
Encoding = Encoding.UTF8,
//OmitXmlDeclaration = true
}))
{
//xmlWriter.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");
xml.WriteTo(xmlWriter); // already contains the xml declaration
}
}
private XmlDocument LoadXmlFromFile()
{
// do NOT try to load if we are not the main domain anymore
if (_released) return null;
LogHelper.Info<content>("Load Xml from file...");
try
{
var xml = new XmlDocument();
using (var fs = new FileStream(_xmlFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
xml.Load(fs);
}
_lastFileRead = DateTime.UtcNow;
LogHelper.Info<content>("Loaded Xml from file.");
return xml;
}
catch (FileNotFoundException)
{
LogHelper.Warn<content>("Failed to load Xml, file does not exist.");
return null;
}
catch (Exception e)
{
LogHelper.Error<content>("Failed to load Xml from file.", e);
try
{
DeleteXmlFile();
}
catch
{
// don't make it worse: could be that we failed to read because we cannot
// access the file, in which case we won't be able to delete it either
}
return null;
}
}
private void DeleteXmlFile()
{
if (File.Exists(_xmlFileName) == false) return;
File.SetAttributes(_xmlFileName, FileAttributes.Normal);
File.Delete(_xmlFileName);
}
private void ReloadXmlFromFileIfChanged()
{
if (SyncFromXmlFile == false) return;
var now = DateTime.UtcNow;
if (now < _nextFileCheck) return;
// time to check
_nextFileCheck = now.AddSeconds(1); // check every 1s
if (XmlFileLastWriteTime <= _lastFileRead) return;
LogHelper.Debug<content>("Xml file change detected, reloading.");
// time to read
using (var safeXml = GetSafeXmlWriter())
{
bool registerXmlChange;
LoadXmlLocked(safeXml, out registerXmlChange); // updates _lastFileRead
safeXml.AcceptChanges(registerXmlChange);
}
}
#endregion
#region Manage change
//TODO remove as soon as we can break backward compatibility
[Obsolete("Use GetAddOrUpdateXmlNode which returns an updated Xml document.", false)]
public static void AddOrUpdateXmlNode(XmlDocument xml, int id, int level, int parentId, XmlNode docNode)
{
GetAddOrUpdateXmlNode(xml, id, level, parentId, docNode);
}
// adds or updates a node (docNode) into a cache (xml)
public static XmlDocument GetAddOrUpdateXmlNode(XmlDocument xml, int id, int level, int parentId, XmlNode docNode)
{
// sanity checks
if (id != docNode.AttributeValue<int>("id"))
throw new ArgumentException("Values of id and docNode/@id are different.");
if (parentId != docNode.AttributeValue<int>("parentID"))
throw new ArgumentException("Values of parentId and docNode/@parentID are different.");
// find the document in the cache
XmlNode currentNode = xml.GetElementById(id.ToInvariantString());
// if the document is not there already then it's a new document
// we must make sure that its document type exists in the schema
if (currentNode == null && UseLegacySchema == false)
{
var xml2 = EnsureSchema(docNode.Name, xml);
if (ReferenceEquals(xml, xml2) == false)
docNode = xml2.ImportNode(docNode, true);
xml = xml2;
}
// find the parent
XmlNode parentNode = level == 1
? xml.DocumentElement
: xml.GetElementById(parentId.ToInvariantString());
// no parent = cannot do anything
if (parentNode == null)
return xml;
// insert/move the node under the parent
if (currentNode == null)
{
// document not there, new node, append
currentNode = docNode;
parentNode.AppendChild(currentNode);
}
else
{
// document found... we could just copy the currentNode children nodes over under
// docNode, then remove currentNode and insert docNode... the code below tries to
// be clever and faster, though only benchmarking could tell whether it's worth the
// pain...
// first copy current parent ID - so we can compare with target parent
var moving = currentNode.AttributeValue<int>("parentID") != parentId;
if (docNode.Name == currentNode.Name)
{
// name has not changed, safe to just update the current node
// by transfering values eg copying the attributes, and importing the data elements
TransferValuesFromDocumentXmlToPublishedXml(docNode, currentNode);
// if moving, move the node to the new parent
// else it's already under the right parent
// (but maybe the sort order has been updated)
if (moving)
parentNode.AppendChild(currentNode); // remove then append to parentNode
}
else
{
// name has changed, must use docNode (with new name)
// move children nodes from currentNode to docNode (already has properties)
var children = currentNode.SelectNodes(ChildNodesXPath);
if (children == null) throw new Exception("oops");
foreach (XmlNode child in children)
docNode.AppendChild(child); // remove then append to docNode
// and put docNode in the right place - if parent has not changed, then
// just replace, else remove currentNode and insert docNode under the right parent
// (but maybe not at the right position due to sort order)
if (moving)
{
if (currentNode.ParentNode == null) throw new Exception("oops");
currentNode.ParentNode.RemoveChild(currentNode);
parentNode.AppendChild(docNode);
}
else
{
// replacing might screw the sort order
parentNode.ReplaceChild(docNode, currentNode);
}
currentNode = docNode;
}
}
// if the nodes are not ordered, must sort
// (see U4-509 + has to work with ReplaceChild too)
//XmlHelper.SortNodesIfNeeded(parentNode, childNodesXPath, x => x.AttributeValue<int>("sortOrder"));
// but...
// if we assume that nodes are always correctly sorted
// then we just need to ensure that currentNode is at the right position.
// should be faster that moving all the nodes around.
XmlHelper.SortNode(parentNode, ChildNodesXPath, currentNode, x => x.AttributeValue<int>("sortOrder"));
return xml;
}
private static void TransferValuesFromDocumentXmlToPublishedXml(XmlNode documentNode, XmlNode publishedNode)
{
// remove all attributes from the published node
if (publishedNode.Attributes == null) throw new Exception("oops");
publishedNode.Attributes.RemoveAll();
// remove all data nodes from the published node
//TODO: This could be faster, might as well just iterate all children and filter
// instead of selecting matching children (i.e. iterating all) and then iterating the
// filtered items to remove, this also allocates more memory to store the list of children.
// Below we also then do another filtering of child nodes, if we just iterate all children we
// can perform both functions more efficiently
var dataNodes = publishedNode.SelectNodes(DataNodesXPath);
if (dataNodes == null) throw new Exception("oops");
foreach (XmlNode n in dataNodes)
publishedNode.RemoveChild(n);
// append all attributes from the document node to the published node
if (documentNode.Attributes == null) throw new Exception("oops");
foreach (XmlAttribute att in documentNode.Attributes)
((XmlElement)publishedNode).SetAttribute(att.Name, att.Value);
// find the first child node, if any
var childNodes = publishedNode.SelectNodes(ChildNodesXPath);
if (childNodes == null) throw new Exception("oops");
var firstChildNode = childNodes.Count == 0 ? null : childNodes[0];
// append all data nodes from the document node to the published node
dataNodes = documentNode.SelectNodes(DataNodesXPath);
if (dataNodes == null) throw new Exception("oops");
foreach (XmlNode n in dataNodes)
{
if (publishedNode.OwnerDocument == null) throw new Exception("oops");
var imported = publishedNode.OwnerDocument.ImportNode(n, true);
if (firstChildNode == null)
publishedNode.AppendChild(imported);
else
publishedNode.InsertBefore(imported, firstChildNode);
}
}
#endregion
#region Events
/// <summary>
/// Occurs when [after loading the xml string from the database].
/// </summary>
public delegate void ContentCacheDatabaseLoadXmlStringEventHandler(
ref string xml, ContentCacheLoadNodeEventArgs e);
/// <summary>
/// Occurs when [after loading the xml string from the database and creating the xml node].
/// </summary>
public delegate void ContentCacheLoadNodeEventHandler(XmlNode xmlNode, ContentCacheLoadNodeEventArgs e);
public delegate void DocumentCacheEventHandler(Document sender, DocumentCacheEventArgs e);
public delegate void RefreshContentEventHandler(Document sender, RefreshContentEventArgs e);
/// <summary>
/// Occurs when [before document cache update].
/// </summary>
public static event DocumentCacheEventHandler BeforeUpdateDocumentCache;
/// <summary>
/// Fires the before document cache.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="umbraco.cms.businesslogic.DocumentCacheEventArgs"/> instance containing the event data.</param>
protected virtual void FireBeforeUpdateDocumentCache(Document sender, DocumentCacheEventArgs e)
{
if (BeforeUpdateDocumentCache != null)
{
BeforeUpdateDocumentCache(sender, e);
}
}
/// <summary>
/// Occurs when [after document cache update].
/// </summary>
public static event DocumentCacheEventHandler AfterUpdateDocumentCache;
/// <summary>
/// Fires after document cache updater.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="umbraco.cms.businesslogic.DocumentCacheEventArgs"/> instance containing the event data.</param>
protected virtual void FireAfterUpdateDocumentCache(Document sender, DocumentCacheEventArgs e)
{
if (AfterUpdateDocumentCache != null)
{
AfterUpdateDocumentCache(sender, e);
}
}
/// <summary>
/// Occurs when [before document cache unpublish].
/// </summary>
public static event DocumentCacheEventHandler BeforeClearDocumentCache;
/// <summary>
/// Fires the before document cache unpublish.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="umbraco.cms.businesslogic.DocumentCacheEventArgs"/> instance containing the event data.</param>
protected virtual void FireBeforeClearDocumentCache(Document sender, DocumentCacheEventArgs e)
{
if (BeforeClearDocumentCache != null)
{
BeforeClearDocumentCache(sender, e);
}
}
public static event DocumentCacheEventHandler AfterClearDocumentCache;
/// <summary>
/// Fires the after document cache unpublish.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="umbraco.cms.businesslogic.DocumentCacheEventArgs"/> instance containing the event data.</param>
protected virtual void FireAfterClearDocumentCache(Document sender, DocumentCacheEventArgs e)
{
if (AfterClearDocumentCache != null)
{
AfterClearDocumentCache(sender, e);
}
}
/// <summary>
/// Occurs when [before refresh content].
/// </summary>
public static event RefreshContentEventHandler BeforeRefreshContent;
/// <summary>
/// Fires the content of the before refresh.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="umbraco.cms.businesslogic.RefreshContentEventArgs"/> instance containing the event data.</param>
protected virtual void FireBeforeRefreshContent(RefreshContentEventArgs e)
{
if (BeforeRefreshContent != null)
{
BeforeRefreshContent(null, e);
}
}
/// <summary>
/// Occurs when [after refresh content].
/// </summary>
public static event RefreshContentEventHandler AfterRefreshContent;
/// <summary>
/// Fires the content of the after refresh.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="umbraco.cms.businesslogic.RefreshContentEventArgs"/> instance containing the event data.</param>
protected virtual void FireAfterRefreshContent(RefreshContentEventArgs e)
{
if (AfterRefreshContent != null)
{
AfterRefreshContent(null, e);
}
}
[Obsolete("This is no used, do not use this for any reason")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static event ContentCacheDatabaseLoadXmlStringEventHandler AfterContentCacheDatabaseLoadXmlString;
/// <summary>
/// Occurs when [before when creating the document cache from database].
/// </summary>
public static event ContentCacheLoadNodeEventHandler BeforeContentCacheLoadNode;
/// <summary>
/// Fires the before when creating the document cache from database
/// </summary>
/// <param name="node">The sender.</param>
/// <param name="e">The <see cref="umbraco.cms.businesslogic.ContentCacheLoadNodeEventArgs"/> instance containing the event data.</param>
internal static void FireBeforeContentCacheLoadNode(XmlNode node, ContentCacheLoadNodeEventArgs e)
{
if (BeforeContentCacheLoadNode != null)
{
BeforeContentCacheLoadNode(node, e);
}
}
[Obsolete("This is no used, do not use this for any reason")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static event ContentCacheLoadNodeEventHandler AfterContentCacheLoadNodeFromDatabase;
/// <summary>
/// Occurs when [before a publish action updates the content cache].
/// </summary>
public static event ContentCacheLoadNodeEventHandler BeforePublishNodeToContentCache;
/// <summary>
/// Fires the before a publish action updates the content cache
/// </summary>
/// <param name="node">The sender.</param>
/// <param name="e">The <see cref="umbraco.cms.businesslogic.ContentCacheLoadNodeEventArgs"/> instance containing the event data.</param>
public static void FireBeforePublishNodeToContentCache(XmlNode node, ContentCacheLoadNodeEventArgs e)
{
if (BeforePublishNodeToContentCache != null)
{
BeforePublishNodeToContentCache(node, e);
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using CoreXml.Test.XLinq;
using Microsoft.Test.ModuleCore;
namespace XLinqTests
{
public class XAttributeEnumRemove : XLinqTestCase
{
#region Fields
private EventsHelper _eHelper;
private bool _runWithEvents;
#endregion
#region Public Methods and Operators
public override void AddChildren()
{
AddChild(new TestVariation(IdAttrsMultipleDocs) { Attribute = new VariationAttribute("attributes from multiple elements") { Priority = 1 } });
AddChild(new TestVariation(IdAttrs) { Attribute = new VariationAttribute("attributes from multiple documents") { Priority = 1 } });
AddChild(new TestVariation(OneElementNonNS) { Attribute = new VariationAttribute("All non-namespace attributes in one element") { Priority = 1 } });
AddChild(new TestVariation(OneElementNS) { Attribute = new VariationAttribute("All namespace attributes in one element") { Priority = 1 } });
AddChild(new TestVariation(OneElement) { Attribute = new VariationAttribute("All attributes in one element") { Priority = 0 } });
AddChild(new TestVariation(OneDocument) { Attribute = new VariationAttribute("All attributes in one document") { Priority = 1 } });
AddChild(new TestVariation(IdAttrsNulls) { Attribute = new VariationAttribute("All attributes in one document + nulls") { Priority = 1 } });
AddChild(new TestVariation(DuplicateAttributeInside) { Attribute = new VariationAttribute("Duplicate attribute in sequence") { Priority = 3 } });
AddChild(new TestVariation(EmptySequence) { Attribute = new VariationAttribute("Empty sequence") { Priority = 1 } });
}
// From the same element
// - all attributes
// - some attributes
// From different elements - the same document
// From different documents
// Enumerable + nulls
//[Variation(Priority = 1, Desc = "attributes from multiple elements")]
//[Variation(Priority = 3, Desc = "Duplicate attribute in sequence")]
public void DuplicateAttributeInside()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D id='x' datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Root.Attributes().Concat(doc.Root.Attributes());
try
{
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count();
}
allAttributes.Remove(); // should throw because of snapshot logic
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
TestLog.Compare(false, "exception expected here");
}
catch (InvalidOperationException)
{
}
}
//[Variation(Priority = 1, Desc = "Empty sequence")]
public void EmptySequence()
{
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D id='x' datrt='dat'/></A>");
IEnumerable<XAttribute> noAttributes = doc.Descendants().Where(x => !x.HasAttributes).Attributes();
TestLog.Compare(noAttributes.IsEmpty(), "should be empty sequence");
var ms1 = new MemoryStream();
doc.Save(new StreamWriter(ms1));
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
}
noAttributes.Remove();
if (_runWithEvents)
{
_eHelper.Verify(0);
}
var ms2 = new MemoryStream();
doc.Save(new StreamWriter(ms2));
TestLog.Compare(ms1.ToArray().SequenceEqual(ms2.ToArray()), "Documents different");
}
public void IdAttrs()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D id='x' datrt='dat'/></A>");
XElement e = XElement.Parse(@"<X id='z'><Z xmlns='a' id='z'/></X>");
IEnumerable<XAttribute> allAttributes = doc.Descendants().Attributes().Concat(e.Descendants().Attributes()).Where(a => a.Name == "id");
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = doc.Descendants().Attributes().Where(a => a.Name == "id").Count();
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
}
public void IdAttrsMultipleDocs()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D id='x' datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Descendants().Attributes().Where(a => a.Name == "id");
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count();
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
}
public void IdAttrsNulls()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D id='x' datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Descendants().Attributes().Where(a => a.Name == "id").InsertNulls(1);
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
// null attribute will not cause the remove event.
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count() / 2;
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
}
public void OneDocument()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Descendants().Attributes();
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count();
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
}
public void OneElement()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Root.Element("{nbs}B").Attributes();
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count();
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
}
public void OneElementNS()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Root.Element("{nbs}B").Attributes().Where(a => a.IsNamespaceDeclaration);
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count();
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
VerifyDeleteAttributes(allAttributes);
}
public void OneElementNonNS()
{
int count = 0;
_runWithEvents = (bool)Params[0];
XDocument doc = XDocument.Parse(@"<A id='a' xmlns:p1='nsp1'><B id='b' xmlns='nbs' xmlns:p='nsp' p:x='xx'>text</B><C/><p1:D datrt='dat'/></A>");
IEnumerable<XAttribute> allAttributes = doc.Root.Element("{nbs}B").Attributes().Where(a => !a.IsNamespaceDeclaration);
if (_runWithEvents)
{
_eHelper = new EventsHelper(doc);
count = allAttributes.IsEmpty() ? 0 : allAttributes.Count();
}
VerifyDeleteAttributes(allAttributes);
if (_runWithEvents)
{
_eHelper.Verify(XObjectChange.Remove, count);
}
}
#endregion
#region Methods
private void VerifyDeleteAttributes(IEnumerable<XAttribute> allAttributes)
{
// specify enum + make copy of it
IEnumerable<XAttribute> copyAllAttributes = allAttributes.ToList();
// calculate parents + make copy
IEnumerable<XElement> parents = allAttributes.Select(a => a == null ? null : a.Parent).ToList();
// calculate the expected results for the parents of the processed elements
var expectedAttrsForParent = new Dictionary<XElement, List<ExpectedValue>>();
foreach (XElement p in parents)
{
if (p != null)
{
expectedAttrsForParent.TryAdd(p, p.Attributes().Except(copyAllAttributes.Where(x => x != null)).Select(a => new ExpectedValue(true, a)).ToList());
}
}
// enum.Remove ()
allAttributes.Remove();
// verify properties of the deleted attrs
TestLog.Compare(allAttributes.IsEmpty(), "There should be no attributes left");
IEnumerator<XAttribute> copyAttrib = copyAllAttributes.GetEnumerator();
IEnumerator<XElement> parentsEnum = parents.GetEnumerator();
// verify on parents: deleted elements should not be found
while (copyAttrib.MoveNext() && parentsEnum.MoveNext())
{
XAttribute a = copyAttrib.Current;
if (a != null)
{
XElement parent = parentsEnum.Current;
a.Verify();
parent.Verify();
TestLog.Compare(a.Parent, null, "Parent of deleted");
TestLog.Compare(a.NextAttribute, null, "NextAttribute of deleted");
TestLog.Compare(a.PreviousAttribute, null, "PreviousAttribute of deleted");
if (parent != null)
{
TestLog.Compare(parent.Attribute(a.Name), null, "Attribute lookup");
TestLog.Compare(parent.Attributes().Where(x => x.Name == a.Name).IsEmpty(), "Attributes node");
// Compare the rest of the elements
TestLog.Compare(expectedAttrsForParent[parent].EqualAllAttributes(parent.Attributes(), Helpers.MyAttributeComparer), "The rest of the attributes");
}
}
}
}
#endregion
// Type is CoreXml.Test.XLinq.FunctionalTests+TreeManipulationTests+XAttributeEnumRemove
// Test Case
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
using System.Text;
using System;
using System.Diagnostics.Contracts;
namespace System.Text
{
// An Encoder is used to encode a sequence of blocks of characters into
// a sequence of blocks of bytes. Following instantiation of an encoder,
// sequential blocks of characters are converted into blocks of bytes through
// calls to the GetBytes method. The encoder maintains state between the
// conversions, allowing it to correctly encode character sequences that span
// adjacent blocks.
//
// Instances of specific implementations of the Encoder abstract base
// class are typically obtained through calls to the GetEncoder method
// of Encoding objects.
//
[Serializable]
internal class EncoderNLS : Encoder, ISerializable
{
// Need a place for the last left over character, most of our encodings use this
internal char charLeftOver;
protected Encoding m_encoding;
[NonSerialized] protected bool m_mustFlush;
[NonSerialized] internal bool m_throwOnOverflow;
[NonSerialized] internal int m_charsUsed;
#region Serialization
// Constructor called by serialization. called during deserialization.
internal EncoderNLS(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException(
String.Format(
System.Globalization.CultureInfo.CurrentCulture,
SR.NotSupported_TypeCannotDeserialized, this.GetType()));
}
// ISerializable implementation. called during serialization.
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
SerializeEncoder(info);
info.AddValue("encoding", this.m_encoding);
info.AddValue("charLeftOver", this.charLeftOver);
info.SetType(typeof(Encoding.DefaultEncoder));
}
#endregion Serialization
internal EncoderNLS(Encoding encoding)
{
this.m_encoding = encoding;
this.m_fallback = this.m_encoding.EncoderFallback;
this.Reset();
}
// This one is used when deserializing (like UTF7Encoding.Encoder)
internal EncoderNLS()
{
this.m_encoding = null;
this.Reset();
}
public override void Reset()
{
this.charLeftOver = (char)0;
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
public override unsafe int GetByteCount(char[] chars, int index, int count, bool flush)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException(nameof(chars),
SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(chars),
SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
// Avoid empty input problem
if (chars.Length == 0)
chars = new char[1];
// Just call the pointer version
int result = -1;
fixed (char* pChars = &chars[0])
{
result = GetByteCount(pChars + index, count, flush);
}
return result;
}
public unsafe override int GetByteCount(char* chars, int count, bool flush)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException(nameof(chars),
SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
this.m_mustFlush = flush;
this.m_throwOnOverflow = true;
return m_encoding.GetByteCount(chars, count, this);
}
public override unsafe int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, bool flush)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars),
SR.ArgumentOutOfRange_IndexCountBuffer);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException(nameof(byteIndex),
SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
if (chars.Length == 0)
chars = new char[1];
int byteCount = bytes.Length - byteIndex;
if (bytes.Length == 0)
bytes = new byte[1];
// Just call pointer version
fixed (char* pChars = &chars[0])
fixed (byte* pBytes = &bytes[0])
// Remember that charCount is # to decode, not size of array.
return GetBytes(pChars + charIndex, charCount,
pBytes + byteIndex, byteCount, flush);
}
public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
this.m_mustFlush = flush;
this.m_throwOnOverflow = true;
return m_encoding.GetBytes(chars, charCount, bytes, byteCount, this);
}
// This method is used when your output buffer might not be large enough for the entire result.
// Just call the pointer version. (This gets bytes)
public override unsafe void Convert(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars),
SR.ArgumentOutOfRange_IndexCountBuffer);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes),
SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
// Avoid empty input problem
if (chars.Length == 0)
chars = new char[1];
if (bytes.Length == 0)
bytes = new byte[1];
// Just call the pointer version (can't do this for non-msft encoders)
fixed (char* pChars = &chars[0])
{
fixed (byte* pBytes = &bytes[0])
{
Convert(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush,
out charsUsed, out bytesUsed, out completed);
}
}
}
// This is the version that uses pointers. We call the base encoding worker function
// after setting our appropriate internal variables. This is getting bytes
public override unsafe void Convert(char* chars, int charCount,
byte* bytes, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
// Validate input parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
SR.ArgumentNull_Array);
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// We don't want to throw
this.m_mustFlush = flush;
this.m_throwOnOverflow = false;
this.m_charsUsed = 0;
// Do conversion
bytesUsed = this.m_encoding.GetBytes(chars, charCount, bytes, byteCount, this);
charsUsed = this.m_charsUsed;
// Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed
completed = (charsUsed == charCount) && (!flush || !this.HasState) &&
(m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0);
// Our data thingys are now full, we can return
}
public Encoding Encoding
{
get
{
return m_encoding;
}
}
public bool MustFlush
{
get
{
return m_mustFlush;
}
}
// Anything left in our encoder?
internal virtual bool HasState
{
get
{
return (this.charLeftOver != (char)0);
}
}
// Allow encoding to clear our must flush instead of throwing (in ThrowBytesOverflow)
internal void ClearMustFlush()
{
m_mustFlush = false;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Prism.Regions;
using Prism.Wpf.Tests.Mocks;
namespace Prism.Wpf.Tests.Regions
{
[TestClass]
public class RegionManagerFixture
{
[TestMethod]
public void CanAddRegion()
{
IRegion region1 = new MockPresentationRegion();
region1.Name = "MainRegion";
RegionManager regionManager = new RegionManager();
regionManager.Regions.Add(region1);
IRegion region2 = regionManager.Regions["MainRegion"];
Assert.AreSame(region1, region2);
}
[TestMethod]
[ExpectedException(typeof(KeyNotFoundException))]
public void ShouldFailIfRegionDoesntExists()
{
RegionManager regionManager = new RegionManager();
IRegion region = regionManager.Regions["nonExistentRegion"];
}
[TestMethod]
public void CanCheckTheExistenceOfARegion()
{
RegionManager regionManager = new RegionManager();
bool result = regionManager.Regions.ContainsRegionWithName("noRegion");
Assert.IsFalse(result);
IRegion region = new MockPresentationRegion();
region.Name = "noRegion";
regionManager.Regions.Add(region);
result = regionManager.Regions.ContainsRegionWithName("noRegion");
Assert.IsTrue(result);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void AddingMultipleRegionsWithSameNameThrowsArgumentException()
{
var regionManager = new RegionManager();
regionManager.Regions.Add(new MockPresentationRegion { Name = "region name" });
regionManager.Regions.Add(new MockPresentationRegion { Name = "region name" });
}
[TestMethod]
public void AddPassesItselfAsTheRegionManagerOfTheRegion()
{
var regionManager = new RegionManager();
var region = new MockPresentationRegion();
region.Name = "region";
regionManager.Regions.Add(region);
Assert.AreSame(regionManager, region.RegionManager);
}
[TestMethod]
public void CreateRegionManagerCreatesANewInstance()
{
var regionManager = new RegionManager();
var createdRegionManager = regionManager.CreateRegionManager();
Assert.IsNotNull(createdRegionManager);
Assert.IsInstanceOfType(createdRegionManager, typeof(RegionManager));
Assert.AreNotSame(regionManager, createdRegionManager);
}
[TestMethod]
public void CanRemoveRegion()
{
var regionManager = new RegionManager();
IRegion region = new MockPresentationRegion();
region.Name = "TestRegion";
regionManager.Regions.Add(region);
regionManager.Regions.Remove("TestRegion");
Assert.IsFalse(regionManager.Regions.ContainsRegionWithName("TestRegion"));
}
[TestMethod]
public void ShouldRemoveRegionManagerWhenRemoving()
{
var regionManager = new RegionManager();
var region = new MockPresentationRegion();
region.Name = "TestRegion";
regionManager.Regions.Add(region);
regionManager.Regions.Remove("TestRegion");
Assert.IsNull(region.RegionManager);
}
[TestMethod]
public void UpdatingRegionsGetsCalledWhenAccessingRegionMembers()
{
var listener = new MySubscriberClass();
try
{
RegionManager.UpdatingRegions += listener.OnUpdatingRegions;
RegionManager regionManager = new RegionManager();
regionManager.Regions.ContainsRegionWithName("TestRegion");
Assert.IsTrue(listener.OnUpdatingRegionsCalled);
listener.OnUpdatingRegionsCalled = false;
regionManager.Regions.Add(new MockPresentationRegion() { Name = "TestRegion" });
Assert.IsTrue(listener.OnUpdatingRegionsCalled);
listener.OnUpdatingRegionsCalled = false;
var region = regionManager.Regions["TestRegion"];
Assert.IsTrue(listener.OnUpdatingRegionsCalled);
listener.OnUpdatingRegionsCalled = false;
regionManager.Regions.Remove("TestRegion");
Assert.IsTrue(listener.OnUpdatingRegionsCalled);
listener.OnUpdatingRegionsCalled = false;
regionManager.Regions.GetEnumerator();
Assert.IsTrue(listener.OnUpdatingRegionsCalled);
}
finally
{
RegionManager.UpdatingRegions -= listener.OnUpdatingRegions;
}
}
[TestMethod]
public void ShouldSetObservableRegionContextWhenRegionContextChanges()
{
var region = new MockPresentationRegion();
var view = new MockDependencyObject();
var observableObject = RegionContext.GetObservableContext(view);
bool propertyChangedCalled = false;
observableObject.PropertyChanged += (sender, args) => propertyChangedCalled = true;
Assert.IsNull(observableObject.Value);
RegionManager.SetRegionContext(view, "MyContext");
Assert.IsTrue(propertyChangedCalled);
Assert.AreEqual("MyContext", observableObject.Value);
}
[TestMethod]
public void ShouldNotPreventSubscribersToStaticEventFromBeingGarbageCollected()
{
var subscriber = new MySubscriberClass();
RegionManager.UpdatingRegions += subscriber.OnUpdatingRegions;
RegionManager.UpdateRegions();
Assert.IsTrue(subscriber.OnUpdatingRegionsCalled);
WeakReference subscriberWeakReference = new WeakReference(subscriber);
subscriber = null;
GC.Collect();
Assert.IsFalse(subscriberWeakReference.IsAlive);
}
[TestMethod]
public void ExceptionMessageWhenCallingUpdateRegionsShouldBeClear()
{
try
{
ExceptionExtensions.RegisterFrameworkExceptionType(typeof(FrameworkException));
RegionManager.UpdatingRegions += new EventHandler(RegionManager_UpdatingRegions);
try
{
RegionManager.UpdateRegions();
Assert.Fail();
}
catch (Exception ex)
{
Assert.IsTrue(ex.Message.Contains("Abcde"));
}
}
finally
{
RegionManager.UpdatingRegions -= new EventHandler(RegionManager_UpdatingRegions);
}
}
public void RegionManager_UpdatingRegions(object sender, EventArgs e)
{
try
{
throw new Exception("Abcde");
}
catch (Exception ex)
{
throw new FrameworkException(ex);
}
}
public class MySubscriberClass
{
public bool OnUpdatingRegionsCalled;
public void OnUpdatingRegions(object sender, EventArgs e)
{
OnUpdatingRegionsCalled = true;
}
}
[TestMethod]
public void WhenAddingRegions_ThenRegionsCollectionNotifiesUpdate()
{
var regionManager = new RegionManager();
var region1 = new Region { Name = "region1" };
var region2 = new Region { Name = "region2" };
NotifyCollectionChangedEventArgs args = null;
regionManager.Regions.CollectionChanged += (s, e) => args = e;
regionManager.Regions.Add(region1);
Assert.AreEqual(NotifyCollectionChangedAction.Add, args.Action);
CollectionAssert.AreEqual(new object[] { region1 }, args.NewItems);
Assert.AreEqual(0, args.NewStartingIndex);
Assert.IsNull(args.OldItems);
Assert.AreEqual(-1, args.OldStartingIndex);
regionManager.Regions.Add(region2);
Assert.AreEqual(NotifyCollectionChangedAction.Add, args.Action);
CollectionAssert.AreEqual(new object[] { region2 }, args.NewItems);
Assert.AreEqual(0, args.NewStartingIndex);
Assert.IsNull(args.OldItems);
Assert.AreEqual(-1, args.OldStartingIndex);
}
[TestMethod]
public void WhenRemovingRegions_ThenRegionsCollectionNotifiesUpdate()
{
var regionManager = new RegionManager();
var region1 = new Region { Name = "region1" };
var region2 = new Region { Name = "region2" };
regionManager.Regions.Add(region1);
regionManager.Regions.Add(region2);
NotifyCollectionChangedEventArgs args = null;
regionManager.Regions.CollectionChanged += (s, e) => args = e;
regionManager.Regions.Remove("region2");
Assert.AreEqual(NotifyCollectionChangedAction.Remove, args.Action);
CollectionAssert.AreEqual(new object[] { region2 }, args.OldItems);
Assert.AreEqual(0, args.OldStartingIndex);
Assert.IsNull(args.NewItems);
Assert.AreEqual(-1, args.NewStartingIndex);
regionManager.Regions.Remove("region1");
Assert.AreEqual(NotifyCollectionChangedAction.Remove, args.Action);
CollectionAssert.AreEqual(new object[] { region1 }, args.OldItems);
Assert.AreEqual(0, args.OldStartingIndex);
Assert.IsNull(args.NewItems);
Assert.AreEqual(-1, args.NewStartingIndex);
}
[TestMethod]
public void WhenRemovingNonExistingRegion_ThenRegionsCollectionDoesNotNotifyUpdate()
{
var regionManager = new RegionManager();
var region1 = new Region { Name = "region1" };
regionManager.Regions.Add(region1);
NotifyCollectionChangedEventArgs args = null;
regionManager.Regions.CollectionChanged += (s, e) => args = e;
regionManager.Regions.Remove("region2");
Assert.IsNull(args);
}
}
internal class FrameworkException : Exception
{
public FrameworkException(Exception inner)
: base(string.Empty, inner)
{
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Diagnostics {
using System.Text;
using System;
using System.IO;
using System.Reflection;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
// There is no good reason for the methods of this class to be virtual.
// In order to ensure trusted code can trust the data it gets from a
// StackTrace, we use an InheritanceDemand to prevent partially-trusted
// subclasses.
#if !FEATURE_CORECLR
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
#endif
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class StackFrame
{
private MethodBase method;
private int offset;
private int ILOffset;
private String strFileName;
private int iLineNumber;
private int iColumnNumber;
#if FEATURE_EXCEPTIONDISPATCHINFO
[System.Runtime.Serialization.OptionalField]
private bool fIsLastFrameFromForeignExceptionStackTrace;
#endif // FEATURE_EXCEPTIONDISPATCHINFO
internal void InitMembers()
{
method = null;
offset = OFFSET_UNKNOWN;
ILOffset = OFFSET_UNKNOWN;
strFileName = null;
iLineNumber = 0;
iColumnNumber = 0;
#if FEATURE_EXCEPTIONDISPATCHINFO
fIsLastFrameFromForeignExceptionStackTrace = false;
#endif // FEATURE_EXCEPTIONDISPATCHINFO
}
// Constructs a StackFrame corresponding to the active stack frame.
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif
public StackFrame()
{
InitMembers();
BuildStackFrame (0 + StackTrace.METHODS_TO_SKIP, false);// iSkipFrames=0
}
// Constructs a StackFrame corresponding to the active stack frame.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackFrame(bool fNeedFileInfo)
{
InitMembers();
BuildStackFrame (0 + StackTrace.METHODS_TO_SKIP, fNeedFileInfo);// iSkipFrames=0
}
// Constructs a StackFrame corresponding to a calling stack frame.
//
public StackFrame(int skipFrames)
{
InitMembers();
BuildStackFrame (skipFrames + StackTrace.METHODS_TO_SKIP, false);
}
// Constructs a StackFrame corresponding to a calling stack frame.
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackFrame(int skipFrames, bool fNeedFileInfo)
{
InitMembers();
BuildStackFrame (skipFrames + StackTrace.METHODS_TO_SKIP, fNeedFileInfo);
}
// Called from the class "StackTrace"
//
internal StackFrame(bool DummyFlag1, bool DummyFlag2)
{
InitMembers();
}
// Constructs a "fake" stack frame, just containing the given file
// name and line number. Use when you don't want to use the
// debugger's line mapping logic.
//
public StackFrame(String fileName, int lineNumber)
{
InitMembers();
BuildStackFrame (StackTrace.METHODS_TO_SKIP, false);
strFileName = fileName;
iLineNumber = lineNumber;
iColumnNumber = 0;
}
// Constructs a "fake" stack frame, just containing the given file
// name, line number and column number. Use when you don't want to
// use the debugger's line mapping logic.
//
public StackFrame(String fileName, int lineNumber, int colNumber)
{
InitMembers();
BuildStackFrame (StackTrace.METHODS_TO_SKIP, false);
strFileName = fileName;
iLineNumber = lineNumber;
iColumnNumber = colNumber;
}
// Constant returned when the native or IL offset is unknown
public const int OFFSET_UNKNOWN = -1;
internal virtual void SetMethodBase (MethodBase mb)
{
method = mb;
}
internal virtual void SetOffset (int iOffset)
{
offset = iOffset;
}
internal virtual void SetILOffset (int iOffset)
{
ILOffset = iOffset;
}
internal virtual void SetFileName (String strFName)
{
strFileName = strFName;
}
internal virtual void SetLineNumber (int iLine)
{
iLineNumber = iLine;
}
internal virtual void SetColumnNumber (int iCol)
{
iColumnNumber = iCol;
}
#if FEATURE_EXCEPTIONDISPATCHINFO
internal virtual void SetIsLastFrameFromForeignExceptionStackTrace (bool fIsLastFrame)
{
fIsLastFrameFromForeignExceptionStackTrace = fIsLastFrame;
}
internal virtual bool GetIsLastFrameFromForeignExceptionStackTrace()
{
return fIsLastFrameFromForeignExceptionStackTrace;
}
#endif // FEATURE_EXCEPTIONDISPATCHINFO
// Returns the method the frame is executing
//
public virtual MethodBase GetMethod ()
{
Contract.Ensures(Contract.Result<MethodBase>() != null);
return method;
}
// Returns the offset from the start of the native (jitted) code for the
// method being executed
//
public virtual int GetNativeOffset ()
{
return offset;
}
// Returns the offset from the start of the IL code for the
// method being executed. This offset may be approximate depending
// on whether the jitter is generating debuggable code or not.
//
public virtual int GetILOffset()
{
return ILOffset;
}
// Returns the file name containing the code being executed. This
// information is normally extracted from the debugging symbols
// for the executable.
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
public virtual String GetFileName()
{
if (strFileName != null)
{
// This isn't really correct, but we don't have
// a permission that protects discovery of potentially
// local urls so we'll use this.
FileIOPermission perm = new FileIOPermission( PermissionState.None );
perm.AllFiles = FileIOPermissionAccess.PathDiscovery;
perm.Demand();
}
return strFileName;
}
// Returns the line number in the file containing the code being executed.
// This information is normally extracted from the debugging symbols
// for the executable.
//
public virtual int GetFileLineNumber()
{
return iLineNumber;
}
// Returns the column number in the line containing the code being executed.
// This information is normally extracted from the debugging symbols
// for the executable.
//
public virtual int GetFileColumnNumber()
{
return iColumnNumber;
}
// Builds a readable representation of the stack frame
//
[System.Security.SecuritySafeCritical] // auto-generated
public override String ToString()
{
StringBuilder sb = new StringBuilder(255);
if (method != null)
{
sb.Append(method.Name);
// deal with the generic portion of the method
if (method is MethodInfo && ((MethodInfo)method).IsGenericMethod)
{
Type[] typars = ((MethodInfo)method).GetGenericArguments();
sb.Append('<');
int k = 0;
bool fFirstTyParam = true;
while (k < typars.Length)
{
if (fFirstTyParam == false)
sb.Append(',');
else
fFirstTyParam = false;
sb.Append(typars[k].Name);
k++;
}
sb.Append('>');
}
sb.Append(" at offset ");
if (offset == OFFSET_UNKNOWN)
sb.Append("<offset unknown>");
else
sb.Append(offset);
sb.Append(" in file:line:column ");
bool useFileName = (strFileName != null);
if (useFileName)
{
try
{
// This isn't really correct, but we don't have
// a permission that protects discovery of potentially
// local urls so we'll use this.
FileIOPermission perm = new FileIOPermission(PermissionState.None);
perm.AllFiles = FileIOPermissionAccess.PathDiscovery;
perm.Demand();
}
catch (System.Security.SecurityException)
{
useFileName = false;
}
}
if (!useFileName)
sb.Append("<filename unknown>");
else
sb.Append(strFileName);
sb.Append(':');
sb.Append(iLineNumber);
sb.Append(':');
sb.Append(iColumnNumber);
}
else
{
sb.Append("<null>");
}
sb.Append(Environment.NewLine);
return sb.ToString();
}
private void BuildStackFrame(int skipFrames, bool fNeedFileInfo)
{
StackFrameHelper StackF = new StackFrameHelper(fNeedFileInfo, null);
StackTrace.GetStackFramesInternal (StackF, 0, null);
int iNumOfFrames = StackF.GetNumberOfFrames();
skipFrames += StackTrace.CalculateFramesToSkip (StackF, iNumOfFrames);
if ((iNumOfFrames - skipFrames) > 0)
{
method = StackF.GetMethodBase (skipFrames);
offset = StackF.GetOffset (skipFrames);
ILOffset = StackF.GetILOffset (skipFrames);
if (fNeedFileInfo)
{
strFileName = StackF.GetFilename (skipFrames);
iLineNumber = StackF.GetLineNumber (skipFrames);
iColumnNumber = StackF.GetColumnNumber (skipFrames);
}
}
}
}
}
| |
using System;
using ExcelDna.Integration;
namespace AsyncDNA
{
// Encapsulates the information that defines and async call or observable hook-up.
// Checked for equality and stored in a Dictionary, so we have to be careful
// to define value equality and a consistent HashCode.
// Used as Keys in a Dictionary - should be immutable.
// We allow parameters to be null or primitives or ExcelReference objects,
// or a 1D array or 2D array with primitives or arrays.
internal struct AsyncCallInfo : IEquatable<AsyncCallInfo>
{
readonly string _functionName;
readonly object _parameters;
readonly int _hashCode;
public AsyncCallInfo(string functionName, object parameters)
{
_functionName = functionName;
_parameters = parameters;
_hashCode = 0; // Need to set to some value before we call a method.
_hashCode = ComputeHashCode();
}
// Jon Skeet: http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode
int ComputeHashCode()
{
unchecked
{
int hash = 17;
hash = hash * 23 + (_functionName == null ? 0 : _functionName.GetHashCode());
hash = hash * 23 + ComputeHashCode(_parameters);
return hash;
}
}
// Computes a hash code for the parameters, consistent with the value equality that we define.
// Also checks that the data types passed for parameters are among those we handle properly for value equality.
// For now no string[]. But invalid types passed in will causes exception immediately.
static int ComputeHashCode(object obj)
{
if (obj == null) return 0;
// CONSIDER: All of this could be replaced by a check for (obj is ValueType || obj is ExcelReference)
// which would allow a more flexible set of parameters, at the risk of comparisons going wrong.
// We can reconsider if this arises, or when we implement async automatically or custom marshaling
// to other data types. For now this allow everything that can be passed as parameters from Excel-DNA.
if (obj is double ||
obj is float ||
obj is string ||
obj is bool ||
obj is DateTime ||
obj is ExcelReference ||
obj is ExcelError ||
obj is ExcelEmpty ||
obj is ExcelMissing ||
obj is int ||
obj is uint ||
obj is long ||
obj is ulong ||
obj is short ||
obj is ushort ||
obj is byte ||
obj is sbyte ||
obj is decimal ||
obj.GetType().IsEnum)
{
return obj.GetHashCode();
}
unchecked
{
int hash = 17;
double[] doubles = obj as double[];
if (doubles != null)
{
foreach (double item in doubles)
{
hash = hash * 23 + item.GetHashCode();
}
return hash;
}
double[,] doubles2 = obj as double[,];
if (doubles2 != null)
{
foreach (double item in doubles2)
{
hash = hash * 23 + item.GetHashCode();
}
return hash;
}
object[] objects = obj as object[];
if (objects != null)
{
foreach (object item in objects)
{
hash = hash * 23 + ((item == null) ? 0 : ComputeHashCode(item));
}
return hash;
}
object[,] objects2 = obj as object[,];
if (objects2 != null)
{
foreach (object item in objects2)
{
hash = hash * 23 + ((item == null) ? 0 : ComputeHashCode(item));
}
return hash;
}
}
throw new ArgumentException("Invalid type used for async parameter(s)", "parameters");
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (obj.GetType() != typeof(AsyncCallInfo)) return false;
return Equals((AsyncCallInfo)obj);
}
public bool Equals(AsyncCallInfo other)
{
if (_hashCode != other._hashCode) return false;
return Equals(other._functionName, _functionName)
&& ValueEquals(_parameters, other._parameters);
}
#region Helpers to implement value equality
// The value equality we check here is for the types we allow in CheckParameterTypes above.
static bool ValueEquals(object a, object b)
{
if (Equals(a, b)) return true; // Includes check for both null
if (a is double[] && b is double[]) return ArrayEquals((double[])a, (double[])b);
if (a is double[,] && b is double[,]) return ArrayEquals((double[,])a, (double[,])b);
if (a is object[] && b is object[]) return ArrayEquals((object[])a, (object[])b);
if (a is object[,] && b is object[,]) return ArrayEquals((object[,])a, (object[,])b);
return false;
}
static bool ArrayEquals(double[] a, double[] b)
{
if (a.Length != b.Length)
return false;
for (int i = 0; i < a.Length; i++)
{
if (a[i] != b[i]) return false;
}
return true;
}
static bool ArrayEquals(double[,] a, double[,] b)
{
int rows = a.GetLength(0);
int cols = a.GetLength(1);
if (rows != b.GetLength(0) ||
cols != b.GetLength(1))
{
return false;
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (a[i, j] != b[i, j]) return false;
}
}
return true;
}
static bool ArrayEquals(object[] a, object[] b)
{
if (a.Length != b.Length)
return false;
for (int i = 0; i < a.Length; i++)
{
if (!ValueEquals(a[i], b[i]))
return false;
}
return true;
}
static bool ArrayEquals(object[,] a, object[,] b)
{
int rows = a.GetLength(0);
int cols = a.GetLength(1);
if (rows != b.GetLength(0) ||
cols != b.GetLength(1))
{
return false;
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (!ValueEquals(a[i, j], b[i, j]))
return false;
}
}
return true;
}
#endregion
public override int GetHashCode()
{
return _hashCode;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.TypeInfos;
using System.Reflection.Runtime.ParameterInfos;
using Internal.Reflection.Core.Execution;
using Internal.Reflection.Tracing;
namespace System.Reflection.Runtime.MethodInfos
{
internal abstract class RuntimeNamedMethodInfo : RuntimeMethodInfo
{
protected internal abstract String ComputeToString(RuntimeMethodInfo contextMethod);
internal abstract MethodInvoker GetUncachedMethodInvoker(RuntimeTypeInfo[] methodArguments, MemberInfo exceptionPertainant);
internal abstract RuntimeMethodHandle GetRuntimeMethodHandle(Type[] methodArguments);
}
//
// The runtime's implementation of non-constructor MethodInfo's that represent a method definition.
//
internal sealed partial class RuntimeNamedMethodInfo<TRuntimeMethodCommon> : RuntimeNamedMethodInfo
where TRuntimeMethodCommon : IRuntimeMethodCommon<TRuntimeMethodCommon>, IEquatable<TRuntimeMethodCommon>
{
//
// methodHandle - the "tkMethodDef" that identifies the method.
// definingType - the "tkTypeDef" that defined the method (this is where you get the metadata reader that created methodHandle.)
// contextType - the type that supplies the type context (i.e. substitutions for generic parameters.) Though you
// get your raw information from "definingType", you report "contextType" as your DeclaringType property.
//
// For example:
//
// typeof(Foo<>).GetTypeInfo().DeclaredMembers
//
// The definingType and contextType are both Foo<>
//
// typeof(Foo<int,String>).GetTypeInfo().DeclaredMembers
//
// The definingType is "Foo<,>"
// The contextType is "Foo<int,String>"
//
// We don't report any DeclaredMembers for arrays or generic parameters so those don't apply.
//
private RuntimeNamedMethodInfo(TRuntimeMethodCommon common, RuntimeTypeInfo reflectedType)
: base()
{
_common = common;
_reflectedType = reflectedType;
}
public sealed override MethodAttributes Attributes
{
get
{
return _common.Attributes;
}
}
public sealed override CallingConventions CallingConvention
{
get
{
return _common.CallingConvention;
}
}
public sealed override IEnumerable<CustomAttributeData> CustomAttributes
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.MethodBase_CustomAttributes(this);
#endif
return _common.CustomAttributes;
}
}
public sealed override MethodInfo GetGenericMethodDefinition()
{
if (IsGenericMethodDefinition)
return this;
throw new InvalidOperationException();
}
public sealed override bool IsConstructedGenericMethod
{
get
{
return false;
}
}
public sealed override bool IsGenericMethod
{
get
{
return IsGenericMethodDefinition;
}
}
public sealed override bool IsGenericMethodDefinition
{
get
{
return _common.IsGenericMethodDefinition;
}
}
public sealed override MethodInfo MakeGenericMethod(params Type[] typeArguments)
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.MethodInfo_MakeGenericMethod(this, typeArguments);
#endif
if (typeArguments == null)
throw new ArgumentNullException(nameof(typeArguments));
if (GenericTypeParameters.Length == 0)
throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericMethodDefinition, this));
RuntimeTypeInfo[] genericTypeArguments = new RuntimeTypeInfo[typeArguments.Length];
for (int i = 0; i < typeArguments.Length; i++)
{
if (typeArguments[i] == null)
throw new ArgumentNullException();
if (!typeArguments[i].IsRuntimeImplemented())
throw new ArgumentException(SR.Format(SR.Reflection_CustomReflectionObjectsNotSupported, typeArguments[i]), "typeArguments[" + i + "]"); // Not a runtime type.
genericTypeArguments[i] = typeArguments[i].CastToRuntimeTypeInfo();
}
if (typeArguments.Length != GenericTypeParameters.Length)
throw new ArgumentException(SR.Format(SR.Argument_NotEnoughGenArguments, typeArguments.Length, GenericTypeParameters.Length));
RuntimeMethodInfo methodInfo = (RuntimeMethodInfo)RuntimeConstructedGenericMethodInfo.GetRuntimeConstructedGenericMethodInfo(this, genericTypeArguments);
MethodInvoker methodInvoker = methodInfo.MethodInvoker; // For compatibility with other Make* apis, trigger any MissingMetadataExceptions now rather than later.
return methodInfo;
}
public sealed override MethodBase MetadataDefinitionMethod
{
get
{
return RuntimeNamedMethodInfo<TRuntimeMethodCommon>.GetRuntimeNamedMethodInfo(_common.RuntimeMethodCommonOfUninstantiatedMethod, _common.ContextTypeInfo);
}
}
public sealed override MethodImplAttributes MethodImplementationFlags
{
get
{
return _common.MethodImplementationFlags;
}
}
public sealed override Module Module
{
get
{
return _common.Module;
}
}
public sealed override Type ReflectedType
{
get
{
return _reflectedType;
}
}
public sealed override int MetadataToken
{
get
{
return _common.MetadataToken;
}
}
public sealed override String ToString()
{
return ComputeToString(this);
}
public sealed override bool Equals(Object obj)
{
RuntimeNamedMethodInfo<TRuntimeMethodCommon> other = obj as RuntimeNamedMethodInfo<TRuntimeMethodCommon>;
if (other == null)
return false;
if (!_common.Equals(other._common))
return false;
if (!(_reflectedType.Equals(other._reflectedType)))
return false;
return true;
}
public sealed override int GetHashCode()
{
return _common.GetHashCode();
}
public sealed override RuntimeMethodHandle MethodHandle => GetRuntimeMethodHandle(null);
protected internal sealed override String ComputeToString(RuntimeMethodInfo contextMethod)
{
return RuntimeMethodHelpers.ComputeToString(ref _common, contextMethod, contextMethod.RuntimeGenericArgumentsOrParameters);
}
internal sealed override RuntimeTypeInfo[] RuntimeGenericArgumentsOrParameters
{
get
{
return this.GenericTypeParameters;
}
}
internal sealed override RuntimeParameterInfo[] GetRuntimeParameters(RuntimeMethodInfo contextMethod, out RuntimeParameterInfo returnParameter)
{
return RuntimeMethodHelpers.GetRuntimeParameters(ref _common, contextMethod, contextMethod.RuntimeGenericArgumentsOrParameters, out returnParameter);
}
internal sealed override RuntimeTypeInfo RuntimeDeclaringType
{
get
{
return _common.DeclaringType;
}
}
internal sealed override String RuntimeName
{
get
{
return _common.Name;
}
}
internal sealed override RuntimeMethodInfo WithReflectedTypeSetToDeclaringType
{
get
{
if (_reflectedType.Equals(_common.DefiningTypeInfo))
return this;
return RuntimeNamedMethodInfo<TRuntimeMethodCommon>.GetRuntimeNamedMethodInfo(_common, _common.ContextTypeInfo);
}
}
private RuntimeTypeInfo[] GenericTypeParameters
{
get
{
RuntimeNamedMethodInfo<TRuntimeMethodCommon> owningMethod = this;
if (DeclaringType.IsConstructedGenericType)
{
// Desktop compat: Constructed generic types and their generic type definitions share the same Type objects for method generic parameters.
TRuntimeMethodCommon uninstantiatedCommon = _common.RuntimeMethodCommonOfUninstantiatedMethod;
owningMethod = RuntimeNamedMethodInfo<TRuntimeMethodCommon>.GetRuntimeNamedMethodInfo(uninstantiatedCommon, uninstantiatedCommon.DeclaringType);
}
else
{
// Desktop compat: DeclaringMethod always returns a MethodInfo whose ReflectedType is equal to DeclaringType.
if (!_reflectedType.Equals(_common.DeclaringType))
owningMethod = RuntimeNamedMethodInfo<TRuntimeMethodCommon>.GetRuntimeNamedMethodInfo(_common, _common.DeclaringType);
}
return _common.GetGenericTypeParametersWithSpecifiedOwningMethod(owningMethod);
}
}
internal sealed override MethodInvoker GetUncachedMethodInvoker(RuntimeTypeInfo[] methodArguments, MemberInfo exceptionPertainant)
{
return _common.GetUncachedMethodInvoker(methodArguments, exceptionPertainant);
}
protected sealed override MethodInvoker UncachedMethodInvoker
{
get
{
return GetUncachedMethodInvoker(Array.Empty<RuntimeTypeInfo>(), this);
}
}
internal sealed override RuntimeMethodHandle GetRuntimeMethodHandle(Type[] genericArgs)
{
return _common.GetRuntimeMethodHandle(genericArgs);
}
private TRuntimeMethodCommon _common;
private readonly RuntimeTypeInfo _reflectedType;
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.IO;
using ID3.ID3v2Frames;
using ID3.ID3v2Frames.TextFrames;
using ID3.ID3v2Frames.BinaryFrames;
using ID3.ID3v2Frames.OtherFrames;
using ID3.ID3v2Frames.ArrayFrames;
using ID3.ID3v2Frames.StreamFrames;
namespace ID3
{
public class ID3v2
{
private string _FilePath; // ID3 file path
private FilterCollection _Filter; // Contain Filter Frames
private FilterTypes _FilterType; //Indicate wich filter type use
private ID3v2Flags _Flags;
private bool _LoadLinkedFrames; // Indicate load Link frames when loading ID3 or not
private bool _DropUnknown; // if true. unknown frames will not save
private Version _ver; // Contain ID3 version information
private bool _HaveTag; // Indicate if current file have ID3v2 Info
private ErrorCollection _Errors; // Contain Errors that occured
private static TextEncodings _DefaultUnicodeEncoding = TextEncodings.UTF_16; // when use AutoTextEncoding which unicode type must use
private static bool _AutoTextEncoding = true; // when want to save frame use automatic text encoding
#region -> Frame Variable <-
// Frames that can be more than one
private FramesCollection<TextFrame> _TextFrames;
private FramesCollection<UserTextFrame> _UserTextFrames;
private FramesCollection<PrivateFrame> _PrivateFrames;
private FramesCollection<TextWithLanguageFrame> _TextWithLangFrames;
private FramesCollection<SynchronisedText> _SynchronisedTextFrames;
private FramesCollection<AttachedPictureFrame> _AttachedPictureFrames;
private FramesCollection<GeneralFileFrame> _EncapsulatedObjectFrames;
private FramesCollection<PopularimeterFrame> _PopularimeterFrames;
private FramesCollection<AudioEncryptionFrame> _AudioEncryptionFrames;
private FramesCollection<LinkFrame> _LinkFrames;
private FramesCollection<TermOfUseFrame> _TermOfUseFrames;
private FramesCollection<DataWithSymbolFrame> _DataWithSymbolFrames;
private FramesCollection<BinaryFrame> _UnknownFrames;
// Frames that can't repeat
private BinaryFrame _MCDIFrame;
private SynchronisedTempoFrame _SYTCFrame; // Synchronised tempo codes
private PlayCounterFrame _PCNTFrame; // Play Counter
private RecomendedBufferSizeFrame _RBUFFrame;
private OwnershipFrame _OWNEFrame; // Owner ship
private CommercialFrame _COMRFrame;
private ReverbFrame _RVRBFrame;
private Equalisation _EQUAFrame;
private RelativeVolumeFrame _RVADFrame;
private EventTimingCodeFrame _ETCOFrame;
private PositionSynchronisedFrame _POSSFrame;
#endregion
/// <summary>
/// Create new ID3v2 class for specific file
/// </summary>
/// <param name="FileAddress">FileAddress to read ID3 information from</param>
/// <param name="LoadData">Indicate load ID3 in constructor or not</param>
public ID3v2(string FilePath, bool LoadData)
{
// ------ Set default values -----------
_LoadLinkedFrames = true;
_DropUnknown = false;
_FilePath = FilePath;
Initializer();
if (LoadData == true)
Load();
}
private void Initializer()
{
_Filter = new FilterCollection();
_FilterType = FilterTypes.NoFilter;
_Errors = new ErrorCollection();
_TextFrames = new FramesCollection<TextFrame>();
_UserTextFrames = new FramesCollection<UserTextFrame>();
_PrivateFrames = new FramesCollection<PrivateFrame>();
_TermOfUseFrames = new FramesCollection<TermOfUseFrame>();
_TextWithLangFrames = new FramesCollection<TextWithLanguageFrame>();
_SynchronisedTextFrames = new FramesCollection<SynchronisedText>();
_AttachedPictureFrames = new FramesCollection<AttachedPictureFrame>();
_EncapsulatedObjectFrames = new FramesCollection<GeneralFileFrame>();
_PopularimeterFrames = new FramesCollection<PopularimeterFrame>();
_AudioEncryptionFrames = new FramesCollection<AudioEncryptionFrame>();
_LinkFrames = new FramesCollection<LinkFrame>();
_DataWithSymbolFrames = new FramesCollection<DataWithSymbolFrame>();
_UnknownFrames = new FramesCollection<BinaryFrame>();
}
private void WriteID3Header(FileStream Data, int Ver)
{
byte[] Buf;
Buf = Encoding.ASCII.GetBytes("ID3");
Data.Write(Buf, 0, 3); // Write ID3
// ----------- Write Version ---------
Data.WriteByte(Convert.ToByte(Ver));
Data.WriteByte(0);
Data.WriteByte((byte)_Flags);
// -------- Write Size --------------------
// -- Calculating and writing length of ID3
// for more information look at references
Buf = new byte[4];
int Len = Length;
for (int i = 3; i >= 0; i--)
{
Buf[i] = Convert.ToByte(Len % 0x80);
Len /= 0x80;
}
Data.Write(Buf, 0, 4);
_ver = new Version("2.3.0");
}
/// <summary>
/// Get FileName according to specific formula
/// </summary>
/// <param name="Formula">Formula to make FileName</param>
/// <returns>System.String contain FileName according to formula or String.Empty</returns>
private string FormulaFileName(string Formula)
{
Formula = Formula.Replace("[Title]", GetTextFrame("TIT2"));
if (Formula.Contains("[Track]"))
Formula = Formula.Replace("[Track]", TrackNumber);
if (Formula.Contains("[00Track]"))
{
string T = TrackNumber;
if (T.Length < 2)
T = T.Insert(0, "0");
Formula = Formula.Replace("[00Track]", T);
}
if (Formula.Contains("[000Track]"))
{
string T = TrackNumber;
if (T.Length < 2)
T = T.Insert(0, "00");
else if (T.Length < 3)
T = T.Insert(0, "0");
Formula = Formula.Replace("[000Track]", T);
}
Formula = Formula.Replace("[Album]", GetTextFrame("TALB"));
return Formula + ".mp3";
}
/// <summary>
/// Get TrackNumber for renaming
/// </summary>
private string TrackNumber
{
get
{
string Track = GetTextFrame("TRCK");
int i = Track.IndexOf('/');
if (i != -1)
Track = Track.Substring(0, i);
return Track;
}
}
/// <summary>
/// Add specific ID3Error to ErrorCollection
/// </summary>
/// <param name="Error">Error to add</param>
private void AddError(ID3Error Error)
{
_Errors.Add(Error);
}
#region -> Public Properties <-
/// <summary>
/// Gets Collection of Errors that occured
/// </summary>
public ErrorCollection Errors
{
get
{ return _Errors; }
}
/// <summary>
/// Gets FileAddress of current ID3v2
/// </summary>
public string FilePath
{
get
{ return _FilePath; }
}
/// <summary>
/// Get FileName of current ID3v2
/// </summary>
public string FileName
{
get
{ return Path.GetFileName(_FilePath); }
}
/// <summary>
/// Get Filter of current frame
/// </summary>
public FilterCollection Filter
{
get
{ return _Filter; }
}
/// <summary>
/// Gets or Sets current Tag filter type
/// </summary>
public FilterTypes FilterType
{
get
{ return _FilterType; }
set
{ _FilterType = value; }
}
/// <summary>
/// Gets or Sets Flags of current ID3 Tag
/// </summary>
public ID3v2Flags Flags
{
get
{ return _Flags; }
set
{ _Flags = value; }
}
/// <summary>
/// Indicate load Linked frames info while loading Tag
/// </summary>
public bool LoadLinkedFrames
{
get
{ return _LoadLinkedFrames; }
set
{ _LoadLinkedFrames = value; }
}
/// <summary>
/// Indicate drop unknown frame while saving ID3 or not
/// </summary>
public bool DropUnknowFrames
{
get
{ return _DropUnknown; }
set
{ _DropUnknown = value; }
}
/// <summary>
/// Get version of current ID3 Tag
/// </summary>
public Version VersionInfo
{
get
{ return _ver; }
}
/// <summary>
/// Indicate if current file have ID3v2 Information
/// </summary>
public bool HaveTag
{
get
{ return _HaveTag; }
set
{
if (_HaveTag == true && value == false)
ClearAll();
_HaveTag = value;
}
}
/// <summary>
/// Get length of current ID3 Tag
/// </summary>
public int Length
{
get
{
int RLen = 0;
foreach (TextFrame TF in _TextFrames.Items)
if (TF.IsAvailable)
RLen += TF.Length + 10;
/*foreach (UserTextFrame UTF in _UserTextFrames.Items)
if (UTF.IsAvailable)
RLen += UTF.Length + 10;
foreach (PrivateFrame PF in _PrivateFrames.Items)
if (PF.IsAvailable)
RLen += PF.Length + 10;*/
foreach (TextWithLanguageFrame TWLF in _TextWithLangFrames.Items)
if (TWLF != null && TWLF.IsAvailable)
RLen += TWLF.Length + 10;/*
foreach (SynchronisedText ST in _SynchronisedTextFrames.Items)
if (ST.IsAvailable)
RLen += ST.Length + 10;*/
foreach (AttachedPictureFrame AP in _AttachedPictureFrames.Items)
if (AP.IsAvailable)
RLen += AP.Length + 10;/*
foreach (GeneralFileFrame GF in _EncapsulatedObjectFrames.Items)
if (GF.IsAvailable)
RLen += GF.Length + 10;
foreach (PopularimeterFrame PF in _PopularimeterFrames.Items)
if (PF.IsAvailable)
RLen += PF.Length + 10;
foreach (AudioEncryptionFrame AE in _AudioEncryptionFrames.Items)
if (AE.IsAvailable)
RLen += AE.Length + 10;
foreach (LinkFrame LF in _LinkFrames.Items)
if (LF.IsAvailable)
RLen += LF.Length + 10;
foreach (TermOfUseFrame TU in _TermOfUseFrames.Items)
if (TU.IsAvailable)
RLen += TU.Length + 10;
foreach (DataWithSymbolFrame DS in _DataWithSymbolFrames.Items)
if (DS.IsAvailable)
RLen += DS.Length + 10;
if (!_DropUnknown)
foreach (BinaryFrame BF in _UnknownFrames.Items)
if (BF.IsAvailable)
RLen += BF.Length + 10;
if (_MCDIFrame != null)
if (_MCDIFrame.IsAvailable)
RLen += _MCDIFrame.Length + 10;
if (_SYTCFrame != null)
if (_SYTCFrame.IsAvailable)
RLen += _SYTCFrame.Length + 10;
if (_PCNTFrame != null)
if (_PCNTFrame.IsAvailable)
RLen += _PCNTFrame.Length + 10;
if (_RBUFFrame != null)
if (_RBUFFrame.IsAvailable)
RLen += _RBUFFrame.Length + 10;
if (_OWNEFrame != null)
if (_OWNEFrame.IsAvailable)
RLen += _OWNEFrame.Length + 10;
if (_COMRFrame != null)
if (_COMRFrame.IsAvailable)
RLen += _COMRFrame.Length + 10;
if (_RVRBFrame != null)
if (_RVRBFrame.IsAvailable)
RLen += _RVRBFrame.Length + 10;
if (_EQUAFrame != null)
if (_EQUAFrame.IsAvailable)
RLen += _EQUAFrame.Length + 10;
if (_RVADFrame != null)
if (_RVADFrame.IsAvailable)
RLen += _RVADFrame.Length + 10;
if (_ETCOFrame != null)
if (_ETCOFrame.IsAvailable)
RLen += _ETCOFrame.Length + 10;
if (_POSSFrame != null)
if (_POSSFrame.IsAvailable)
RLen += _POSSFrame.Length + 10;*/
return RLen;
}
}
/// <summary>
/// Indicate if current ID3Info had error while openning
/// </summary>
public bool HadError
{
get
{
if (_Errors.Count > 0)
return true;
else
return false;
}
}
/// <summary>
/// Gets or sets unicode encoding of AutoTextEncoding
/// </summary>
public static TextEncodings DefaultUnicodeEncoding
{
get
{ return _DefaultUnicodeEncoding; }
set
{
if ((int)value > 3 || (int)value < 2)
throw (new ArgumentOutOfRangeException("Default unicode must be one of (UTF_16, UTF_16BE, UTF_8)"));
_DefaultUnicodeEncoding = value;
}
}
/// <summary>
/// Indicate while saving automatically detect encoding of texts of not
/// </summary>
public static bool AutoTextEncoding
{
get
{ return _AutoTextEncoding; }
set
{ _AutoTextEncoding = value; }
}
#endregion
#region -> Public Methods <-
/// <summary>
/// Load ID3 information from file
/// </summary>
/// <exception cref="FileNotFoundException">File Not Found</exception>
public void Load()
{
FileStreamEx ID3File = new FileStreamEx(_FilePath, FileMode.Open);
if (!ID3File.HaveID3v2()) // If file don't contain ID3v2 exit function
{
_HaveTag = false;
ID3File.Close();
return;
}
_ver = ID3File.ReadVersion(); // Read ID3v2 version
_Flags = (ID3v2Flags)ID3File.ReadByte();
// Extended Header Must Read Here
ReadFrames(ID3File, ID3File.ReadSize());
ID3File.Close();
_HaveTag = true;
}
/// <summary>
/// Save ID3v2 data without renaming file with minor version of 3
/// </summary>
public void Save()
{
Save(3, "");
}
/// <summary>
/// Save ID3 info to file
/// </summary>
/// <param name="Ver">minor version of ID3v2</param>
/// <param name="Formula">Formula to renaming file</param>
public void Save(int Ver, string Formula)
{
if (Ver < 3 || Ver > 4)
throw (new ArgumentOutOfRangeException("Version of ID3 can be between 3-4"));
string NewFilePath;
if (Formula == "")
NewFilePath = _FilePath;
else
{
string DirName = Path.GetDirectoryName(_FilePath);
NewFilePath = DirName + ((DirName.Length > 0) ? "\\" : "") +
this.FormulaFileName(Formula);
}
FileStreamEx Orgin = new FileStreamEx(_FilePath, FileMode.Open);
FileStreamEx Temp = new FileStreamEx(NewFilePath + "~TEMP", FileMode.Create);
int StartIndex = 0;
if (Orgin.HaveID3v2())
{
Orgin.Seek(3, SeekOrigin.Current);
StartIndex = Orgin.ReadSize();
}
//if (!_HaveTag)
//{
// SaveRestOfFile(StartIndex, Orgin, Temp, 0);
// return;
//}
WriteID3Header(Temp, Ver);
foreach (TextFrame TF in _TextFrames.Items)
{
if (!FramesInfo.IsCompatible(TF.FrameID, Ver))
continue;
if (TF.IsAvailable)
TF.FrameStream(Ver).WriteTo(Temp);
}
/*
foreach (UserTextFrame UTF in _UserTextFrames.Items)
{
if (!FramesInfo.IsCompatible(UTF.FrameID, Ver))
continue;
if (UTF.IsAvailable)
UTF.FrameStream(Ver).WriteTo(Temp);
}
foreach (PrivateFrame PF in _PrivateFrames.Items)
{
if (!FramesInfo.IsCompatible(PF.FrameID, Ver))
continue;
if (PF.IsAvailable)
PF.FrameStream(Ver).WriteTo(Temp);
}
foreach (SynchronisedText ST in _SynchronisedTextFrames.Items)
{
if (!FramesInfo.IsCompatible(ST.FrameID, Ver))
continue;
if (ST.IsAvailable)
ST.FrameStream(Ver).WriteTo(Temp);
}
*/
foreach (TextWithLanguageFrame TWLF in _TextWithLangFrames.Items)
{
if (!FramesInfo.IsCompatible(TWLF.FrameID, Ver))
continue;
if (TWLF.IsAvailable)
TWLF.FrameStream(Ver).WriteTo(Temp);
}
foreach (AttachedPictureFrame AP in _AttachedPictureFrames.Items)
{
if (!FramesInfo.IsCompatible(AP.FrameID, Ver))
continue;
if (AP.IsAvailable)
AP.FrameStream(Ver).WriteTo(Temp);
}
/*
foreach (GeneralFileFrame GF in _EncapsulatedObjectFrames.Items)
{
if (!FramesInfo.IsCompatible(GF.FrameID, Ver))
continue;
if (GF.IsAvailable)
GF.FrameStream(Ver).WriteTo(Temp);
}
foreach (PopularimeterFrame PF in _PopularimeterFrames.Items)
{
if (!FramesInfo.IsCompatible(PF.FrameID, Ver))
continue;
if (PF.IsAvailable)
PF.FrameStream(Ver).WriteTo(Temp);
}
foreach (AudioEncryptionFrame AE in _AudioEncryptionFrames.Items)
{
if (!FramesInfo.IsCompatible(AE.FrameID, Ver))
continue;
if (AE.IsAvailable)
AE.FrameStream(Ver).WriteTo(Temp);
}
foreach (LinkFrame LF in _LinkFrames.Items)
{
if (!FramesInfo.IsCompatible(LF.FrameID, Ver))
continue;
if (LF.IsAvailable)
LF.FrameStream(Ver).WriteTo(Temp);
}
foreach (TermOfUseFrame TU in _TermOfUseFrames.Items)
{
if (!FramesInfo.IsCompatible(TU.FrameID, Ver))
continue;
if (TU.IsAvailable)
TU.FrameStream(Ver).WriteTo(Temp);
}
foreach (DataWithSymbolFrame DS in _DataWithSymbolFrames.Items)
{
if (!FramesInfo.IsCompatible(DS.FrameID, Ver))
continue;
if (DS.IsAvailable)
DS.FrameStream(Ver).WriteTo(Temp);
}
// Saving Unknown Frames
if (!_DropUnknown)
foreach (BinaryFrame BF in _UnknownFrames.Items)
if (BF.IsAvailable)
BF.FrameStream(Ver).WriteTo(Temp);
if (_MCDIFrame != null && FramesInfo.IsCompatible(_MCDIFrame.FrameID, Ver))
if (_MCDIFrame.IsAvailable)
_MCDIFrame.FrameStream(Ver).WriteTo(Temp);
if (_SYTCFrame != null && FramesInfo.IsCompatible(_SYTCFrame.FrameID, Ver))
if (_SYTCFrame.IsAvailable)
_SYTCFrame.FrameStream(Ver).WriteTo(Temp);
if (_PCNTFrame != null && FramesInfo.IsCompatible(_PCNTFrame.FrameID, Ver))
if (_PCNTFrame.IsAvailable)
_PCNTFrame.FrameStream(Ver).WriteTo(Temp);
if (_RBUFFrame != null && FramesInfo.IsCompatible(_RBUFFrame.FrameID, Ver))
if (_RBUFFrame.IsAvailable)
_RBUFFrame.FrameStream(Ver).WriteTo(Temp);
if (_OWNEFrame != null && FramesInfo.IsCompatible(_OWNEFrame.FrameID, Ver))
if (_OWNEFrame.IsAvailable)
_OWNEFrame.FrameStream(Ver).WriteTo(Temp);
if (_COMRFrame != null && FramesInfo.IsCompatible(_COMRFrame.FrameID, Ver))
if (_COMRFrame.IsAvailable)
_COMRFrame.FrameStream(Ver).WriteTo(Temp);
if (_RVRBFrame != null && FramesInfo.IsCompatible(_RVRBFrame.FrameID, Ver))
if (_RVRBFrame.IsAvailable)
_RVRBFrame.FrameStream(Ver).WriteTo(Temp);
if (_EQUAFrame != null && FramesInfo.IsCompatible(_EQUAFrame.FrameID, Ver))
if (_EQUAFrame.IsAvailable)
_EQUAFrame.FrameStream(Ver).WriteTo(Temp);
if (_RVADFrame != null && FramesInfo.IsCompatible(_RVADFrame.FrameID, Ver))
if (_RVADFrame.IsAvailable)
_RVADFrame.FrameStream(Ver).WriteTo(Temp);
if (_ETCOFrame != null && FramesInfo.IsCompatible(_ETCOFrame.FrameID, Ver))
if (_ETCOFrame.IsAvailable)
_ETCOFrame.FrameStream(_ver.Minor).WriteTo(Temp);
if (_POSSFrame != null && FramesInfo.IsCompatible(_POSSFrame.FrameID, Ver))
if (_POSSFrame.IsAvailable)
_POSSFrame.FrameStream(Ver).WriteTo(Temp);
*/
SaveRestOfFile(StartIndex, Orgin, Temp, Ver);
}
private void SaveRestOfFile(int StartIndex, FileStreamEx Orgin,
FileStreamEx Temp, int Ver)
{
try
{
if (!Orgin.CanWrite) return;
Orgin.Seek(StartIndex, SeekOrigin.Begin);
byte[] Buf = new byte[Orgin.Length - StartIndex];
Orgin.Read(Buf, 0, Buf.Length);
Temp.Write(Buf, 0, Buf.Length);
Orgin.Close();
Temp.Close();
if (Ver != 0)
SetMinorVersion(Ver);
File.Delete(Orgin.Name);
string FinallyName = Temp.Name.Remove(Temp.Name.Length - 5);
File.Move(Temp.Name, FinallyName);
_FilePath = FinallyName;
}
catch
{
}
}
/// <summary>
/// Save ID3 info to file
/// </summary>
/// <param name="Ver">minor version of ID3v2</param>
public void Save(int Ver)
{
Save(Ver, "");
}
/// <summary>
/// Clear all ID3 Tag information
/// </summary>
public void ClearAll()
{
_TextFrames.Clear();
_UserTextFrames.Clear();
_PrivateFrames.Clear();
_TextWithLangFrames.Clear();
_SynchronisedTextFrames.Clear();
_SynchronisedTextFrames.Clear();
_AttachedPictureFrames.Clear();
_EncapsulatedObjectFrames.Clear();
_PopularimeterFrames.Clear();
_AudioEncryptionFrames.Clear();
_LinkFrames.Clear();
_TermOfUseFrames.Clear();
_DataWithSymbolFrames.Clear();
_UnknownFrames.Clear();
_MCDIFrame = null;
_SYTCFrame = null;
_PCNTFrame = null;
_RBUFFrame = null;
_OWNEFrame = null;
_COMRFrame = null;
_RVRBFrame = null;
_EQUAFrame = null;
_RVADFrame = null;
_ETCOFrame = null;
}
/// <summary>
/// Load all linked information frames
/// </summary>
public void LoadAllLinkedFrames()
{
foreach (LinkFrame LF in _LinkFrames.Items)
LoadFrameFromFile(LF.FrameIdentifier, LF.URL);
}
/// <summary>
/// Load spefic frame information
/// </summary>
/// <param name="FrameID">FrameID to load</param>
/// <param name="FileAddress">FileAddress to read tag from</param>
private void LoadFrameFromFile(string FrameID, string FileAddress)
{
ID3v2 LinkedInfo = new ID3v2(FileAddress, false);
LinkedInfo.Filter.Add(FrameID);
LinkedInfo.FilterType = FilterTypes.LoadFiltersOnly;
LinkedInfo.Load();
if (LinkedInfo.HadError)
foreach (ID3Error IE in LinkedInfo.Errors)
_Errors.Add(new ID3Error("In Linked Info(" +
FileAddress + "): " + IE.Message, IE.FrameID));
foreach (TextFrame TF in LinkedInfo._TextFrames)
_TextFrames.Add(TF);
foreach (UserTextFrame UT in LinkedInfo._UserTextFrames)
_UserTextFrames.Add(UT);
foreach (PrivateFrame PF in LinkedInfo._PrivateFrames)
_PrivateFrames.Add(PF);
foreach (TextWithLanguageFrame TWLF in LinkedInfo._TextWithLangFrames)
_TextWithLangFrames.Add(TWLF);
foreach (SynchronisedText ST in LinkedInfo._SynchronisedTextFrames)
_SynchronisedTextFrames.Add(ST);
foreach (AttachedPictureFrame AP in LinkedInfo._AttachedPictureFrames)
_AttachedPictureFrames.Add(AP);
foreach (GeneralFileFrame GF in LinkedInfo._EncapsulatedObjectFrames)
_EncapsulatedObjectFrames.Add(GF);
foreach (PopularimeterFrame PF in LinkedInfo._PopularimeterFrames)
_PopularimeterFrames.Add(PF);
foreach (AudioEncryptionFrame AE in LinkedInfo._AudioEncryptionFrames)
_AudioEncryptionFrames.Add(AE);
// Link to LinkFrame is not available
foreach (TermOfUseFrame TU in LinkedInfo._TermOfUseFrames)
_TermOfUseFrames.Add(TU);
foreach (DataWithSymbolFrame DWS in LinkedInfo._DataWithSymbolFrames)
_DataWithSymbolFrames.Add(DWS);
foreach (BinaryFrame BF in LinkedInfo._UnknownFrames)
_UnknownFrames.Add(BF);
if (LinkedInfo._MCDIFrame != null)
_MCDIFrame = LinkedInfo._MCDIFrame;
if (LinkedInfo._SYTCFrame != null)
_SYTCFrame = LinkedInfo._SYTCFrame;
if (LinkedInfo._PCNTFrame != null)
_PCNTFrame = LinkedInfo._PCNTFrame;
if (LinkedInfo._RBUFFrame != null)
_RBUFFrame = LinkedInfo._RBUFFrame;
if (LinkedInfo._OWNEFrame != null)
_OWNEFrame = LinkedInfo._OWNEFrame;
if (LinkedInfo._COMRFrame != null)
_COMRFrame = LinkedInfo._COMRFrame;
if (LinkedInfo._RVRBFrame != null)
_RVRBFrame = LinkedInfo._RVRBFrame;
if (LinkedInfo._EQUAFrame != null)
_EQUAFrame = LinkedInfo._EQUAFrame;
if (LinkedInfo._RVADFrame != null)
_RVADFrame = LinkedInfo._RVADFrame;
if (LinkedInfo._ETCOFrame != null)
_ETCOFrame = LinkedInfo._ETCOFrame;
}
/// <summary>
/// Search TextFrames for specific FrameID
/// </summary>
/// <param name="FrameID">FrameID to search in TextFrames</param>
/// <returns>TextFrame according to FrameID</returns>
public string GetTextFrame(string FrameID)
{
foreach (TextFrame TF in _TextFrames)
if (TF.FrameID == FrameID)
return TF.Text;
return "";
}
/// <summary>
/// Set text of specific TextFrame
/// </summary>
/// <param name="FrameID">FrameID</param>
/// <param name="Text">Text to set</param>
/// <param name="TextEncoding">Enxoding of text</param>
/// <param name="ver">minor version of ID3v2</param>
public void SetTextFrame(string FrameID, string Text)
{
if (!FramesInfo.IsValidFrameID(FrameID))
return;
for (int i = 0; i < _TextFrames.Count - 1; i++)
{
if (_TextFrames.Items[i].FrameID == FrameID)
{
_TextFrames.RemoveAt(i);
break;
}
}
if (Text != "")
{
_TextFrames.Add(new TextFrame(FrameID, new FrameFlags(),
Text, (Frame.IsAscii(Text) ? TextEncodings.Ascii : _DefaultUnicodeEncoding),
_ver.Minor));
}
}
/// <summary>
/// Set minor version of current ID3v2
/// </summary>
/// <param name="ver"></param>
public void SetMinorVersion(int ver)
{
if (ver == 4 || ver == 3)
_ver = new Version(2, ver, 0);
else
throw (new ArgumentException("Minor version can be 3 of 4"));
}
#endregion
#region -> Private 'Read Methods' <-
/// <summary>
/// Read all frames from specific FileStream
/// </summary>
/// <param name="Data">FileStream to read data from</param>
/// <param name="Length">Length of data to read from FileStream</param>
private void ReadFrames(FileStreamEx Data, int Length)
{
string FrameID;
int FrameLength;
FrameFlags Flags = new FrameFlags();
byte Buf;
// If ID3v2 is ID3v2.2 FrameID, FrameLength of Frames is 3 byte
// otherwise it's 4 character
int FrameIDLen = VersionInfo.Minor == 2 ? 3 : 4;
// Minimum frame size is 10 because frame header is 10 byte
while (Length > 10)
{
// check for padding( 00 bytes )
Buf = Data.ReadByte();
if (Buf == 0)
{
Length--;
continue;
}
// if readed byte is not zero. it must read as FrameID
Data.Seek(-1, SeekOrigin.Current);
// ---------- Read Frame Header -----------------------
FrameID = Data.ReadText(FrameIDLen, TextEncodings.Ascii);
try
{
if (FrameIDLen == 3)
FrameID = FramesInfo.Get4CharID(FrameID);
FrameLength = Convert.ToInt32(Data.ReadUInt(FrameIDLen));
if (FrameLength > 0xA00000) //10M
{
return;
}
if (FrameIDLen == 4)
Flags = (FrameFlags)Data.ReadUInt(2);
else
Flags = 0; // must set to default flag
}
catch
{
return;
}
long Position = Data.Position;
if (Length > 0x10000000)
throw (new FileLoadException("This file contain frame that have more than 256MB data"));
bool Added = false;
if (IsAddable(FrameID)) // Check if frame is not filter
Added = AddFrame(Data, FrameID, FrameLength, Flags);
if (!Added)
// if don't read this frame
// we must go forward to read next frame
Data.Position = Position + FrameLength;
Length -= FrameLength + 10;
}
}
/// <summary>
/// Indicate can add specific frame according to Filter
/// </summary>
/// <param name="FrameID">FrameID to check</param>
/// <returns>true if can add otherwise false</returns>
private bool IsAddable(string FrameID)
{
if (_FilterType == FilterTypes.NoFilter)
return true;
else if (_FilterType == FilterTypes.LoadFiltersOnly)
return _Filter.IsExists(FrameID);
else // Not Load Filters
return !_Filter.IsExists(FrameID);
}
/// <summary>
/// Add Frame information to where it must store
/// </summary>
/// <param name="Data">FileStream contain Frame</param>
/// <param name="FrameID">FrameID of frame</param>
/// <param name="Length">Maximum available length to read</param>
/// <param name="Flags">Flags of frame</param>
private bool AddFrame(FileStreamEx Data, string FrameID, int Length, FrameFlags Flags)
{
// NOTE: All FrameIDs must be capital letters
if (!FramesInfo.IsValidFrameID(FrameID))
{
AddError(new ID3Error("nonValid Frame found and dropped", FrameID));
return false;
}
int IsText = FramesInfo.IsTextFrame(FrameID, _ver.Minor);
if (IsText == 1)
{
TextFrame TempTextFrame = new TextFrame(FrameID, Flags, Data, Length);
if (TempTextFrame.IsReadableFrame)
{
_TextFrames.Add(TempTextFrame);
return true;
}
return false;
}
if (IsText == 2)
{
UserTextFrame TempUserTextFrame = new UserTextFrame(FrameID, Flags, Data, Length);
if (TempUserTextFrame.IsReadableFrame)
{
_UserTextFrames.Add(TempUserTextFrame);
return true;
}
return false;
}
switch (FrameID)
{
case "UFID":
case "PRIV":
PrivateFrame TempPrivateFrame = new PrivateFrame(FrameID, Flags, Data, Length);
if (TempPrivateFrame.IsReadableFrame)
{
_PrivateFrames.Add(TempPrivateFrame); return true;
}
else
AddError(new ID3Error(TempPrivateFrame.ErrorMessage, FrameID));
break;
case "USLT":
case "COMM":
TextWithLanguageFrame TempTextWithLangFrame = new TextWithLanguageFrame(FrameID, Flags, Data, Length);
if (TempTextWithLangFrame.IsReadableFrame)
{ _TextWithLangFrames.Add(TempTextWithLangFrame); return true; }
else
AddError(new ID3Error(TempTextWithLangFrame.ErrorMessage, FrameID));
break;
case "SYLT":
SynchronisedText TempSynchronisedText = new SynchronisedText(FrameID, Flags, Data, Length);
if (TempSynchronisedText.IsReadableFrame)
{ _SynchronisedTextFrames.Add(TempSynchronisedText); return true; }
else
AddError(new ID3Error(TempSynchronisedText.ErrorMessage, FrameID));
break;
case "GEOB":
GeneralFileFrame TempGeneralFileFrame = new GeneralFileFrame(FrameID, Flags, Data, Length);
if (TempGeneralFileFrame.IsReadableFrame)
{ _EncapsulatedObjectFrames.Add(TempGeneralFileFrame); return true; }
else
AddError(new ID3Error(TempGeneralFileFrame.ErrorMessage, FrameID));
break;
case "POPM":
PopularimeterFrame TempPopularimeterFrame = new PopularimeterFrame(FrameID, Flags, Data, Length);
if (TempPopularimeterFrame.IsReadableFrame)
{ _PopularimeterFrames.Add(TempPopularimeterFrame); return true; }
else
AddError(new ID3Error(TempPopularimeterFrame.ErrorMessage, FrameID));
break;
case "AENC":
AudioEncryptionFrame TempAudioEncryptionFrame = new AudioEncryptionFrame(FrameID, Flags, Data, Length);
if (TempAudioEncryptionFrame.IsReadableFrame)
{ _AudioEncryptionFrames.Add(TempAudioEncryptionFrame); return true; }
else
AddError(new ID3Error(TempAudioEncryptionFrame.ErrorMessage, FrameID));
break;
case "USER":
TermOfUseFrame TempTermOfUseFrame = new TermOfUseFrame(FrameID, Flags, Data, Length);
if (TempTermOfUseFrame.IsReadableFrame)
{ _TermOfUseFrames.Add(TempTermOfUseFrame); return true; }
else
AddError(new ID3Error(TempTermOfUseFrame.ErrorMessage, FrameID));
break;
case "ENCR":
case "GRID":
DataWithSymbolFrame TempDataWithSymbolFrame = new DataWithSymbolFrame(FrameID, Flags, Data, Length);
if (TempDataWithSymbolFrame.IsReadableFrame)
{ _DataWithSymbolFrames.Add(TempDataWithSymbolFrame); return true; }
else
AddError(new ID3Error(TempDataWithSymbolFrame.ErrorMessage, FrameID));
break;
case "LINK":
LinkFrame LF = new LinkFrame(FrameID, Flags, Data, Length);
if (LF.IsReadableFrame)
{
_LinkFrames.Add(LF);
if (_LoadLinkedFrames)
{ LoadFrameFromFile(LF.FrameIdentifier, LF.URL); return true; }
}
else
AddError(new ID3Error(LF.ErrorMessage, FrameID));
break;
case "APIC":
AttachedPictureFrame TempAttachedPictureFrame = new AttachedPictureFrame(FrameID, Flags, Data, Length);
if (TempAttachedPictureFrame.IsReadableFrame)
{ _AttachedPictureFrames.Add(TempAttachedPictureFrame); return true; }
else
AddError(new ID3Error(TempAttachedPictureFrame.ErrorMessage, FrameID));
break;
case "MCDI":
BinaryFrame MCDI = new BinaryFrame(FrameID, Flags, Data, Length);
if (MCDI.IsReadableFrame)
{ _MCDIFrame = MCDI; return true; }
else
AddError(new ID3Error(MCDI.ErrorMessage, FrameID));
break;
case "SYTC":
SynchronisedTempoFrame SYTC = new SynchronisedTempoFrame(FrameID, Flags, Data, Length);
if (SYTC.IsReadableFrame)
{ _SYTCFrame = SYTC; return true; }
else
AddError(new ID3Error(SYTC.ErrorMessage, FrameID));
break;
case "PCNT":
PlayCounterFrame PCNT = new PlayCounterFrame(FrameID, Flags, Data, Length);
if (PCNT.IsReadableFrame)
{ _PCNTFrame = PCNT; return true; }
else
AddError(new ID3Error(PCNT.ErrorMessage, FrameID));
break;
case "RBUF":
RecomendedBufferSizeFrame RBUF = new RecomendedBufferSizeFrame(FrameID, Flags, Data, Length);
if (RBUF.IsReadableFrame)
{ _RBUFFrame = RBUF; return true; }
else
AddError(new ID3Error(RBUF.ErrorMessage, FrameID));
break;
case "OWNE":
OwnershipFrame OWNE = new OwnershipFrame(FrameID, Flags, Data, Length);
if (OWNE.IsReadableFrame)
{ _OWNEFrame = OWNE; return true; }
else
AddError(new ID3Error(OWNE.ErrorMessage, FrameID));
break;
case "COMR":
CommercialFrame COMR = new CommercialFrame(FrameID, Flags, Data, Length);
if (COMR.IsReadableFrame)
{ _COMRFrame = COMR; return true; }
else
AddError(new ID3Error(COMR.ErrorMessage, FrameID));
break;
case "RVRB":
ReverbFrame RVRB = new ReverbFrame(FrameID, Flags, Data, Length);
if (RVRB.IsReadableFrame)
{ _RVRBFrame = RVRB; return true; }
else
AddError(new ID3Error(RVRB.ErrorMessage, FrameID));
break;
case "EQUA":
Equalisation EQUA = new Equalisation(FrameID, Flags, Data, Length);
if (EQUA.IsReadableFrame)
{ _EQUAFrame = EQUA; return true; }
else
AddError(new ID3Error(EQUA.ErrorMessage, FrameID));
break;
case "RVAD":
RelativeVolumeFrame RVAD = new RelativeVolumeFrame(FrameID, Flags, Data, Length);
if (RVAD.IsReadableFrame)
{ _RVADFrame = RVAD; return true; }
else
AddError(new ID3Error(RVAD.ErrorMessage, FrameID));
break;
case "ETCO":
EventTimingCodeFrame ETCO = new EventTimingCodeFrame(FrameID, Flags, Data, Length);
if (ETCO.IsReadableFrame)
{ _ETCOFrame = ETCO; return true; }
else
AddError(new ID3Error(ETCO.ErrorMessage, FrameID));
break;
case "POSS":
PositionSynchronisedFrame POSS = new PositionSynchronisedFrame(FrameID, Flags, Data, Length);
if (POSS.IsReadableFrame)
{ _POSSFrame = POSS; return true; }
else
AddError(new ID3Error(POSS.ErrorMessage, FrameID));
break;
default:
BinaryFrame Temp = new BinaryFrame(FrameID, Flags, Data, Length);
if (Temp.IsReadableFrame)
{ _UnknownFrames.Add(Temp); return true; }
else
AddError(new ID3Error(Temp.ErrorMessage, FrameID));
break;
// TODO: Mpeg Location
}
return false;
}
#endregion
#region -> Public 'Single Time Frames Properties' <-
/// <summary>
/// Get MusicCDIdentifier of current ID3
/// </summary>
public BinaryFrame MusicCDIdentifier
{
get
{ return _MCDIFrame; }
set
{ _MCDIFrame = value; }
}
/// <summary>
/// Get SynchronisedTempoCodes of current ID3
/// </summary>
public SynchronisedTempoFrame SynchronisedTempoCodes
{
get
{ return _SYTCFrame; }
}
/// <summary>
/// Get PlayCounter of current ID3
/// </summary>
public PlayCounterFrame PlayCounter
{
get
{ return _PCNTFrame; }
set
{ _PCNTFrame = value; }
}
/// <summary>
/// Get RecomendedBuffer of current ID3
/// </summary>
public RecomendedBufferSizeFrame RecomendedBuffer
{
get
{ return _RBUFFrame; }
}
/// <summary>
/// Get OwnerShip of current ID3
/// </summary>
public OwnershipFrame OwnerShip
{
get
{ return _OWNEFrame; }
set
{ _OWNEFrame = value; }
}
/// <summary>
/// Get Commercial of current ID3
/// </summary>
public CommercialFrame Commercial
{
get
{ return _COMRFrame; }
set
{ _COMRFrame = value; }
}
/// <summary>
/// Get Reverb of current ID3
/// </summary>
public ReverbFrame Reverb
{
get
{ return _RVRBFrame; }
}
/// <summary>
/// Get Equalisations of current ID3
/// </summary>
public Equalisation Equalisations
{
get
{ return _EQUAFrame; }
}
/// <summary>
/// Get RelativeVolume of current ID3
/// </summary>
public RelativeVolumeFrame RelativeVolume
{
get
{ return _RVADFrame; }
}
/// <summary>
/// Get EventTimingCode of current ID3
/// </summary>
public EventTimingCodeFrame EventTimingCode
{
get
{ return _ETCOFrame; }
}
/// <summary>
/// Get PositionSynchronised of current ID3
/// </summary>
public PositionSynchronisedFrame PositionSynchronised
{
get
{ return _POSSFrame; }
}
#endregion
#region -> Public 'Collection Properties' <-
/// <summary>
/// Get TextFrame Collection of current ID3
/// </summary>
public FramesCollection<TextFrame> TextFrames
{
get { return _TextFrames; }
}
/// <summary>
/// Get UserTextFrame Collection of current ID3
/// </summary>
public FramesCollection<UserTextFrame> UserTextFrames
{
get { return _UserTextFrames; }
}
/// <summary>
/// Get PrivateFrame Collection of current ID3
/// </summary>
public FramesCollection<PrivateFrame> PrivateFrames
{
get { return _PrivateFrames; }
}
/// <summary>
/// Get TextWithLanguageFrame Collection of current ID3
/// </summary>
public FramesCollection<TextWithLanguageFrame> TextWithLanguageFrames
{
get { return _TextWithLangFrames; }
}
/// <summary>
/// Get SynchronisedText Collection of current ID3
/// </summary>
public FramesCollection<SynchronisedText> SynchronisedTextFrames
{
get { return _SynchronisedTextFrames; }
}
/// <summary>
/// Get AttachedPictureFrame Collection of current ID3
/// </summary>
public FramesCollection<AttachedPictureFrame> AttachedPictureFrames
{
get { return _AttachedPictureFrames; }
}
/// <summary>
/// Get GeneralFileFrame Collection of current ID3
/// </summary>
public FramesCollection<GeneralFileFrame> EncapsulatedObjectFrames
{
get { return _EncapsulatedObjectFrames; }
}
/// <summary>
/// Get PopularimeterFrame Collection of current ID3
/// </summary>
public FramesCollection<PopularimeterFrame> PopularimeterFrames
{
get { return _PopularimeterFrames; }
}
/// <summary>
/// Get AudioEncryptionFrame Collection of current ID3
/// </summary>
public FramesCollection<AudioEncryptionFrame> AudioEncryptionFrames
{
get { return _AudioEncryptionFrames; }
}
/// <summary>
/// Get LinkFrame Collection of current ID3
/// </summary>
public FramesCollection<LinkFrame> LinkFrames
{
get { return _LinkFrames; }
}
/// <summary>
/// Get TermOfUseFrame Collection of current ID3
/// </summary>
public FramesCollection<TermOfUseFrame> TermOfUseFrames
{
get { return _TermOfUseFrames; }
}
/// <summary>
/// Get DataWithSymbolFrame Collection of current ID3
/// </summary>
public FramesCollection<DataWithSymbolFrame> DataWithSymbolFrames
{
get { return _DataWithSymbolFrames; }
}
/// <summary>
/// Get BinaryFrame Collection of current ID3
/// </summary>
public FramesCollection<BinaryFrame> UnKnownFrames
{
get { return _UnknownFrames; }
}
#endregion
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
using Microsoft.Win32.SafeHandles;
namespace System.Security.Cryptography {
/// <summary>
/// Flag to indicate if we're doing encryption or decryption
/// </summary>
internal enum EncryptionMode {
Encrypt,
Decrypt
}
/// <summary>
/// Implementation of a generic CAPI symmetric encryption algorithm. Concrete SymmetricAlgorithm classes
/// which wrap CAPI implementations can use this class to perform the actual encryption work.
/// </summary>
internal sealed class CapiSymmetricAlgorithm : ICryptoTransform {
private int m_blockSize;
private byte[] m_depadBuffer;
private EncryptionMode m_encryptionMode;
[SecurityCritical]
private SafeCapiKeyHandle m_key;
private PaddingMode m_paddingMode;
[SecurityCritical]
private SafeCspHandle m_provider;
[System.Security.SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Reviewed")]
public CapiSymmetricAlgorithm(int blockSize,
int feedbackSize,
SafeCspHandle provider,
SafeCapiKeyHandle key,
byte[] iv,
CipherMode cipherMode,
PaddingMode paddingMode,
EncryptionMode encryptionMode) {
Contract.Requires(0 < blockSize && blockSize % 8 == 0);
Contract.Requires(0 <= feedbackSize);
Contract.Requires(provider != null && !provider.IsInvalid && !provider.IsClosed);
Contract.Requires(key != null && !key.IsInvalid && !key.IsClosed);
Contract.Ensures(m_provider != null && !m_provider.IsInvalid && !m_provider.IsClosed);
m_blockSize = blockSize;
m_encryptionMode = encryptionMode;
m_paddingMode = paddingMode;
m_provider = provider.Duplicate();
m_key = SetupKey(key, ProcessIV(iv, blockSize, cipherMode), cipherMode, feedbackSize);
}
public bool CanReuseTransform {
get { return true; }
}
public bool CanTransformMultipleBlocks {
get { return true; }
}
//
// Note: both input and output block size are in bytes rather than bits
//
public int InputBlockSize {
[Pure]
get { return m_blockSize / 8; }
}
public int OutputBlockSize {
get { return m_blockSize / 8; }
}
[SecuritySafeCritical]
public void Dispose() {
Contract.Ensures(m_key == null || m_key.IsClosed);
Contract.Ensures(m_provider == null || m_provider.IsClosed);
Contract.Ensures(m_depadBuffer == null);
if (m_key != null) {
m_key.Dispose();
}
if (m_provider != null) {
m_provider.Dispose();
}
if (m_depadBuffer != null) {
Array.Clear(m_depadBuffer, 0, m_depadBuffer.Length);
}
return;
}
[SecuritySafeCritical]
private int DecryptBlocks(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) {
Contract.Requires(m_key != null);
Contract.Requires(inputBuffer != null && inputCount <= inputBuffer.Length - inputOffset);
Contract.Requires(inputOffset >= 0);
Contract.Requires(inputCount > 0 && inputCount % InputBlockSize == 0);
Contract.Requires(outputBuffer != null && inputCount <= outputBuffer.Length - outputOffset);
Contract.Requires(inputOffset >= 0);
Contract.Requires(m_depadBuffer == null || (m_paddingMode != PaddingMode.None && m_paddingMode != PaddingMode.Zeros));
Contract.Ensures(Contract.Result<int>() >= 0);
//
// If we're decrypting, it's possible to be called with the last blocks of the data, and then
// have TransformFinalBlock called with an empty array. Since we don't know if this is the case,
// we won't decrypt the last block of the input until either TransformBlock or
// TransformFinalBlock is next called.
//
// We don't need to do this for PaddingMode.None because there is no padding to strip, and
// we also don't do this for PaddingMode.Zeros since there is no way for us to tell if the
// zeros at the end of a block are part of the plaintext or the padding.
//
int decryptedBytes = 0;
if (m_paddingMode != PaddingMode.None && m_paddingMode != PaddingMode.Zeros) {
// If we have data saved from a previous call, decrypt that into the output first
if (m_depadBuffer != null) {
int depadDecryptLength = RawDecryptBlocks(m_depadBuffer, 0, m_depadBuffer.Length);
Buffer.BlockCopy(m_depadBuffer, 0, outputBuffer, outputOffset, depadDecryptLength);
Array.Clear(m_depadBuffer, 0, m_depadBuffer.Length);
outputOffset += depadDecryptLength;
decryptedBytes += depadDecryptLength;
}
else {
m_depadBuffer = new byte[InputBlockSize];
}
// Copy the last block of the input buffer into the depad buffer
Debug.Assert(inputCount >= m_depadBuffer.Length, "inputCount >= m_depadBuffer.Length");
Buffer.BlockCopy(inputBuffer,
inputOffset + inputCount - m_depadBuffer.Length,
m_depadBuffer,
0,
m_depadBuffer.Length);
inputCount -= m_depadBuffer.Length;
Debug.Assert(inputCount % InputBlockSize == 0, "Did not remove whole blocks for depadding");
}
// CryptDecrypt operates in place, so if after reserving the depad buffer there's still data to decrypt,
// make a copy of that in the output buffer to work on.
if (inputCount > 0) {
Buffer.BlockCopy(inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount);
decryptedBytes += RawDecryptBlocks(outputBuffer, outputOffset, inputCount);
}
return decryptedBytes;
}
/// <summary>
/// Remove the padding from the last blocks being decrypted
/// </summary>
private byte[] DepadBlock(byte[] block, int offset, int count) {
Contract.Requires(block != null && count >= block.Length - offset);
Contract.Requires(0 <= offset);
Contract.Requires(0 <= count);
Contract.Ensures(Contract.Result<byte[]>() != null && Contract.Result<byte[]>().Length <= block.Length);
int padBytes = 0;
// See code:System.Security.Cryptography.CapiSymmetricAlgorithm.PadBlock for a description of the
// padding modes.
switch (m_paddingMode) {
case PaddingMode.ANSIX923:
padBytes = block[offset + count - 1];
// Verify the amount of padding is reasonable
if (padBytes <= 0 || padBytes > InputBlockSize) {
throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidPadding));
}
// Verify that all the padding bytes are 0s
for (int i = offset + count - padBytes; i < offset + count - 1; i++) {
if (block[i] != 0) {
throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidPadding));
}
}
break;
case PaddingMode.ISO10126:
padBytes = block[offset + count - 1];
// Verify the amount of padding is reasonable
if (padBytes <= 0 || padBytes > InputBlockSize) {
throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidPadding));
}
// Since the padding consists of random bytes, we cannot verify the actual pad bytes themselves
break;
case PaddingMode.PKCS7:
padBytes = block[offset + count - 1];
// Verify the amount of padding is reasonable
if (padBytes <= 0 || padBytes > InputBlockSize) {
throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidPadding));
}
// Verify all the padding bytes match the amount of padding
for (int i = offset + count - padBytes; i < offset + count; i++) {
if (block[i] != padBytes) {
throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidPadding));
}
}
break;
// We cannot remove Zeros padding because we don't know if the zeros at the end of the block
// belong to the padding or the plaintext itself.
case PaddingMode.Zeros:
case PaddingMode.None:
padBytes = 0;
break;
default:
throw new CryptographicException(SR.GetString(SR.Cryptography_UnknownPaddingMode));
}
// Copy everything but the padding to the output
byte[] depadded = new byte[count - padBytes];
Buffer.BlockCopy(block, offset, depadded, 0, depadded.Length);
return depadded;
}
/// <summary>
/// Encrypt blocks of plaintext
/// </summary>
[SecurityCritical]
private int EncryptBlocks(byte[] buffer, int offset, int count) {
Contract.Requires(m_key != null);
Contract.Requires(buffer != null && count <= buffer.Length - offset);
Contract.Requires(offset >= 0);
Contract.Requires(count > 0 && count % InputBlockSize == 0);
Contract.Ensures(Contract.Result<int>() >= 0);
//
// Do the encryption. Note that CapiSymmetricAlgorithm will do all padding itself since the CLR
// supports padding modes that CAPI does not, so we will always tell CAPI that we are not working
// with the final block.
//
int dataLength = count;
unsafe {
fixed (byte* pData = &buffer[offset]) {
if (!CapiNative.UnsafeNativeMethods.CryptEncrypt(m_key,
SafeCapiHashHandle.InvalidHandle,
false,
0,
new IntPtr(pData),
ref dataLength,
buffer.Length - offset)) {
throw new CryptographicException(Marshal.GetLastWin32Error());
}
}
}
return dataLength;
}
/// <summary>
/// Calculate the padding for a block of data
/// </summary>
[SecuritySafeCritical]
private byte[] PadBlock(byte[] block, int offset, int count) {
Contract.Requires(m_provider != null);
Contract.Requires(block != null && count <= block.Length - offset);
Contract.Requires(0 <= offset);
Contract.Requires(0 <= count);
Contract.Ensures(Contract.Result<byte[]>() != null && Contract.Result<byte[]>().Length % InputBlockSize == 0);
byte[] result = null;
int padBytes = InputBlockSize - (count % InputBlockSize);
switch (m_paddingMode) {
// ANSI padding fills the blocks with zeros and adds the total number of padding bytes as
// the last pad byte, adding an extra block if the last block is complete.
//
// x 00 00 00 00 00 00 07
case PaddingMode.ANSIX923:
result = new byte[count + padBytes];
Buffer.BlockCopy(block, 0, result, 0, count);
result[result.Length - 1] = (byte)padBytes;
break;
// ISO padding fills the blocks up with random bytes and adds the total number of padding
// bytes as the last pad byte, adding an extra block if the last block is complete.
//
// xx rr rr rr rr rr rr 07
case PaddingMode.ISO10126:
result = new byte[count + padBytes];
CapiNative.UnsafeNativeMethods.CryptGenRandom(m_provider, result.Length - 1, result);
Buffer.BlockCopy(block, 0, result, 0, count);
result[result.Length - 1] = (byte)padBytes;
break;
// No padding requires that the input already be a multiple of the block size
case PaddingMode.None:
if (count % InputBlockSize != 0) {
throw new CryptographicException(SR.GetString(SR.Cryptography_PartialBlock));
}
result = new byte[count];
Buffer.BlockCopy(block, offset, result, 0, result.Length);
break;
// PKCS padding fills the blocks up with bytes containing the total number of padding bytes
// used, adding an extra block if the last block is complete.
//
// xx xx 06 06 06 06 06 06
case PaddingMode.PKCS7:
result = new byte[count + padBytes];
Buffer.BlockCopy(block, offset, result, 0, count);
for (int i = count; i < result.Length; i++) {
result[i] = (byte)padBytes;
}
break;
// Zeros padding fills the last partial block with zeros, and does not add a new block to
// the end if the last block is already complete.
//
// xx 00 00 00 00 00 00 00
case PaddingMode.Zeros:
if (padBytes == InputBlockSize) {
padBytes = 0;
}
result = new byte[count + padBytes];
Buffer.BlockCopy(block, offset, result, 0, count);
break;
default:
throw new CryptographicException(SR.GetString(SR.Cryptography_UnknownPaddingMode));
}
return result;
}
/// <summary>
/// Validate and transform the user's IV into one that we will pass on to CAPI
///
/// If we have an IV, make a copy of it so that it doesn't get modified while we're using it. If
/// not, and we're not in ECB mode then throw an error, since we cannot decrypt without the IV, and
/// generating a random IV to encrypt with would lead to data which is not decryptable.
///
/// For compatibility with v1.x, we accept IVs which are longer than the block size, and truncate
/// them back. We will reject an IV which is smaller than the block size however.
/// </summary>
private static byte[] ProcessIV(byte[] iv, int blockSize, CipherMode cipherMode) {
Contract.Requires(blockSize % 8 == 0);
Contract.Ensures(cipherMode == CipherMode.ECB ||
(Contract.Result<byte[]>() != null && Contract.Result<byte[]>().Length == blockSize / 8));
byte[] realIV = null;
if (iv != null) {
if (blockSize / 8 <= iv.Length) {
realIV = new byte[blockSize / 8];
Buffer.BlockCopy(iv, 0, realIV, 0, realIV.Length);
}
else {
throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidIVSize));
}
}
else if (cipherMode != CipherMode.ECB) {
throw new CryptographicException(SR.GetString(SR.Cryptography_MissingIV));
}
return realIV;
}
/// <summary>
/// Do a direct decryption of the ciphertext blocks. This method should not be called from anywhere
/// but DecryptBlocks or TransformFinalBlock since it does not account for the depadding buffer and
/// direct use could lead to incorrect decryption values.
/// </summary>
[SecurityCritical]
private int RawDecryptBlocks(byte[] buffer, int offset, int count) {
Contract.Requires(m_key != null);
Contract.Requires(buffer != null && count <= buffer.Length - offset);
Contract.Requires(offset >= 0);
Contract.Requires(count > 0 && count % InputBlockSize == 0);
Contract.Ensures(Contract.Result<int>() >= 0);
//
// Do the decryption. Note that CapiSymmetricAlgorithm will do all padding itself since the CLR
// supports padding modes that CAPI does not, so we will always tell CAPI that we are not working
// with the final block.
//
int dataLength = count;
unsafe {
fixed (byte* pData = &buffer[offset]) {
if (!CapiNative.UnsafeNativeMethods.CryptDecrypt(m_key,
SafeCapiHashHandle.InvalidHandle,
false,
0,
new IntPtr(pData),
ref dataLength)) {
throw new CryptographicException(Marshal.GetLastWin32Error());
}
}
}
return dataLength;
}
/// <summary>
/// Reset the state of the algorithm so that it can begin processing a new message
/// </summary>
[SecuritySafeCritical]
private void Reset() {
Contract.Requires(m_key != null);
Contract.Ensures(m_depadBuffer == null);
//
// CryptEncrypt / CryptDecrypt must be called with the Final parameter set to true so that
// their internal state is reset. Since we do all padding by hand, this isn't done by
// TransformFinalBlock so is done on an empty buffer here.
//
byte[] buffer = new byte[OutputBlockSize];
int resetSize = 0;
unsafe {
fixed (byte* pBuffer = buffer) {
if (m_encryptionMode == EncryptionMode.Encrypt) {
CapiNative.UnsafeNativeMethods.CryptEncrypt(m_key,
SafeCapiHashHandle.InvalidHandle,
true,
0,
new IntPtr(pBuffer),
ref resetSize,
buffer.Length);
}
else {
CapiNative.UnsafeNativeMethods.CryptDecrypt(m_key,
SafeCapiHashHandle.InvalidHandle,
true,
0,
new IntPtr(pBuffer),
ref resetSize);
}
}
}
// Also erase the depadding buffer so we don't cross data from the previous message into this one
if (m_depadBuffer != null) {
Array.Clear(m_depadBuffer, 0, m_depadBuffer.Length);
m_depadBuffer = null;
}
}
/// <summary>
/// Encrypt or decrypt a single block of data
/// </summary>
[SecuritySafeCritical]
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) {
Contract.Ensures(Contract.Result<int>() >= 0);
if (inputBuffer == null) {
throw new ArgumentNullException("inputBuffer");
}
if (inputOffset < 0) {
throw new ArgumentOutOfRangeException("inputOffset");
}
if (inputCount <= 0) {
throw new ArgumentOutOfRangeException("inputCount");
}
if (inputCount % InputBlockSize != 0) {
throw new ArgumentOutOfRangeException("inputCount", SR.GetString(SR.Cryptography_MustTransformWholeBlock));
}
if (inputCount > inputBuffer.Length - inputOffset) {
throw new ArgumentOutOfRangeException("inputCount", SR.GetString(SR.Cryptography_TransformBeyondEndOfBuffer));
}
if (outputBuffer == null) {
throw new ArgumentNullException("outputBuffer");
}
if (inputCount > outputBuffer.Length - outputOffset) {
throw new ArgumentOutOfRangeException("outputOffset", SR.GetString(SR.Cryptography_TransformBeyondEndOfBuffer));
}
if (m_encryptionMode == EncryptionMode.Encrypt) {
// CryptEncrypt operates in place, so make a copy of the original data in the output buffer for
// it to work on.
Buffer.BlockCopy(inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount);
return EncryptBlocks(outputBuffer, outputOffset, inputCount);
}
else {
return DecryptBlocks(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
}
}
/// <summary>
/// Encrypt or decrypt the last block of data in the current message
/// </summary>
[SecuritySafeCritical]
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) {
Contract.Ensures(Contract.Result<byte[]>() != null);
if (inputBuffer == null) {
throw new ArgumentNullException("inputBuffer");
}
if (inputOffset < 0) {
throw new ArgumentOutOfRangeException("inputOffset");
}
if (inputCount < 0) {
throw new ArgumentOutOfRangeException("inputCount");
}
if (inputCount > inputBuffer.Length - inputOffset) {
throw new ArgumentOutOfRangeException("inputCount", SR.GetString(SR.Cryptography_TransformBeyondEndOfBuffer));
}
byte[] outputData = null;
if (m_encryptionMode == EncryptionMode.Encrypt) {
// If we're encrypting, we need to pad the last block before encrypting it
outputData = PadBlock(inputBuffer, inputOffset, inputCount);
if (outputData.Length > 0) {
EncryptBlocks(outputData, 0, outputData.Length);
}
}
else {
// We can't complete decryption on a partial block
if (inputCount % InputBlockSize != 0) {
throw new CryptographicException(SR.GetString(SR.Cryptography_PartialBlock));
}
//
// If we have a depad buffer, copy that into the decryption buffer followed by the input data.
// Otherwise the decryption buffer is just the input data.
//
byte[] ciphertext = null;
if (m_depadBuffer == null) {
ciphertext = new byte[inputCount];
Buffer.BlockCopy(inputBuffer, inputOffset, ciphertext, 0, inputCount);
}
else {
ciphertext = new byte[m_depadBuffer.Length + inputCount];
Buffer.BlockCopy(m_depadBuffer, 0, ciphertext, 0, m_depadBuffer.Length);
Buffer.BlockCopy(inputBuffer, inputOffset, ciphertext, m_depadBuffer.Length, inputCount);
}
// Decrypt the data, then strip the padding to get the final decrypted data.
if (ciphertext.Length > 0) {
int decryptedBytes = RawDecryptBlocks(ciphertext, 0, ciphertext.Length);
outputData = DepadBlock(ciphertext, 0, decryptedBytes);
}
else {
outputData = new byte[0];
}
}
Reset();
return outputData;
}
/// <summary>
/// Prepare the cryptographic key for use in the encryption / decryption operation
/// </summary>
[System.Security.SecurityCritical]
private static SafeCapiKeyHandle SetupKey(SafeCapiKeyHandle key, byte[] iv, CipherMode cipherMode, int feedbackSize) {
Contract.Requires(key != null);
Contract.Requires(cipherMode == CipherMode.ECB || iv != null);
Contract.Requires(0 <= feedbackSize);
Contract.Ensures(Contract.Result<SafeCapiKeyHandle>() != null &&
!Contract.Result<SafeCapiKeyHandle>().IsInvalid &&
!Contract.Result<SafeCapiKeyHandle>().IsClosed);
// Make a copy of the key so that we don't modify the properties of the caller's copy
SafeCapiKeyHandle encryptionKey = key.Duplicate();
// Setup the cipher mode first
CapiNative.SetKeyParameter(encryptionKey, CapiNative.KeyParameter.Mode, (int)cipherMode);
// If we're not in ECB mode then setup the IV
if (cipherMode != CipherMode.ECB) {
CapiNative.SetKeyParameter(encryptionKey, CapiNative.KeyParameter.IV, iv);
}
// OFB and CFB require a feedback loop size
if (cipherMode == CipherMode.CFB || cipherMode == CipherMode.OFB) {
CapiNative.SetKeyParameter(encryptionKey, CapiNative.KeyParameter.ModeBits, feedbackSize);
}
return encryptionKey;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace System.IO
{
/// <devdoc>
/// Listens to the system directory change notifications and
/// raises events when a directory or file within a directory changes.
/// </devdoc>
public partial class FileSystemWatcher : IDisposable
{
/// <devdoc>
/// Private instance variables
/// </devdoc>
// Directory being monitored
private string _directory;
// Filter for name matching
private string _filter;
// The watch filter for the API call.
private const NotifyFilters c_defaultNotifyFilters = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
private NotifyFilters _notifyFilters = c_defaultNotifyFilters;
// Flag to watch subtree of this directory
private bool _includeSubdirectories = false;
// Flag to note whether we are attached to the thread pool and responding to changes
private bool _enabled = false;
// Buffer size
private int _internalBufferSize = 8192;
// Used for synchronization
private bool _disposed;
// Event handlers
private FileSystemEventHandler _onChangedHandler = null;
private FileSystemEventHandler _onCreatedHandler = null;
private FileSystemEventHandler _onDeletedHandler = null;
private RenamedEventHandler _onRenamedHandler = null;
private ErrorEventHandler _onErrorHandler = null;
// To validate the input for "path"
private static readonly char[] s_wildcards = new char[] { '?', '*' };
private const int c_notifyFiltersValidMask = (int)(NotifyFilters.Attributes |
NotifyFilters.CreationTime |
NotifyFilters.DirectoryName |
NotifyFilters.FileName |
NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.Security |
NotifyFilters.Size);
#if DEBUG
static FileSystemWatcher()
{
int s_notifyFiltersValidMask = 0;
foreach (int enumValue in Enum.GetValues(typeof(NotifyFilters)))
s_notifyFiltersValidMask |= enumValue;
Debug.Assert(c_notifyFiltersValidMask == s_notifyFiltersValidMask, "The NotifyFilters enum has changed. The c_notifyFiltersValidMask must be updated to reflect the values of the NotifyFilters enum.");
}
#endif
~FileSystemWatcher()
{
this.Dispose(false);
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class.
/// </devdoc>
public FileSystemWatcher()
{
_directory = string.Empty;
_filter = "*.*";
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class,
/// given the specified directory to monitor.
/// </devdoc>
public FileSystemWatcher(string path) : this(path, "*.*")
{
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class,
/// given the specified directory and type of files to monitor.
/// </devdoc>
public FileSystemWatcher(string path, string filter)
{
if (path == null)
throw new ArgumentNullException("path");
if (filter == null)
throw new ArgumentNullException("filter");
// Early check for directory parameter so that an exception can be thrown as early as possible.
if (path.Length == 0 || !Directory.Exists(path))
throw new ArgumentException(SR.Format(SR.InvalidDirName, path), "path");
_directory = path;
_filter = filter;
}
/// <devdoc>
/// Gets or sets the type of changes to watch for.
/// </devdoc>
public NotifyFilters NotifyFilter
{
get
{
return _notifyFilters;
}
set
{
if (((int)value & ~c_notifyFiltersValidMask) != 0)
throw new ArgumentException(SR.Format(SR.InvalidEnumArgument, "value", (int)value, typeof(NotifyFilters).Name));
if (_notifyFilters != value)
{
_notifyFilters = value;
Restart();
}
}
}
/// <devdoc>
/// Gets or sets a value indicating whether the component is enabled.
/// </devdoc>
public bool EnableRaisingEvents
{
get
{
return _enabled;
}
set
{
if (_enabled == value)
{
return;
}
if (value)
{
StartRaisingEventsIfNotDisposed(); // will set _enabled to true once successfully started
}
else
{
StopRaisingEvents(); // will set _enabled to false
}
}
}
/// <devdoc>
/// Gets or sets the filter string, used to determine what files are monitored in a directory.
/// </devdoc>
public string Filter
{
get
{
return _filter;
}
set
{
if (string.IsNullOrEmpty(value))
{
// Skip the string compare for "*.*" since it has no case-insensitive representation that differs from
// the case-sensitive representation.
_filter = "*.*";
}
else if (!string.Equals(_filter, value, PathInternal.StringComparison))
{
_filter = value;
}
}
}
/// <devdoc>
/// Gets or sets a value indicating whether subdirectories within the specified path should be monitored.
/// </devdoc>
public bool IncludeSubdirectories
{
get
{
return _includeSubdirectories;
}
set
{
if (_includeSubdirectories != value)
{
_includeSubdirectories = value;
Restart();
}
}
}
/// <devdoc>
/// Gets or sets the size of the internal buffer.
/// </devdoc>
public int InternalBufferSize
{
get
{
return _internalBufferSize;
}
set
{
if (_internalBufferSize != value)
{
if (value < 4096)
{
_internalBufferSize = 4096;
}
else
{
_internalBufferSize = value;
}
Restart();
}
}
}
/// <summary>Allocates a buffer of the requested internal buffer size.</summary>
/// <returns>The allocated buffer.</returns>
private byte[] AllocateBuffer()
{
try
{
return new byte[_internalBufferSize];
}
catch (OutOfMemoryException)
{
throw new OutOfMemoryException(SR.Format(SR.BufferSizeTooLarge, _internalBufferSize));
}
}
/// <devdoc>
/// Gets or sets the path of the directory to watch.
/// </devdoc>
public string Path
{
get
{
return _directory;
}
set
{
value = (value == null) ? string.Empty : value;
if (!string.Equals(_directory, value, PathInternal.StringComparison))
{
if (!Directory.Exists(value))
{
throw new ArgumentException(SR.Format(SR.InvalidDirName, value));
}
_directory = value;
Restart();
}
}
}
/// <devdoc>
/// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is changed.
/// </devdoc>
public event FileSystemEventHandler Changed
{
add
{
_onChangedHandler += value;
}
remove
{
_onChangedHandler -= value;
}
}
/// <devdoc>
/// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is created.
/// </devdoc>
public event FileSystemEventHandler Created
{
add
{
_onCreatedHandler += value;
}
remove
{
_onCreatedHandler -= value;
}
}
/// <devdoc>
/// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is deleted.
/// </devdoc>
public event FileSystemEventHandler Deleted
{
add
{
_onDeletedHandler += value;
}
remove
{
_onDeletedHandler -= value;
}
}
/// <devdoc>
/// Occurs when the internal buffer overflows.
/// </devdoc>
public event ErrorEventHandler Error
{
add
{
_onErrorHandler += value;
}
remove
{
_onErrorHandler -= value;
}
}
/// <devdoc>
/// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/>
/// is renamed.
/// </devdoc>
public event RenamedEventHandler Renamed
{
add
{
_onRenamedHandler += value;
}
remove
{
_onRenamedHandler -= value;
}
}
/// <devdoc>
/// Disposes of the <see cref='System.IO.FileSystemWatcher'/>.
/// </devdoc>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <devdoc>
/// </devdoc>
protected virtual void Dispose(bool disposing)
{
try
{
if (disposing)
{
//Stop raising events cleans up managed and
//unmanaged resources.
StopRaisingEvents();
// Clean up managed resources
_onChangedHandler = null;
_onCreatedHandler = null;
_onDeletedHandler = null;
_onRenamedHandler = null;
_onErrorHandler = null;
}
else
{
FinalizeDispose();
}
}
finally
{
_disposed = true;
}
}
/// <devdoc>
/// Sees if the name given matches the name filter we have.
/// </devdoc>
/// <internalonly/>
private bool MatchPattern(string relativePath)
{
string name = System.IO.Path.GetFileName(relativePath);
return name != null ?
PatternMatcher.StrictMatchPattern(_filter, name) :
false;
}
/// <devdoc>
/// Raises the event to each handler in the list.
/// </devdoc>
/// <internalonly/>
private void NotifyInternalBufferOverflowEvent()
{
ErrorEventHandler handler = _onErrorHandler;
if (handler != null)
{
handler(this, new ErrorEventArgs(
new InternalBufferOverflowException(SR.Format(SR.FSW_BufferOverflow, _directory))));
}
}
/// <devdoc>
/// Raises the event to each handler in the list.
/// </devdoc>
/// <internalonly/>
private void NotifyRenameEventArgs(WatcherChangeTypes action, string name, string oldName)
{
// filter if there's no handler or neither new name or old name match a specified pattern
RenamedEventHandler handler = _onRenamedHandler;
if (handler != null &&
(MatchPattern(name) || MatchPattern(oldName)))
{
handler(this, new RenamedEventArgs(action, _directory, name, oldName));
}
}
/// <devdoc>
/// Raises the event to each handler in the list.
/// </devdoc>
/// <internalonly/>
private void NotifyFileSystemEventArgs(WatcherChangeTypes changeType, string name)
{
FileSystemEventHandler handler = null;
switch (changeType)
{
case WatcherChangeTypes.Created:
handler = _onCreatedHandler;
break;
case WatcherChangeTypes.Deleted:
handler = _onDeletedHandler;
break;
case WatcherChangeTypes.Changed:
handler = _onChangedHandler;
break;
default:
Debug.Fail("Unknown FileSystemEvent change type! Value: " + changeType);
break;
}
if (handler != null && MatchPattern(string.IsNullOrEmpty(name) ? _directory : name))
{
handler(this, new FileSystemEventArgs(changeType, _directory, name));
}
}
/// <devdoc>
/// Raises the <see cref='System.IO.FileSystemWatcher.Changed'/> event.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")]
protected void OnChanged(FileSystemEventArgs e)
{
FileSystemEventHandler changedHandler = _onChangedHandler;
if (changedHandler != null)
{
changedHandler(this, e);
}
}
/// <devdoc>
/// Raises the <see cref='System.IO.FileSystemWatcher.Created'/> event.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")]
protected void OnCreated(FileSystemEventArgs e)
{
FileSystemEventHandler createdHandler = _onCreatedHandler;
if (createdHandler != null)
{
createdHandler(this, e);
}
}
/// <devdoc>
/// Raises the <see cref='System.IO.FileSystemWatcher.Deleted'/> event.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")]
protected void OnDeleted(FileSystemEventArgs e)
{
FileSystemEventHandler deletedHandler = _onDeletedHandler;
if (deletedHandler != null)
{
deletedHandler(this, e);
}
}
/// <devdoc>
/// Raises the <see cref='System.IO.FileSystemWatcher.Error'/> event.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")]
protected void OnError(ErrorEventArgs e)
{
ErrorEventHandler errorHandler = _onErrorHandler;
if (errorHandler != null)
{
errorHandler(this, e);
}
}
/// <devdoc>
/// Raises the <see cref='System.IO.FileSystemWatcher.Renamed'/> event.
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")]
protected void OnRenamed(RenamedEventArgs e)
{
RenamedEventHandler renamedHandler = _onRenamedHandler;
if (renamedHandler != null)
{
renamedHandler(this, e);
}
}
/// <devdoc>
/// Stops and starts this object.
/// </devdoc>
/// <internalonly/>
private void Restart()
{
if (_enabled)
{
StopRaisingEvents();
StartRaisingEventsIfNotDisposed();
}
}
private void StartRaisingEventsIfNotDisposed()
{
//Cannot allocate the directoryHandle and the readBuffer if the object has been disposed; finalization has been suppressed.
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
StartRaisingEvents();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Interlocked = System.Threading.Interlocked;
#if ES_BUILD_STANDALONE
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
/// <summary>
/// TraceLogging: Used when calling EventSource.WriteMultiMerge.
/// Stores the type information to use when writing the event fields.
/// </summary>
public class TraceLoggingEventTypes
{
internal readonly TraceLoggingTypeInfo[] typeInfos;
internal readonly string name;
internal readonly EventTags tags;
internal readonly byte level;
internal readonly byte opcode;
internal readonly EventKeywords keywords;
internal readonly byte[] typeMetadata;
internal readonly int scratchSize;
internal readonly int dataCount;
internal readonly int pinCount;
private ConcurrentSet<KeyValuePair<string, EventTags>, NameInfo> nameInfos;
/// <summary>
/// Initializes a new instance of TraceLoggingEventTypes corresponding
/// to the name, flags, and types provided. Always uses the default
/// TypeInfo for each Type.
/// </summary>
/// <param name="name">
/// The name to use when the name parameter passed to
/// EventSource.Write is null. This value must not be null.
/// </param>
/// <param name="tags">
/// Tags to add to the event if the tags are not set via options.
/// </param>
/// <param name="types">
/// The types of the fields in the event. This value must not be null.
/// </param>
internal TraceLoggingEventTypes(
string name,
EventTags tags,
params Type[] types)
: this(tags, name, MakeArray(types))
{
return;
}
/// <summary>
/// Returns a new instance of TraceLoggingEventInfo corresponding to the name,
/// flags, and typeInfos provided.
/// </summary>
/// <param name="name">
/// The name to use when the name parameter passed to
/// EventSource.Write is null. This value must not be null.
/// </param>
/// <param name="tags">
/// Tags to add to the event if the tags are not set via options.
/// </param>
/// <param name="typeInfos">
/// The types of the fields in the event. This value must not be null.
/// </param>
/// <returns>
/// An instance of TraceLoggingEventInfo with DefaultName set to the specified name
/// and with the specified typeInfos.
/// </returns>
internal TraceLoggingEventTypes(
string name,
EventTags tags,
params TraceLoggingTypeInfo[] typeInfos)
: this(tags, name, MakeArray(typeInfos))
{
return;
}
internal TraceLoggingEventTypes(
string name,
EventTags tags,
System.Reflection.ParameterInfo[] paramInfos)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
this.typeInfos = MakeArray(paramInfos);
this.name = name;
this.tags = tags;
this.level = Statics.DefaultLevel;
var collector = new TraceLoggingMetadataCollector();
for (int i = 0; i < typeInfos.Length; ++i)
{
var typeInfo = typeInfos[i];
this.level = Statics.Combine((int)typeInfo.Level, this.level);
this.opcode = Statics.Combine((int)typeInfo.Opcode, this.opcode);
this.keywords |= typeInfo.Keywords;
var paramName = paramInfos[i].Name;
if (Statics.ShouldOverrideFieldName(paramName))
{
paramName = typeInfo.Name;
}
typeInfo.WriteMetadata(collector, paramName, EventFieldFormat.Default);
}
this.typeMetadata = collector.GetMetadata();
this.scratchSize = collector.ScratchSize;
this.dataCount = collector.DataCount;
this.pinCount = collector.PinCount;
}
private TraceLoggingEventTypes(
EventTags tags,
string defaultName,
TraceLoggingTypeInfo[] typeInfos)
{
if (defaultName == null)
{
throw new ArgumentNullException(nameof(defaultName));
}
this.typeInfos = typeInfos;
this.name = defaultName;
this.tags = tags;
this.level = Statics.DefaultLevel;
var collector = new TraceLoggingMetadataCollector();
foreach (var typeInfo in typeInfos)
{
this.level = Statics.Combine((int)typeInfo.Level, this.level);
this.opcode = Statics.Combine((int)typeInfo.Opcode, this.opcode);
this.keywords |= typeInfo.Keywords;
typeInfo.WriteMetadata(collector, null, EventFieldFormat.Default);
}
this.typeMetadata = collector.GetMetadata();
this.scratchSize = collector.ScratchSize;
this.dataCount = collector.DataCount;
this.pinCount = collector.PinCount;
}
/// <summary>
/// Gets the default name that will be used for events with this descriptor.
/// </summary>
internal string Name
{
get { return this.name; }
}
/// <summary>
/// Gets the default level that will be used for events with this descriptor.
/// </summary>
internal EventLevel Level
{
get { return (EventLevel)this.level; }
}
/// <summary>
/// Gets the default opcode that will be used for events with this descriptor.
/// </summary>
internal EventOpcode Opcode
{
get { return (EventOpcode)this.opcode; }
}
/// <summary>
/// Gets the default set of keywords that will added to events with this descriptor.
/// </summary>
internal EventKeywords Keywords
{
get { return (EventKeywords)this.keywords; }
}
/// <summary>
/// Gets the default tags that will be added events with this descriptor.
/// </summary>
internal EventTags Tags
{
get { return this.tags; }
}
internal NameInfo GetNameInfo(string name, EventTags tags)
{
var ret = this.nameInfos.TryGet(new KeyValuePair<string, EventTags>(name, tags));
if (ret == null)
{
ret = this.nameInfos.GetOrAdd(new NameInfo(name, tags, this.typeMetadata.Length));
}
return ret;
}
private TraceLoggingTypeInfo[] MakeArray(System.Reflection.ParameterInfo[] paramInfos)
{
if (paramInfos == null)
{
throw new ArgumentNullException(nameof(paramInfos));
}
var recursionCheck = new List<Type>(paramInfos.Length);
var result = new TraceLoggingTypeInfo[paramInfos.Length];
for (int i = 0; i < paramInfos.Length; ++i)
{
result[i] = TraceLoggingTypeInfo.GetInstance(paramInfos[i].ParameterType, recursionCheck);
}
return result;
}
private static TraceLoggingTypeInfo[] MakeArray(Type[] types)
{
if (types == null)
{
throw new ArgumentNullException(nameof(types));
}
var recursionCheck = new List<Type>(types.Length);
var result = new TraceLoggingTypeInfo[types.Length];
for (int i = 0; i < types.Length; i++)
{
result[i] = TraceLoggingTypeInfo.GetInstance(types[i], recursionCheck);
}
return result;
}
private static TraceLoggingTypeInfo[] MakeArray(
TraceLoggingTypeInfo[] typeInfos)
{
if (typeInfos == null)
{
throw new ArgumentNullException(nameof(typeInfos));
}
return (TraceLoggingTypeInfo[])typeInfos.Clone(); ;
}
}
}
| |
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("SqlStreamStore.Sqlite.Tests")]
namespace SqlStreamStore
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.Sqlite;
using SqlStreamStore.Infrastructure;
using SqlStreamStore.Logging;
using SqlStreamStore.Streams;
using SqlStreamStore.Subscriptions;
public partial class SqliteStreamStore : StreamStoreBase
{
private static readonly System.Collections.Concurrent.ConcurrentDictionary<string, string> _scripts = new ConcurrentDictionary<string, string>();
private static readonly Assembly s_assembly = typeof(SqliteStreamStore)
.GetTypeInfo()
.Assembly;
private readonly Lazy<IStreamStoreNotifier> _streamStoreNotifier;
private readonly SqliteStreamStoreSettings _settings;
private readonly Func<IEnumerable<StreamMessage>, ReadDirection, int, int> _resolveNextVersion;
public SqliteStreamStore(SqliteStreamStoreSettings settings)
: base(settings.MetadataMaxAgeCacheExpire,
settings.MetadataMaxAgeCacheMaxSize,
settings.GetUtcNow,
settings.LogName)
{
_settings = settings;
SqliteCommandExtensions.WithSettings(settings);
_streamStoreNotifier = new Lazy<IStreamStoreNotifier>(() =>
{
if(_settings.CreateStreamStoreNotifier == null)
{
throw new InvalidOperationException(
"Cannot create notifier because supplied createStreamStoreNotifier was null");
}
return settings.CreateStreamStoreNotifier.Invoke(this);
});
_resolveNextVersion = (messages, direction, currentVersion) =>
{
if(messages.Any())
{
var mVers = messages.Last().StreamVersion;
mVers = direction == ReadDirection.Forward
? mVers + 1
: mVers < StreamVersion.Start ? StreamVersion.Start : mVers - 1;
return mVers;
}
currentVersion = direction == ReadDirection.Forward
? currentVersion + 1
: currentVersion == StreamVersion.End ? StreamVersion.End : currentVersion - 1;
return currentVersion;
};
}
public SqliteStreamStore(Infrastructure.GetUtcNow getUtcNow, string logName) : base(getUtcNow, logName)
{
throw new NotSupportedException();
}
protected override async Task<long> ReadHeadPositionInternal(CancellationToken cancellationToken)
{
GuardAgainstDisposed();
cancellationToken.ThrowIfCancellationRequested();
using(var connection = OpenConnection())
{
return (await connection
.AllStream()
.HeadPosition(cancellationToken)) ?? Position.End;
}
}
protected override async Task<long> ReadStreamHeadPositionInternal(string streamId, CancellationToken cancellationToken)
{
GuardAgainstDisposed();
cancellationToken.ThrowIfCancellationRequested();
using(var connection = OpenConnection())
{
return (await connection
.Streams(streamId)
.StreamHeadPosition() ?? Position.End);
}
}
protected override async Task<int> ReadStreamHeadVersionInternal(string streamId, CancellationToken cancellationToken)
{
GuardAgainstDisposed();
cancellationToken.ThrowIfCancellationRequested();
using(var connection = OpenConnection())
{
return (await connection
.Streams(streamId)
.StreamHeadVersion() ?? StreamVersion.End);
}
}
internal void CreateSchemaIfNotExists()
{
using(var connection = OpenConnection(false))
using(var command = connection.CreateCommand())
{
command.CommandText = GetScript("Tables");
command.ExecuteNonQuery();
}
}
internal SqliteConnection OpenConnection(bool isReadOnly = true)
{
var connection = new SqliteConnection(_settings.GetConnectionString(isReadOnly));
connection.Open();
using(var command = connection.CreateCommand())
{
command.CommandText = @"PRAGMA foreign_keys = true;
PRAGMA journal_mode = WAL;";
command.ExecuteNonQuery();
}
// register functions.
connection.CreateFunction("split", (string source) => source.Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries));
connection.CreateFunction("contains",
(string allIdsBeingSought, string idToSeek) =>
{
var ids = allIdsBeingSought.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
return ids.Contains(idToSeek, StringComparer.OrdinalIgnoreCase);
});
return connection;
}
internal async Task TryScavengeAsync(string streamId, CancellationToken ct)
{
//RESEARCH: Is this valid?
if(streamId.Equals(SqliteStreamId.Deleted.Id) || streamId.StartsWith("$"))
{
return;
}
var deletedMessageIds = new List<Guid>();
using(var connection = OpenConnection(false))
using(var command = connection.CreateCommand())
{
long idInternal = 0;
long? maxCount = default;
command.CommandText = @"SELECT streams.id_internal, streams.max_count
FROM streams
WHERE streams.id_original = @streamId";
command.Parameters.Clear();
command.Parameters.AddWithValue("@streamId", streamId);
using(var reader = command.ExecuteReader())
{
if(reader.Read())
{
idInternal = reader.ReadScalar<long>(0, -1);
maxCount = reader.ReadScalar<long?>(1);
}
}
command.CommandText = @"SELECT COUNT(*)
FROM messages
WHERE messages.stream_id_internal = @idInternal;";
command.Parameters.Clear();
command.Parameters.AddWithValue("@idInternal", idInternal);
var streamLength = command.ExecuteScalar<long>(StreamVersion.Start);
var limit = streamLength - maxCount;
if(limit > 0)
{
// capture all messages that should be removed.
command.CommandText = @"SELECT messages.event_id
FROM messages
WHERE messages.stream_id_internal = @idInternal
ORDER BY messages.stream_version ASC
LIMIT @limit";
command.Parameters.Clear();
command.Parameters.AddWithValue("@idInternal", idInternal);
command.Parameters.AddWithValue("@limit", limit);
using(var reader = command.ExecuteReader())
{
while(reader.Read())
{
deletedMessageIds.Add(reader.ReadScalar(0, Guid.Empty));
}
}
}
}
Logger.Info(
"Found {deletedMessageIdCount} message(s) for stream {streamId} to scavenge.",
deletedMessageIds.Count,
streamId);
if(deletedMessageIds.Count > 0)
{
Logger.Debug(
"Scavenging the following messages on stream {streamId}: {deletedMessageIds}",
streamId,
deletedMessageIds);
foreach(var deletedMessageId in deletedMessageIds)
{
await DeleteEventInternal(streamId, deletedMessageId, ct).ConfigureAwait(false);
}
}
}
private string GetScript(string name) => _scripts.GetOrAdd(name,
key =>
{
var resourceNames = s_assembly.GetManifestResourceNames();
var resourceStreamName = $"{typeof(SqliteStreamStore).Namespace}.Scripts.{key}.sql";
using(var stream = s_assembly.GetManifestResourceStream(resourceStreamName))
{
if(stream == null)
{
throw new System.Exception($"Embedded resource, {name}, not found. BUG!");
}
using(System.IO.StreamReader reader = new System.IO.StreamReader(stream))
{
return reader
.ReadToEnd();
}
}
});
private int? ResolveInternalStreamId(string streamId, SqliteCommand cmd = null, bool throwIfNotExists = true)
{
int? PerformDelete(SqliteCommand command)
{
command.CommandText = "SELECT id_internal FROM streams WHERE id_original = @streamId";
command.Parameters.Clear();
command.Parameters.AddWithValue("@streamId", streamId);
var result = command.ExecuteScalar<int?>();
if(throwIfNotExists && result == null)
{
throw new Exception("Stream does not exist.");
}
return result;
}
if(cmd != null)
return PerformDelete(cmd);
using (var conn = OpenConnection(false))
using(var command = conn.CreateCommand())
{
return PerformDelete(command);
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*=============================================================================
**
** File: AssemblyAttributes
**
** <OWNER>[....]</OWNER>
**
**
** Purpose: For Assembly-related custom attributes.
**
**
=============================================================================*/
namespace System.Reflection {
using System;
using System.Configuration.Assemblies;
using System.Diagnostics.Contracts;
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyCopyrightAttribute : Attribute
{
private String m_copyright;
public AssemblyCopyrightAttribute(String copyright)
{
m_copyright = copyright;
}
public String Copyright
{
get { return m_copyright; }
}
}
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyTrademarkAttribute : Attribute
{
private String m_trademark;
public AssemblyTrademarkAttribute(String trademark)
{
m_trademark = trademark;
}
public String Trademark
{
get { return m_trademark; }
}
}
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyProductAttribute : Attribute
{
private String m_product;
public AssemblyProductAttribute(String product)
{
m_product = product;
}
public String Product
{
get { return m_product; }
}
}
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyCompanyAttribute : Attribute
{
private String m_company;
public AssemblyCompanyAttribute(String company)
{
m_company = company;
}
public String Company
{
get { return m_company; }
}
}
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyDescriptionAttribute : Attribute
{
private String m_description;
public AssemblyDescriptionAttribute(String description)
{
m_description = description;
}
public String Description
{
get { return m_description; }
}
}
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyTitleAttribute : Attribute
{
private String m_title;
public AssemblyTitleAttribute(String title)
{
m_title = title;
}
public String Title
{
get { return m_title; }
}
}
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyConfigurationAttribute : Attribute
{
private String m_configuration;
public AssemblyConfigurationAttribute(String configuration)
{
m_configuration = configuration;
}
public String Configuration
{
get { return m_configuration; }
}
}
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyDefaultAliasAttribute : Attribute
{
private String m_defaultAlias;
public AssemblyDefaultAliasAttribute(String defaultAlias)
{
m_defaultAlias = defaultAlias;
}
public String DefaultAlias
{
get { return m_defaultAlias; }
}
}
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyInformationalVersionAttribute : Attribute
{
private String m_informationalVersion;
public AssemblyInformationalVersionAttribute(String informationalVersion)
{
m_informationalVersion = informationalVersion;
}
public String InformationalVersion
{
get { return m_informationalVersion; }
}
}
[AttributeUsage(AttributeTargets.Assembly, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyFileVersionAttribute : Attribute
{
private String _version;
public AssemblyFileVersionAttribute(String version)
{
if (version == null)
throw new ArgumentNullException("version");
Contract.EndContractBlock();
_version = version;
}
public String Version {
get { return _version; }
}
}
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public unsafe sealed class AssemblyCultureAttribute : Attribute
{
private String m_culture;
public AssemblyCultureAttribute(String culture)
{
m_culture = culture;
}
public String Culture
{
get { return m_culture; }
}
}
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public unsafe sealed class AssemblyVersionAttribute : Attribute
{
private String m_version;
public AssemblyVersionAttribute(String version)
{
m_version = version;
}
public String Version
{
get { return m_version; }
}
}
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyKeyFileAttribute : Attribute
{
private String m_keyFile;
public AssemblyKeyFileAttribute(String keyFile)
{
m_keyFile = keyFile;
}
public String KeyFile
{
get { return m_keyFile; }
}
}
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyDelaySignAttribute : Attribute
{
private bool m_delaySign;
public AssemblyDelaySignAttribute(bool delaySign)
{
m_delaySign = delaySign;
}
public bool DelaySign
{ get
{ return m_delaySign; }
}
}
[AttributeUsage(AttributeTargets.Assembly, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public unsafe sealed class AssemblyAlgorithmIdAttribute : Attribute
{
private uint m_algId;
public AssemblyAlgorithmIdAttribute(AssemblyHashAlgorithm algorithmId)
{
m_algId = (uint) algorithmId;
}
[CLSCompliant(false)]
public AssemblyAlgorithmIdAttribute(uint algorithmId)
{
m_algId = algorithmId;
}
[CLSCompliant(false)]
public uint AlgorithmId
{
get { return m_algId; }
}
}
[AttributeUsage(AttributeTargets.Assembly, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public unsafe sealed class AssemblyFlagsAttribute : Attribute
{
private AssemblyNameFlags m_flags;
[Obsolete("This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
[CLSCompliant(false)]
public AssemblyFlagsAttribute(uint flags)
{
m_flags = (AssemblyNameFlags)flags;
}
[Obsolete("This property has been deprecated. Please use AssemblyFlags instead. http://go.microsoft.com/fwlink/?linkid=14202")]
[CLSCompliant(false)]
public uint Flags
{
get { return (uint)m_flags; }
}
// This, of course, should be typed as AssemblyNameFlags. The compat police don't allow such changes.
public int AssemblyFlags
{
get { return (int)m_flags; }
}
[Obsolete("This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public AssemblyFlagsAttribute(int assemblyFlags)
{
m_flags = (AssemblyNameFlags)assemblyFlags;
}
public AssemblyFlagsAttribute(AssemblyNameFlags assemblyFlags)
{
m_flags = assemblyFlags;
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true, Inherited=false)]
public sealed class AssemblyMetadataAttribute : Attribute
{
private String m_key;
private String m_value;
public AssemblyMetadataAttribute(string key, string value)
{
m_key = key;
m_value = value;
}
public string Key
{
get { return m_key; }
}
public string Value
{
get { return m_value;}
}
}
#if FEATURE_STRONGNAME_MIGRATION
[AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple=false)]
public sealed class AssemblySignatureKeyAttribute : Attribute
{
private String _publicKey;
private String _countersignature;
public AssemblySignatureKeyAttribute(String publicKey, String countersignature)
{
_publicKey = publicKey;
_countersignature = countersignature;
}
public String PublicKey
{
get { return _publicKey; }
}
public String Countersignature
{
get { return _countersignature; }
}
}
#endif
[AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyKeyNameAttribute : Attribute
{
private String m_keyName;
public AssemblyKeyNameAttribute(String keyName)
{
m_keyName = keyName;
}
public String KeyName
{
get { return m_keyName; }
}
}
}
| |
// 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.IdentityModel.Selectors;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.Text;
using System.Threading;
using Infrastructure.Common;
using Xunit;
public static class HttpsTests
{
// Client: CustomBinding set MessageVersion to Soap11
// Server: BasicHttpsBinding default value is Soap11
[Fact]
[OuterLoop]
public static void CrossBinding_Soap11_EchoString()
{
string variationDetails = "Client:: CustomBinding/MessageVersion=Soap11\nServer:: BasicHttpsBinding/DefaultValues";
string testString = "Hello";
StringBuilder errorBuilder = new StringBuilder();
bool success = false;
try
{
CustomBinding binding = new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8), new HttpsTransportBindingElement());
ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Https_DefaultBinding_Address));
IWcfService serviceProxy = factory.CreateChannel();
string result = serviceProxy.Echo(testString);
success = string.Equals(result, testString);
if (!success)
{
errorBuilder.AppendLine(String.Format(" Error: expected response from service: '{0}' Actual was: '{1}'", testString, result));
}
}
catch (Exception ex)
{
errorBuilder.AppendLine(String.Format(" Error: Unexpected exception was caught while doing the basic echo test for variation...\n'{0}'\nException: {1}", variationDetails, ex.ToString()));
for (Exception innerException = ex.InnerException; innerException != null; innerException = innerException.InnerException)
{
errorBuilder.AppendLine(String.Format("Inner exception: {0}", innerException.ToString()));
}
}
Assert.True(errorBuilder.Length == 0, "Test case FAILED with errors: " + errorBuilder.ToString());
}
// Client and Server bindings setup exactly the same using default settings.
[Fact]
[OuterLoop]
public static void SameBinding_DefaultSettings_EchoString()
{
string variationDetails = "Client:: CustomBinding/DefaultValues\nServer:: CustomBinding/DefaultValues";
string testString = "Hello";
StringBuilder errorBuilder = new StringBuilder();
bool success = false;
try
{
CustomBinding binding = new CustomBinding(new TextMessageEncodingBindingElement(), new HttpsTransportBindingElement());
ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpsSoap12_Address));
IWcfService serviceProxy = factory.CreateChannel();
string result = serviceProxy.Echo(testString);
success = string.Equals(result, testString);
if (!success)
{
errorBuilder.AppendLine(String.Format(" Error: expected response from service: '{0}' Actual was: '{1}'", testString, result));
}
}
catch (Exception ex)
{
errorBuilder.AppendLine(String.Format(" Error: Unexpected exception was caught while doing the basic echo test for variation...\n'{0}'\nException: {1}", variationDetails, ex.ToString()));
for (Exception innerException = ex.InnerException; innerException != null; innerException = innerException.InnerException)
{
errorBuilder.AppendLine(String.Format("Inner exception: {0}", innerException.ToString()));
}
}
Assert.True(errorBuilder.Length == 0, "Test case FAILED with errors: " + errorBuilder.ToString());
}
// Client and Server bindings setup exactly the same using Soap11
[Fact]
[OuterLoop]
public static void SameBinding_Soap11_EchoString()
{
string variationDetails = "Client:: CustomBinding/MessageVersion=Soap11\nServer:: CustomBinding/MessageVersion=Soap11";
string testString = "Hello";
StringBuilder errorBuilder = new StringBuilder();
bool success = false;
try
{
CustomBinding binding = new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8), new HttpsTransportBindingElement());
ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpsSoap11_Address));
IWcfService serviceProxy = factory.CreateChannel();
string result = serviceProxy.Echo(testString);
success = string.Equals(result, testString);
if (!success)
{
errorBuilder.AppendLine(String.Format(" Error: expected response from service: '{0}' Actual was: '{1}'", testString, result));
}
}
catch (Exception ex)
{
errorBuilder.AppendLine(String.Format(" Error: Unexpected exception was caught while doing the basic echo test for variation...\n'{0}'\nException: {1}", variationDetails, ex.ToString()));
for (Exception innerException = ex.InnerException; innerException != null; innerException = innerException.InnerException)
{
errorBuilder.AppendLine(String.Format("Inner exception: {0}", innerException.ToString()));
}
}
Assert.True(errorBuilder.Length == 0, "Test case FAILED with errors: " + errorBuilder.ToString());
}
// Client and Server bindings setup exactly the same using Soap12
[Fact]
[OuterLoop]
public static void SameBinding_Soap12_EchoString()
{
string variationDetails = "Client:: CustomBinding/MessageVersion=Soap12\nServer:: CustomBinding/MessageVersion=Soap12";
string testString = "Hello";
StringBuilder errorBuilder = new StringBuilder();
bool success = false;
try
{
CustomBinding binding = new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressing10, Encoding.UTF8), new HttpsTransportBindingElement());
ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpsSoap12_Address));
IWcfService serviceProxy = factory.CreateChannel();
string result = serviceProxy.Echo(testString);
success = string.Equals(result, testString);
if (!success)
{
errorBuilder.AppendLine(String.Format(" Error: expected response from service: '{0}' Actual was: '{1}'", testString, result));
}
}
catch (Exception ex)
{
errorBuilder.AppendLine(String.Format(" Error: Unexpected exception was caught while doing the basic echo test for variation...\n'{0}'\nException: {1}", variationDetails, ex.ToString()));
for (Exception innerException = ex.InnerException; innerException != null; innerException = innerException.InnerException)
{
errorBuilder.AppendLine(String.Format("Inner exception: {0}", innerException.ToString()));
}
}
Assert.True(errorBuilder.Length == 0, "Test case FAILED with errors: " + errorBuilder.ToString());
}
[Fact]
[ActiveIssue(544, PlatformID.AnyUnix)]
[OuterLoop]
public static void ServerCertificateValidation_EchoString()
{
string clientCertThumb = null;
EndpointAddress endpointAddress = null;
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
CustomBinding binding = new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8), new HttpsTransportBindingElement());
endpointAddress = new EndpointAddress(new Uri(Endpoints.Https_DefaultBinding_Address));
clientCertThumb = BridgeClientCertificateManager.LocalCertThumbprint; // ClientCert as given by the Bridge
factory = new ChannelFactory<IWcfService>(binding, endpointAddress);
factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom;
MyX509CertificateValidator myX509CertificateValidator = new MyX509CertificateValidator(ScenarioTestHelpers.CertificateIssuerName);
factory.Credentials.ServiceCertificate.Authentication.CustomCertificateValidator = myX509CertificateValidator;
factory.Credentials.ServiceCertificate.SslCertificateAuthentication = factory.Credentials.ServiceCertificate.Authentication;
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.True(myX509CertificateValidator.validateMethodWasCalled, "The Validate method of the X509CertificateValidator was NOT called.");
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
}
| |
// 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.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext;
using Microsoft.CodeAnalysis.Emit;
namespace Microsoft.Cci
{
internal sealed class PeWritingException : Exception
{
public PeWritingException(Exception inner)
: base(inner.Message, inner)
{ }
}
internal static class PeWriter
{
internal static bool WritePeToStream(
EmitContext context,
CommonMessageProvider messageProvider,
Func<Stream> getPeStream,
Func<Stream> getPortablePdbStreamOpt,
PdbWriter nativePdbWriterOpt,
string pdbPathOpt,
bool metadataOnly,
bool isDeterministic,
bool emitTestCoverageData,
CancellationToken cancellationToken)
{
// If PDB writer is given, we have to have PDB path.
Debug.Assert(nativePdbWriterOpt == null || pdbPathOpt != null);
var mdWriter = FullMetadataWriter.Create(context, messageProvider, metadataOnly, isDeterministic,
emitTestCoverageData, getPortablePdbStreamOpt != null, cancellationToken);
var properties = context.Module.SerializationProperties;
nativePdbWriterOpt?.SetMetadataEmitter(mdWriter);
// Since we are producing a full assembly, we should not have a module version ID
// imposed ahead-of time. Instead we will compute a deterministic module version ID
// based on the contents of the generated stream.
Debug.Assert(properties.PersistentIdentifier == default(Guid));
var ilBuilder = new BlobBuilder(32 * 1024);
var mappedFieldDataBuilder = new BlobBuilder();
var managedResourceBuilder = new BlobBuilder(1024);
Blob mvidFixup, mvidStringFixup;
mdWriter.BuildMetadataAndIL(
nativePdbWriterOpt,
ilBuilder,
mappedFieldDataBuilder,
managedResourceBuilder,
out mvidFixup,
out mvidStringFixup);
MethodDefinitionHandle entryPointHandle;
MethodDefinitionHandle debugEntryPointHandle;
mdWriter.GetEntryPoints(out entryPointHandle, out debugEntryPointHandle);
if (!debugEntryPointHandle.IsNil)
{
nativePdbWriterOpt?.SetEntryPoint((uint)MetadataTokens.GetToken(debugEntryPointHandle));
}
if (nativePdbWriterOpt != null)
{
if (context.Module.SourceLinkStreamOpt != null)
{
nativePdbWriterOpt.EmbedSourceLink(context.Module.SourceLinkStreamOpt);
}
if (mdWriter.Module.OutputKind == OutputKind.WindowsRuntimeMetadata)
{
// Dev12: If compiling to winmdobj, we need to add to PDB source spans of
// all types and members for better error reporting by WinMDExp.
nativePdbWriterOpt.WriteDefinitionLocations(mdWriter.Module.GetSymbolToLocationMap());
}
else
{
#if DEBUG
// validate that all definitions are writable
// if same scenario would happen in an winmdobj project
nativePdbWriterOpt.AssertAllDefinitionsHaveTokens(mdWriter.Module.GetSymbolToLocationMap());
#endif
}
// embedded text not currently supported for native PDB and we should have validated that
Debug.Assert(!mdWriter.Module.DebugDocumentsBuilder.EmbeddedDocuments.Any());
}
Stream peStream = getPeStream();
if (peStream == null)
{
return false;
}
BlobContentId pdbContentId = nativePdbWriterOpt?.GetContentId() ?? default(BlobContentId);
// the writer shall not be used after this point for writing:
nativePdbWriterOpt = null;
ushort portablePdbVersion = 0;
var metadataRootBuilder = mdWriter.GetRootBuilder();
var peHeaderBuilder = new PEHeaderBuilder(
machine: properties.Machine,
sectionAlignment: properties.SectionAlignment,
fileAlignment: properties.FileAlignment,
imageBase: properties.BaseAddress,
majorLinkerVersion: properties.LinkerMajorVersion,
minorLinkerVersion: properties.LinkerMinorVersion,
majorOperatingSystemVersion: 4,
minorOperatingSystemVersion: 0,
majorImageVersion: 0,
minorImageVersion: 0,
majorSubsystemVersion: properties.MajorSubsystemVersion,
minorSubsystemVersion: properties.MinorSubsystemVersion,
subsystem: properties.Subsystem,
dllCharacteristics: properties.DllCharacteristics,
imageCharacteristics: properties.ImageCharacteristics,
sizeOfStackReserve: properties.SizeOfStackReserve,
sizeOfStackCommit: properties.SizeOfStackCommit,
sizeOfHeapReserve: properties.SizeOfHeapReserve,
sizeOfHeapCommit: properties.SizeOfHeapCommit);
var deterministicIdProvider = isDeterministic ?
new Func<IEnumerable<Blob>, BlobContentId>(content => BlobContentId.FromHash(CryptographicHashProvider.ComputeSha1(content))) :
null;
BlobBuilder portablePdbToEmbed = null;
if (mdWriter.EmitStandaloneDebugMetadata)
{
mdWriter.AddRemainingEmbeddedDocuments(mdWriter.Module.DebugDocumentsBuilder.EmbeddedDocuments);
var portablePdbBlob = new BlobBuilder();
var portablePdbBuilder = mdWriter.GetPortablePdbBuilder(metadataRootBuilder.Sizes.RowCounts, debugEntryPointHandle, deterministicIdProvider);
pdbContentId = portablePdbBuilder.Serialize(portablePdbBlob);
portablePdbVersion = portablePdbBuilder.FormatVersion;
if (getPortablePdbStreamOpt == null)
{
// embed to debug directory:
portablePdbToEmbed = portablePdbBlob;
}
else
{
// write to Portable PDB stream:
Stream portablePdbStream = getPortablePdbStreamOpt();
if (portablePdbStream != null)
{
portablePdbBlob.WriteContentTo(portablePdbStream);
}
}
}
DebugDirectoryBuilder debugDirectoryBuilder;
if (pdbPathOpt != null || isDeterministic || portablePdbToEmbed != null)
{
debugDirectoryBuilder = new DebugDirectoryBuilder();
if (pdbPathOpt != null)
{
string paddedPath = isDeterministic ? pdbPathOpt : PadPdbPath(pdbPathOpt);
debugDirectoryBuilder.AddCodeViewEntry(paddedPath, pdbContentId, portablePdbVersion);
}
if (isDeterministic)
{
debugDirectoryBuilder.AddReproducibleEntry();
}
if (portablePdbToEmbed != null)
{
debugDirectoryBuilder.AddEmbeddedPortablePdbEntry(portablePdbToEmbed, portablePdbVersion);
}
}
else
{
debugDirectoryBuilder = null;
}
var peBuilder = new ExtendedPEBuilder(
peHeaderBuilder,
metadataRootBuilder,
ilBuilder,
mappedFieldDataBuilder,
managedResourceBuilder,
CreateNativeResourceSectionSerializer(context.Module),
debugDirectoryBuilder,
CalculateStrongNameSignatureSize(context.Module),
entryPointHandle,
properties.CorFlags,
deterministicIdProvider,
metadataOnly && !context.IncludePrivateMembers);
var peBlob = new BlobBuilder();
var peContentId = peBuilder.Serialize(peBlob, out Blob mvidSectionFixup);
PatchModuleVersionIds(mvidFixup, mvidSectionFixup, mvidStringFixup, peContentId.Guid);
try
{
peBlob.WriteContentTo(peStream);
}
catch (Exception e) when (!(e is OperationCanceledException))
{
throw new PeWritingException(e);
}
return true;
}
private static void PatchModuleVersionIds(Blob guidFixup, Blob guidSectionFixup, Blob stringFixup, Guid mvid)
{
if (!guidFixup.IsDefault)
{
var writer = new BlobWriter(guidFixup);
writer.WriteGuid(mvid);
Debug.Assert(writer.RemainingBytes == 0);
}
if (!guidSectionFixup.IsDefault)
{
var writer = new BlobWriter(guidSectionFixup);
writer.WriteGuid(mvid);
Debug.Assert(writer.RemainingBytes == 0);
}
if (!stringFixup.IsDefault)
{
var writer = new BlobWriter(stringFixup);
writer.WriteUserString(mvid.ToString());
Debug.Assert(writer.RemainingBytes == 0);
}
}
// Padding: We pad the path to this minimal size to
// allow some tools to patch the path without the need to rewrite the entire image.
// This is a workaround put in place until these tools are retired.
private static string PadPdbPath(string path)
{
const int minLength = 260;
return path + new string('\0', Math.Max(0, minLength - Encoding.UTF8.GetByteCount(path) - 1));
}
private static ResourceSectionBuilder CreateNativeResourceSectionSerializer(CommonPEModuleBuilder module)
{
// Win32 resources are supplied to the compiler in one of two forms, .RES (the output of the resource compiler),
// or .OBJ (the output of running cvtres.exe on a .RES file). A .RES file is parsed and processed into
// a set of objects implementing IWin32Resources. These are then ordered and the final image form is constructed
// and written to the resource section. Resources in .OBJ form are already very close to their final output
// form. Rather than reading them and parsing them into a set of objects similar to those produced by
// processing a .RES file, we process them like the native linker would, copy the relevant sections from
// the .OBJ into our output and apply some fixups.
var nativeResourceSectionOpt = module.Win32ResourceSection;
if (nativeResourceSectionOpt != null)
{
return new ResourceSectionBuilderFromObj(nativeResourceSectionOpt);
}
var nativeResourcesOpt = module.Win32Resources;
if (nativeResourcesOpt?.Any() == true)
{
return new ResourceSectionBuilderFromResources(nativeResourcesOpt);
}
return null;
}
private class ResourceSectionBuilderFromObj : ResourceSectionBuilder
{
private readonly ResourceSection _resourceSection;
public ResourceSectionBuilderFromObj(ResourceSection resourceSection)
{
Debug.Assert(resourceSection != null);
_resourceSection = resourceSection;
}
protected override void Serialize(BlobBuilder builder, SectionLocation location)
{
NativeResourceWriter.SerializeWin32Resources(builder, _resourceSection, location.RelativeVirtualAddress);
}
}
private class ResourceSectionBuilderFromResources : ResourceSectionBuilder
{
private readonly IEnumerable<IWin32Resource> _resources;
public ResourceSectionBuilderFromResources(IEnumerable<IWin32Resource> resources)
{
Debug.Assert(resources.Any());
_resources = resources;
}
protected override void Serialize(BlobBuilder builder, SectionLocation location)
{
NativeResourceWriter.SerializeWin32Resources(builder, _resources, location.RelativeVirtualAddress);
}
}
private static int CalculateStrongNameSignatureSize(CommonPEModuleBuilder module)
{
ISourceAssemblySymbolInternal assembly = module.SourceAssemblyOpt;
if (assembly == null)
{
return 0;
}
// EDMAURER the count of characters divided by two because the each pair of characters will turn in to one byte.
int keySize = (assembly.SignatureKey == null) ? 0 : assembly.SignatureKey.Length / 2;
if (keySize == 0)
{
keySize = assembly.Identity.PublicKey.Length;
}
if (keySize == 0)
{
return 0;
}
return (keySize < 128 + 32) ? 128 : keySize - 32;
}
}
}
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
function execEditorProfilesCS()
{
exec("./profiles.ed.cs");
}
$Gui::clipboardFile = expandFilename("./clipboard.gui");
singleton GuiControlProfile( GuiEditorClassProfile )
{
opaque = true;
fillColor = "232 232 232";
border = 1;
borderColor = "40 40 40 140";
borderColorHL = "127 127 127";
fontColor = "0 0 0";
fontColorHL = "50 50 50";
fixedExtent = true;
justify = "center";
bitmap = "core/art/gui/images/scrollBar";
hasBitmapArray = true;
category = "Editor";
};
singleton GuiControlProfile( GuiBackFillProfile )
{
opaque = true;
fillColor = "0 94 94";
border = true;
borderColor = "255 128 128";
fontType = "Arial";
fontSize = 12;
fontColor = "0 0 0";
fontColorHL = "50 50 50";
fixedExtent = true;
justify = "center";
category = "Editor";
};
singleton GuiControlProfile( GuiControlListPopupProfile )
{
opaque = true;
fillColor = "255 255 255";
fillColorHL = "204 203 202";
border = false;
//borderColor = "0 0 0";
fontColor = "0 0 0";
fontColorHL = "0 0 0";
fontColorNA = "50 50 50";
textOffset = "0 2";
autoSizeWidth = false;
autoSizeHeight = true;
tab = true;
canKeyFocus = true;
bitmap = "core/art/gui/images/scrollBar";
hasBitmapArray = true;
category = "Editor";
};
singleton GuiControlProfile( GuiSceneGraphEditProfile )
{
canKeyFocus = true;
tab = true;
category = "Editor";
};
singleton GuiControlProfile( GuiInspectorButtonProfile : GuiButtonProfile )
{
//border = 1;
justify = "Center";
category = "Editor";
};
singleton GuiControlProfile( GuiInspectorSwatchButtonProfile )
{
borderColor = "100 100 100 255";
borderColorNA = "200 200 200 255";
fillColorNA = "255 255 255 0";
borderColorHL = "0 0 0 255";
category = "Editor";
};
singleton GuiControlProfile( GuiInspectorTextEditProfile )
{
// Transparent Background
opaque = true;
fillColor = "0 0 0 0";
fillColorHL = "255 255 255";
// No Border (Rendered by field control)
border = false;
tab = true;
canKeyFocus = true;
// font
fontType = "Arial";
fontSize = 14;
fontColor = "0 0 0";
fontColorSEL = "43 107 206";
fontColorHL = "244 244 244";
fontColorNA = "100 100 100";
category = "Editor";
};
singleton GuiControlProfile( GuiDropdownTextEditProfile : GuiTextEditProfile )
{
bitmap = "core/art/gui/images/dropdown-textEdit";
category = "Editor";
};
singleton GuiControlProfile( GuiInspectorTextEditRightProfile : GuiInspectorTextEditProfile )
{
justify = "right";
category = "Editor";
};
singleton GuiControlProfile( GuiInspectorGroupProfile )
{
fontType = "Arial";
fontSize = "14";
fontColor = "0 0 0 150";
fontColorHL = "25 25 25 220";
fontColorNA = "128 128 128";
justify = "left";
opaque = false;
border = false;
bitmap = "tools/editorclasses/gui/images/rollout";
textOffset = "20 0";
category = "Editor";
};
singleton GuiControlProfile( GuiInspectorFieldProfile)
{
// fill color
opaque = false;
fillColor = "255 255 255";
fillColorHL = "204 203 202";
fillColorNA = "244 244 244";
// border color
border = false;
borderColor = "190 190 190";
borderColorHL = "156 156 156";
borderColorNA = "200 200 200";
//bevelColorHL = "255 255 255";
//bevelColorLL = "0 0 0";
// font
fontType = "Arial";
fontSize = 14;
fontColor = "32 32 32";
fontColorHL = "50 50 50";
fontColorNA = "190 190 190";
textOffset = "10 0";
tab = true;
canKeyFocus = true;
category = "Editor";
};
/*
singleton GuiControlProfile( GuiInspectorMultiFieldProfile : GuiInspectorFieldProfile )
{
opaque = true;
fillColor = "50 50 230 30";
};
*/
singleton GuiControlProfile( GuiInspectorMultiFieldDifferentProfile : GuiInspectorFieldProfile )
{
border = true;
borderColor = "190 100 100";
};
singleton GuiControlProfile( GuiInspectorDynamicFieldProfile : GuiInspectorFieldProfile )
{
// Transparent Background
opaque = true;
fillColor = "0 0 0 0";
fillColorHL = "255 255 255";
// No Border (Rendered by field control)
border = false;
tab = true;
canKeyFocus = true;
// font
fontType = "Arial";
fontSize = 14;
fontColor = "0 0 0";
fontColorSEL = "43 107 206";
fontColorHL = "244 244 244";
fontColorNA = "100 100 100";
category = "Editor";
};
singleton GuiControlProfile( GuiRolloutProfile )
{
border = 1;
borderColor = "200 200 200";
hasBitmapArray = true;
bitmap = "tools/editorClasses/gui/images/rollout";
textoffset = "17 0";
category = "Editor";
};
singleton GuiControlProfile( GuiInspectorRolloutProfile0 )
{
// font
fontType = "Arial";
fontSize = 14;
fontColor = "32 32 32";
fontColorHL = "32 100 100";
fontColorNA = "0 0 0";
justify = "left";
opaque = false;
border = 0;
borderColor = "190 190 190";
borderColorHL = "156 156 156";
borderColorNA = "64 64 64";
bitmap = "tools/editorclasses/gui/images/rollout_plusminus_header";
textOffset = "20 0";
category = "Editor";
};
singleton GuiControlProfile( GuiInspectorStackProfile )
{
opaque = false;
border = false;
category = "Editor";
};
singleton GuiControlProfile( GuiInspectorProfile : GuiInspectorFieldProfile )
{
opaque = true;
fillColor = "255 255 255 255";
border = 0;
cankeyfocus = true;
tab = true;
category = "Editor";
};
singleton GuiControlProfile( GuiInspectorInfoProfile : GuiInspectorFieldProfile )
{
opaque = true;
fillColor = "242 241 240";
border = 0;
cankeyfocus = true;
tab = true;
category = "Editor";
};
singleton GuiControlProfile( GuiInspectorBackgroundProfile : GuiInspectorFieldProfile )
{
border = 0;
cankeyfocus=true;
tab = true;
category = "Editor";
};
singleton GuiControlProfile( GuiInspectorTypeFileNameProfile )
{
// Transparent Background
opaque = false;
// No Border (Rendered by field control)
border = 0;
tab = true;
canKeyFocus = true;
// font
fontType = "Arial";
fontSize = 14;
// Center text
justify = "center";
fontColor = "32 32 32";
fontColorHL = "50 50 50";
fontColorNA = "0 0 0";
fillColor = "255 255 255";
fillColorHL = "204 203 202";
fillColorNA = "244 244 244";
borderColor = "190 190 190";
borderColorHL = "156 156 156";
borderColorNA = "64 64 64";
category = "Editor";
};
singleton GuiControlProfile( GuiInspectorColumnCtrlProfile : GuiInspectorFieldProfile )
{
opaque = true;
fillColor = "210 210 210";
border = 0;
category = "Editor";
};
singleton GuiControlProfile( InspectorTypeEnumProfile : GuiInspectorFieldProfile )
{
mouseOverSelected = true;
bitmap = "core/art/gui/images/scrollBar";
hasBitmapArray = true;
opaque=true;
border=true;
textOffset = "4 0";
category = "Editor";
};
singleton GuiControlProfile( InspectorTypeCheckboxProfile : GuiInspectorFieldProfile )
{
bitmap = "core/art/gui/images/checkBox";
hasBitmapArray = true;
opaque=false;
border=false;
textOffset = "4 0";
category = "Editor";
};
singleton GuiControlProfile( GuiToolboxButtonProfile : GuiButtonProfile )
{
justify = "center";
fontColor = "0 0 0";
border = 0;
textOffset = "0 0";
category = "Editor";
};
singleton GuiControlProfile( T2DDatablockDropDownProfile : GuiPopUpMenuProfile )
{
category = "Editor";
};
singleton GuiControlProfile( GuiDirectoryTreeProfile : GuiTreeViewProfile )
{
fontColor = "40 40 40";
fontColorSEL= "250 250 250 175";
fillColorHL = "0 60 150";
fontColorNA = "240 240 240";
fontType = "Arial";
fontSize = 14;
category = "Editor";
};
singleton GuiControlProfile( GuiDirectoryFileListProfile )
{
fontColor = "40 40 40";
fontColorSEL= "250 250 250 175";
fillColorHL = "0 60 150";
fontColorNA = "240 240 240";
fontType = "Arial";
fontSize = 14;
category = "Editor";
};
singleton GuiControlProfile( GuiDragAndDropProfile )
{
category = "Editor";
};
singleton GuiControlProfile( GuiInspectorFieldInfoPaneProfile )
{
opaque = false;
fillcolor = GuiInspectorBackgroundProfile.fillColor;
borderColor = GuiDefaultProfile.borderColor;
border = 1;
category = "Editor";
};
singleton GuiControlProfile( GuiInspectorFieldInfoMLTextProfile : GuiMLTextProfile )
{
opaque = false;
border = 0;
textOffset = "5 0";
category = "Editor";
};
singleton GuiControlProfile( GuiEditorScrollProfile )
{
opaque = true;
fillcolor = GuiInspectorBackgroundProfile.fillColor;
borderColor = GuiDefaultProfile.borderColor;
border = 1;
bitmap = "core/art/gui/images/scrollBar";
hasBitmapArray = true;
category = "Editor";
};
singleton GuiControlProfile( GuiCreatorIconButtonProfile )
{
opaque = true;
fillColor = "225 243 252 255";
fillColorHL = "225 243 252 0";
fillColorNA = "225 243 252 0";
fillColorSEL = "225 243 252 0";
//tab = true;
//canKeyFocus = true;
fontType = "Arial";
fontSize = 14;
fontColor = "0 0 0";
fontColorSEL = "43 107 206";
fontColorHL = "244 244 244";
fontColorNA = "100 100 100";
border = 1;
borderColor = "153 222 253 255";
borderColorHL = "156 156 156";
borderColorNA = "153 222 253 0";
//bevelColorHL = "255 255 255";
//bevelColorLL = "0 0 0";
category = "Editor";
};
| |
/// <summary>**************************************************************************
///
/// $Id: ICCProfile.java,v 1.1 2002/07/25 14:56:55 grosbois Exp $
///
/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650
/// $Date $
/// ***************************************************************************
/// </summary>
using System;
using System.Text;
using ParameterList = CSJ2K.j2k.util.ParameterList;
using DecoderSpecs = CSJ2K.j2k.decoder.DecoderSpecs;
using BitstreamReaderAgent = CSJ2K.j2k.codestream.reader.BitstreamReaderAgent;
using ColorSpace = CSJ2K.Color.ColorSpace;
using ColorSpaceException = CSJ2K.Color.ColorSpaceException;
using ICCProfileHeader = CSJ2K.Icc.Types.ICCProfileHeader;
using ICCTag = CSJ2K.Icc.Tags.ICCTag;
using ICCTagTable = CSJ2K.Icc.Tags.ICCTagTable;
using ICCCurveType = CSJ2K.Icc.Tags.ICCCurveType;
using ICCXYZType = CSJ2K.Icc.Tags.ICCXYZType;
using XYZNumber = CSJ2K.Icc.Types.XYZNumber;
using ICCProfileVersion = CSJ2K.Icc.Types.ICCProfileVersion;
using ICCDateTime = CSJ2K.Icc.Types.ICCDateTime;
using FileFormatBoxes = CSJ2K.j2k.fileformat.FileFormatBoxes;
using RandomAccessIO = CSJ2K.j2k.io.RandomAccessIO;
using FacilityManager = CSJ2K.j2k.util.FacilityManager;
using MsgLogger = CSJ2K.j2k.util.MsgLogger;
namespace CSJ2K.Icc
{
/// <summary> This class models the ICCProfile file. This file is a binary file which is divided
/// into two parts, an ICCProfileHeader followed by an ICCTagTable. The header is a
/// straightforward list of descriptive parameters such as profile size, version, date and various
/// more esoteric parameters. The tag table is a structured list of more complexly aggragated data
/// describing things such as ICC curves, copyright information, descriptive text blocks, etc.
///
/// Classes exist to model the header and tag table and their various constituent parts the developer
/// is refered to these for further information on the structure and contents of the header and tag table.
///
/// </summary>
/// <seealso cref="jj2000.j2k.icc.types.ICCProfileHeader">
/// </seealso>
/// <seealso cref="jj2000.j2k.icc.tags.ICCTagTable">
/// </seealso>
/// <version> 1.0
/// </version>
/// <author> Bruce A. Kern
/// </author>
public abstract class ICCProfile
{
private int ProfileSize
{
get
{
return header.dwProfileSize;
}
set
{
header.dwProfileSize = value;
}
}
private int CMMTypeSignature
{
get
{
return header.dwCMMTypeSignature;
}
set
{
header.dwCMMTypeSignature = value;
}
}
private int ProfileClass
{
get
{
return header.dwProfileClass;
}
set
{
header.dwProfileClass = value;
}
}
private int ColorSpaceType
{
get
{
return header.dwColorSpaceType;
}
set
{
header.dwColorSpaceType = value;
}
}
private int PCSType
{
get
{
return header.dwPCSType;
}
set
{
header.dwPCSType = value;
}
}
private int ProfileSignature
{
get
{
return header.dwProfileSignature;
}
set
{
header.dwProfileSignature = value;
}
}
private int PlatformSignature
{
get
{
return header.dwPlatformSignature;
}
set
{
header.dwPlatformSignature = value;
}
}
private int CMMFlags
{
get
{
return header.dwCMMFlags;
}
set
{
header.dwCMMFlags = value;
}
}
private int DeviceManufacturer
{
get
{
return header.dwDeviceManufacturer;
}
set
{
header.dwDeviceManufacturer = value;
}
}
private int DeviceModel
{
get
{
return header.dwDeviceModel;
}
set
{
header.dwDeviceModel = value;
}
}
private int DeviceAttributes1
{
get
{
return header.dwDeviceAttributes1;
}
set
{
header.dwDeviceAttributes1 = value;
}
}
private int DeviceAttributesReserved
{
get
{
return header.dwDeviceAttributesReserved;
}
set
{
header.dwDeviceAttributesReserved = value;
}
}
private int RenderingIntent
{
get
{
return header.dwRenderingIntent;
}
set
{
header.dwRenderingIntent = value;
}
}
private int CreatorSig
{
get
{
return header.dwCreatorSig;
}
set
{
header.dwCreatorSig = value;
}
}
private ICCProfileVersion ProfileVersion
{
get
{
return header.profileVersion;
}
set
{
header.profileVersion = value;
}
}
private XYZNumber PCSIlluminant
{
set
{
header.PCSIlluminant = value;
}
}
private ICCDateTime DateTime
{
set
{
header.dateTime = value;
}
}
/// <summary> Access the profile header</summary>
/// <returns> ICCProfileHeader
/// </returns>
virtual public ICCProfileHeader Header
{
get
{
return header;
}
}
/// <summary> Access the profile tag table</summary>
/// <returns> ICCTagTable
/// </returns>
virtual public ICCTagTable TagTable
{
get
{
return tags;
}
}
//UPGRADE_NOTE: Final was removed from the declaration of 'eol '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private static readonly System.String eol = System.Environment.NewLine;
/// <summary>Gray index. </summary>
// Renamed for convenience:
public const int GRAY = 0;
/// <summary>RGB index. </summary>
public const int RED = 0;
/// <summary>RGB index. </summary>
public const int GREEN = 1;
/// <summary>RGB index. </summary>
public const int BLUE = 2;
/// <summary>Size of native type </summary>
public const int boolean_size = 1;
/// <summary>Size of native type </summary>
public const int byte_size = 1;
/// <summary>Size of native type </summary>
public const int char_size = 2;
/// <summary>Size of native type </summary>
public const int short_size = 2;
/// <summary>Size of native type </summary>
public const int int_size = 4;
/// <summary>Size of native type </summary>
public const int float_size = 4;
/// <summary>Size of native type </summary>
public const int long_size = 8;
/// <summary>Size of native type </summary>
public const int double_size = 8;
/* Bit twiddling constant for integral types. */ public const int BITS_PER_BYTE = 8;
/* Bit twiddling constant for integral types. */ public const int BITS_PER_SHORT = 16;
/* Bit twiddling constant for integral types. */ public const int BITS_PER_INT = 32;
/* Bit twiddling constant for integral types. */ public const int BITS_PER_LONG = 64;
/* Bit twiddling constant for integral types. */ public const int BYTES_PER_SHORT = 2;
/* Bit twiddling constant for integral types. */ public const int BYTES_PER_INT = 4;
/* Bit twiddling constant for integral types. */ public const int BYTES_PER_LONG = 8;
/* JP2 Box structure analysis help */
[Serializable]
private class BoxType:System.Collections.Hashtable
{
private static System.Collections.Hashtable map = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable());
public static void put(int type, System.String desc)
{
map[(System.Int32) type] = desc;
}
public static System.String get_Renamed(int type)
{
return (System.String) map[(System.Int32) type];
}
public static System.String colorSpecMethod(int meth)
{
switch (meth)
{
case 2: return "Restricted ICC Profile";
case 1: return "Enumerated Color Space";
default: return "Undefined Color Spec Method";
}
}
static BoxType()
{
{
put(CSJ2K.j2k.fileformat.FileFormatBoxes.BITS_PER_COMPONENT_BOX, "BITS_PER_COMPONENT_BOX");
put(CSJ2K.j2k.fileformat.FileFormatBoxes.CAPTURE_RESOLUTION_BOX, "CAPTURE_RESOLUTION_BOX");
put(CSJ2K.j2k.fileformat.FileFormatBoxes.CHANNEL_DEFINITION_BOX, "CHANNEL_DEFINITION_BOX");
put(CSJ2K.j2k.fileformat.FileFormatBoxes.COLOUR_SPECIFICATION_BOX, "COLOUR_SPECIFICATION_BOX");
put(CSJ2K.j2k.fileformat.FileFormatBoxes.COMPONENT_MAPPING_BOX, "COMPONENT_MAPPING_BOX");
put(CSJ2K.j2k.fileformat.FileFormatBoxes.CONTIGUOUS_CODESTREAM_BOX, "CONTIGUOUS_CODESTREAM_BOX");
put(CSJ2K.j2k.fileformat.FileFormatBoxes.DEFAULT_DISPLAY_RESOLUTION_BOX, "DEFAULT_DISPLAY_RESOLUTION_BOX");
put(CSJ2K.j2k.fileformat.FileFormatBoxes.FILE_TYPE_BOX, "FILE_TYPE_BOX");
put(CSJ2K.j2k.fileformat.FileFormatBoxes.IMAGE_HEADER_BOX, "IMAGE_HEADER_BOX");
put(CSJ2K.j2k.fileformat.FileFormatBoxes.INTELLECTUAL_PROPERTY_BOX, "INTELLECTUAL_PROPERTY_BOX");
put(CSJ2K.j2k.fileformat.FileFormatBoxes.JP2_HEADER_BOX, "JP2_HEADER_BOX");
put(CSJ2K.j2k.fileformat.FileFormatBoxes.JP2_SIGNATURE_BOX, "JP2_SIGNATURE_BOX");
put(CSJ2K.j2k.fileformat.FileFormatBoxes.PALETTE_BOX, "PALETTE_BOX");
put(CSJ2K.j2k.fileformat.FileFormatBoxes.RESOLUTION_BOX, "RESOLUTION_BOX");
put(CSJ2K.j2k.fileformat.FileFormatBoxes.URL_BOX, "URL_BOX");
put(CSJ2K.j2k.fileformat.FileFormatBoxes.UUID_BOX, "UUID_BOX");
put(CSJ2K.j2k.fileformat.FileFormatBoxes.UUID_INFO_BOX, "UUID_INFO_BOX");
put(CSJ2K.j2k.fileformat.FileFormatBoxes.UUID_LIST_BOX, "UUID_LIST_BOX");
put(CSJ2K.j2k.fileformat.FileFormatBoxes.XML_BOX, "XML_BOX");
}
}
}
/// <summary> Creates an int from a 4 character String</summary>
/// <param name="fourChar">string representation of an integer
/// </param>
/// <returns> the integer which is denoted by the input String.
/// </returns>
public static int getIntFromString(System.String fourChar)
{
byte[] bytes = SupportClass.ToByteArray(fourChar);
return getInt(bytes, 0);
}
/// <summary> Create an XYZNumber from byte [] input</summary>
/// <param name="data">array containing the XYZNumber representation
/// </param>
/// <param name="offset">start of the rep in the array
/// </param>
/// <returns> the created XYZNumber
/// </returns>
public static XYZNumber getXYZNumber(byte[] data, int offset)
{
int x, y, z;
x = ICCProfile.getInt(data, offset);
y = ICCProfile.getInt(data, offset + int_size);
z = ICCProfile.getInt(data, offset + 2 * int_size);
return new XYZNumber(x, y, z);
}
/// <summary> Create an ICCProfileVersion from byte [] input</summary>
/// <param name="data">array containing the ICCProfileVersion representation
/// </param>
/// <param name="offset">start of the rep in the array
/// </param>
/// <returns> the created ICCProfileVersion
/// </returns>
public static ICCProfileVersion getICCProfileVersion(byte[] data, int offset)
{
byte major = data[offset];
byte minor = data[offset + byte_size];
byte resv1 = data[offset + 2 * byte_size];
byte resv2 = data[offset + 3 * byte_size];
return new ICCProfileVersion(major, minor, resv1, resv2);
}
/// <summary> Create an ICCDateTime from byte [] input</summary>
/// <param name="data">array containing the ICCProfileVersion representation
/// </param>
/// <param name="offset">start of the rep in the array
/// </param>
/// <returns> the created ICCProfileVersion
/// </returns>
public static ICCDateTime getICCDateTime(byte[] data, int offset)
{
short wYear = ICCProfile.getShort(data, offset); // Number of the actual year (i.e. 1994)
short wMonth = ICCProfile.getShort(data, offset + ICCProfile.short_size); // Number of the month (1-12)
short wDay = ICCProfile.getShort(data, offset + 2 * ICCProfile.short_size); // Number of the day
short wHours = ICCProfile.getShort(data, offset + 3 * ICCProfile.short_size); // Number of hours (0-23)
short wMinutes = ICCProfile.getShort(data, offset + 4 * ICCProfile.short_size); // Number of minutes (0-59)
short wSeconds = ICCProfile.getShort(data, offset + 5 * ICCProfile.short_size); // Number of seconds (0-59)
return new ICCDateTime(wYear, wMonth, wDay, wHours, wMinutes, wSeconds);
}
/// <summary> Create a String from a byte []. Optionally swap adjacent byte
/// pairs. Intended to be used to create integer String representations
/// allowing for endian translations.
/// </summary>
/// <param name="bfr">data array
/// </param>
/// <param name="offset">start of data in array
/// </param>
/// <param name="length">length of data in array
/// </param>
/// <param name="swap">swap adjacent bytes?
/// </param>
/// <returns> String rep of data
/// </returns>
public static System.String getString(byte[] bfr, int offset, int length, bool swap)
{
byte[] result = new byte[length];
int incr = swap?- 1:1;
int start = swap?offset + length - 1:offset;
for (int i = 0, j = start; i < length; ++i)
{
result[i] = bfr[j];
j += incr;
}
return new System.String(SupportClass.ToCharArray(result));
}
/// <summary> Create a short from a two byte [], with optional byte swapping.</summary>
/// <param name="bfr">data array
/// </param>
/// <param name="off">start of data in array
/// </param>
/// <param name="swap">swap bytes?
/// </param>
/// <returns> native type from representation.
/// </returns>
public static short getShort(byte[] bfr, int off, bool swap)
{
int tmp0 = bfr[off] & 0xff; // Clear the sign extended bits in the int.
int tmp1 = bfr[off + 1] & 0xff;
return (short) (swap?(tmp1 << BITS_PER_BYTE | tmp0):(tmp0 << BITS_PER_BYTE | tmp1));
}
/// <summary> Create a short from a two byte [].</summary>
/// <param name="bfr">data array
/// </param>
/// <param name="off">start of data in array
/// </param>
/// <returns> native type from representation.
/// </returns>
public static short getShort(byte[] bfr, int off)
{
int tmp0 = bfr[off] & 0xff; // Clear the sign extended bits in the int.
int tmp1 = bfr[off + 1] & 0xff;
return (short) (tmp0 << BITS_PER_BYTE | tmp1);
}
/// <summary> Separate bytes in an int into a byte array lsb to msb order.</summary>
/// <param name="d">integer to separate
/// </param>
/// <returns> byte [] containing separated int.
/// </returns>
public static byte[] setInt(int d)
{
return setInt(d, new byte[BYTES_PER_INT]);
}
/// <summary> Separate bytes in an int into a byte array lsb to msb order.
/// Return the result in the provided array
/// </summary>
/// <param name="d">integer to separate
/// </param>
/// <param name="b">return output here.
/// </param>
/// <returns> reference to output.
/// </returns>
public static byte[] setInt(int d, byte[] b)
{
if (b == null)
b = new byte[BYTES_PER_INT];
for (int i = 0; i < BYTES_PER_INT; ++i)
{
b[i] = (byte) (d & 0x0ff);
d = d >> BITS_PER_BYTE;
}
return b;
}
/// <summary> Separate bytes in a long into a byte array lsb to msb order.</summary>
/// <param name="d">long to separate
/// </param>
/// <returns> byte [] containing separated int.
/// </returns>
public static byte[] setLong(long d)
{
return setLong(d, new byte[BYTES_PER_INT]);
}
/// <summary> Separate bytes in a long into a byte array lsb to msb order.
/// Return the result in the provided array
/// </summary>
/// <param name="d">long to separate
/// </param>
/// <param name="b">return output here.
/// </param>
/// <returns> reference to output.
/// </returns>
public static byte[] setLong(long d, byte[] b)
{
if (b == null)
b = new byte[BYTES_PER_LONG];
for (int i = 0; i < BYTES_PER_LONG; ++i)
{
b[i] = (byte) (d & 0x0ff);
d = d >> BITS_PER_BYTE;
}
return b;
}
/// <summary> Create an int from a byte [4], with optional byte swapping.</summary>
/// <param name="bfr">data array
/// </param>
/// <param name="off">start of data in array
/// </param>
/// <param name="swap">swap bytes?
/// </param>
/// <returns> native type from representation.
/// </returns>
public static int getInt(byte[] bfr, int off, bool swap)
{
int tmp0 = getShort(bfr, off, swap) & 0xffff; // Clear the sign extended bits in the int.
int tmp1 = getShort(bfr, off + 2, swap) & 0xffff;
return (int) (swap?(tmp1 << BITS_PER_SHORT | tmp0):(tmp0 << BITS_PER_SHORT | tmp1));
}
/// <summary> Create an int from a byte [4].</summary>
/// <param name="bfr">data array
/// </param>
/// <param name="off">start of data in array
/// </param>
/// <returns> native type from representation.
/// </returns>
public static int getInt(byte[] bfr, int off)
{
int tmp0 = getShort(bfr, off) & 0xffff; // Clear the sign extended bits in the int.
int tmp1 = getShort(bfr, off + 2) & 0xffff;
return (int) (tmp0 << BITS_PER_SHORT | tmp1);
}
/// <summary> Create an long from a byte [8].</summary>
/// <param name="bfr">data array
/// </param>
/// <param name="off">start of data in array
/// </param>
/// <returns> native type from representation.
/// </returns>
public static long getLong(byte[] bfr, int off)
{
long tmp0 = getInt(bfr, off) & unchecked((int) 0xffffffff); // Clear the sign extended bits in the int.
long tmp1 = getInt(bfr, off + 4) & unchecked((int) 0xffffffff);
return (long) (tmp0 << BITS_PER_INT | tmp1);
}
/// <summary>signature </summary>
// Define the set of standard signature and type values
// Because of the endian issues and byte swapping, the profile codes must
// be stored in memory and be addressed by address. As such, only those
// codes required for Restricted ICC use are defined here
//UPGRADE_NOTE: Final was removed from the declaration of 'kdwProfileSignature '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int kdwProfileSignature;
/// <summary>signature </summary>
//UPGRADE_NOTE: Final was removed from the declaration of 'kdwProfileSigReverse '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int kdwProfileSigReverse;
/// <summary>profile type </summary>
//UPGRADE_NOTE: Final was removed from the declaration of 'kdwInputProfile '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int kdwInputProfile;
/// <summary>tag type </summary>
//UPGRADE_NOTE: Final was removed from the declaration of 'kdwDisplayProfile '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int kdwDisplayProfile;
/// <summary>tag type </summary>
//UPGRADE_NOTE: Final was removed from the declaration of 'kdwRGBData '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int kdwRGBData;
/// <summary>tag type </summary>
//UPGRADE_NOTE: Final was removed from the declaration of 'kdwGrayData '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int kdwGrayData;
/// <summary>tag type </summary>
//UPGRADE_NOTE: Final was removed from the declaration of 'kdwXYZData '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int kdwXYZData;
/// <summary>input type </summary>
public const int kMonochromeInput = 0;
/// <summary>input type </summary>
public const int kThreeCompInput = 1;
/// <summary>tag signature </summary>
//UPGRADE_NOTE: Final was removed from the declaration of 'kdwGrayTRCTag '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int kdwGrayTRCTag;
/// <summary>tag signature </summary>
//UPGRADE_NOTE: Final was removed from the declaration of 'kdwRedColorantTag '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int kdwRedColorantTag;
/// <summary>tag signature </summary>
//UPGRADE_NOTE: Final was removed from the declaration of 'kdwGreenColorantTag '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int kdwGreenColorantTag;
/// <summary>tag signature </summary>
//UPGRADE_NOTE: Final was removed from the declaration of 'kdwBlueColorantTag '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int kdwBlueColorantTag;
/// <summary>tag signature </summary>
//UPGRADE_NOTE: Final was removed from the declaration of 'kdwRedTRCTag '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int kdwRedTRCTag;
/// <summary>tag signature </summary>
//UPGRADE_NOTE: Final was removed from the declaration of 'kdwGreenTRCTag '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int kdwGreenTRCTag;
/// <summary>tag signature </summary>
//UPGRADE_NOTE: Final was removed from the declaration of 'kdwBlueTRCTag '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int kdwBlueTRCTag;
/// <summary>tag signature </summary>
//UPGRADE_NOTE: Final was removed from the declaration of 'kdwCopyrightTag '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int kdwCopyrightTag;
/// <summary>tag signature </summary>
//UPGRADE_NOTE: Final was removed from the declaration of 'kdwMediaWhiteTag '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int kdwMediaWhiteTag;
/// <summary>tag signature </summary>
//UPGRADE_NOTE: Final was removed from the declaration of 'kdwProfileDescTag '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int kdwProfileDescTag;
private ICCProfileHeader header = null;
private ICCTagTable tags = null;
private byte[] profile = null;
//private byte[] data = null;
private ParameterList pl = null;
private ICCProfile()
{
throw new ICCProfileException("illegal to invoke empty constructor");
}
/// <summary> ParameterList constructor </summary>
/// <param name="csb">provides colorspace information
/// </param>
protected internal ICCProfile(ColorSpace csm)
{
this.pl = csm.pl;
profile = csm.ICCProfile;
initProfile(profile);
}
/// <summary> Read the header and tags into memory and verify
/// that the correct type of profile is being used. for encoding.
/// </summary>
/// <param name="data">ICCProfile
/// </param>
/// <exception cref="ICCProfileInvalidException">for bad signature and class and bad type
/// </exception>
private void initProfile(byte[] data)
{
header = new ICCProfileHeader(data);
tags = ICCTagTable.createInstance(data);
// Verify that the data pointed to by icc is indeed a valid profile
// and that it is possibly of one of the Restricted ICC types. The simplest way to check
// this is to verify that the profile signature is correct, that it is an input profile,
// and that the PCS used is XYX.
// However, a common error in profiles will be to create Monitor profiles rather
// than input profiles. If this is the only error found, it's still useful to let this
// go through with an error written to stderr.
if (ProfileClass == kdwDisplayProfile)
{
System.String message = "NOTE!! Technically, this profile is a Display profile, not an" + " Input Profile, and thus is not a valid Restricted ICC profile." + " However, it is quite possible that this profile is usable as" + " a Restricted ICC profile, so this code will ignore this state" + " and proceed with processing.";
FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, message);
}
if ((ProfileSignature != kdwProfileSignature) || ((ProfileClass != kdwInputProfile) && (ProfileClass != kdwDisplayProfile)) || (PCSType != kdwXYZData))
{
throw new ICCProfileInvalidException();
}
}
/// <summary>Provide a suitable string representation for the class </summary>
public override System.String ToString()
{
System.Text.StringBuilder rep = new System.Text.StringBuilder("[ICCProfile:");
System.Text.StringBuilder body = new System.Text.StringBuilder();
body.Append(eol).Append(header);
body.Append(eol).Append(eol).Append(tags);
rep.Append(ColorSpace.indent(" ", body));
return rep.Append("]").ToString();
}
/// <summary> Create a two character hex representation of a byte</summary>
/// <param name="i">byte to represent
/// </param>
/// <returns> representation
/// </returns>
public static System.String toHexString(byte i)
{
System.String rep = (i >= 0 && i < 16?"0":"") + System.Convert.ToString((int) i, 16);
if (rep.Length > 2)
rep = rep.Substring(rep.Length - 2);
return rep;
}
/// <summary> Create a 4 character hex representation of a short</summary>
/// <param name="i">short to represent
/// </param>
/// <returns> representation
/// </returns>
public static System.String toHexString(short i)
{
System.String rep;
if (i >= 0 && i < 0x10)
rep = "000" + System.Convert.ToString((int) i, 16);
else if (i >= 0 && i < 0x100)
rep = "00" + System.Convert.ToString((int) i, 16);
else if (i >= 0 && i < 0x1000)
rep = "0" + System.Convert.ToString((int) i, 16);
else
rep = "" + System.Convert.ToString((int) i, 16);
if (rep.Length > 4)
rep = rep.Substring(rep.Length - 4);
return rep;
}
/// <summary> Create a 8 character hex representation of a int</summary>
/// <param name="i">int to represent
/// </param>
/// <returns> representation
/// </returns>
public static System.String toHexString(int i)
{
System.String rep;
if (i >= 0 && i < 0x10)
rep = "0000000" + System.Convert.ToString((int) i, 16);
else if (i >= 0 && i < 0x100)
rep = "000000" + System.Convert.ToString((int) i, 16);
else if (i >= 0 && i < 0x1000)
rep = "00000" + System.Convert.ToString((int) i, 16);
else if (i >= 0 && i < 0x10000)
rep = "0000" + System.Convert.ToString((int) i, 16);
else if (i >= 0 && i < 0x100000)
rep = "000" + System.Convert.ToString((int) i, 16);
else if (i >= 0 && i < 0x1000000)
rep = "00" + System.Convert.ToString((int) i, 16);
else if (i >= 0 && i < 0x10000000)
rep = "0" + System.Convert.ToString((int) i, 16);
else
rep = "" + System.Convert.ToString((int) i, 16);
if (rep.Length > 8)
rep = rep.Substring(rep.Length - 8);
return rep;
}
public static System.String ToString(byte[] data)
{
int i, row, col, rem, rows, cols;
System.Text.StringBuilder rep = new System.Text.StringBuilder();
System.Text.StringBuilder rep0 = null;
System.Text.StringBuilder rep1 = null;
System.Text.StringBuilder rep2 = null;
cols = 16;
rows = data.Length / cols;
rem = data.Length % cols;
byte[] lbytes = new byte[8];
for (row = 0, i = 0; row < rows; ++row)
{
rep1 = new System.Text.StringBuilder();
rep2 = new System.Text.StringBuilder();
for (i = 0; i < 8; ++i)
lbytes[i] = 0;
byte[] tbytes = System.Text.ASCIIEncoding.ASCII.GetBytes(System.Convert.ToString(row * 16, 16));
for (int t = 0, l = lbytes.Length - tbytes.Length; t < tbytes.Length; ++l, ++t)
lbytes[l] = tbytes[t];
rep0 = new System.Text.StringBuilder(new System.String(SupportClass.ToCharArray(lbytes)));
for (col = 0; col < cols; ++col)
{
byte b = data[i++];
rep1.Append(toHexString(b)).Append(i % 2 == 0?" ":"");
if ((System.Char.IsLetter((char) b) || ((char) b).CompareTo('$') == 0 || ((char) b).CompareTo('_') == 0))
rep2.Append((char) b);
else
rep2.Append(".");
}
rep.Append(rep0).Append(" : ").Append(rep1).Append(": ").Append(rep2).Append(eol);
}
rep1 = new System.Text.StringBuilder();
rep2 = new System.Text.StringBuilder();
for (i = 0; i < 8; ++i)
lbytes[i] = 0;
byte[] tbytes2 = System.Text.ASCIIEncoding.ASCII.GetBytes(System.Convert.ToString(row * 16, 16));
for (int t = 0, l = lbytes.Length - tbytes2.Length; t < tbytes2.Length; ++l, ++t)
lbytes[l] = tbytes2[t];
rep0 = new System.Text.StringBuilder(System.Text.ASCIIEncoding.ASCII.GetString(lbytes));
for (col = 0; col < rem; ++col)
{
byte b = data[i++];
rep1.Append(toHexString(b)).Append(i % 2 == 0?" ":"");
if ((System.Char.IsLetter((char) b) || ((char) b).CompareTo('$') == 0 || ((char) b).CompareTo('_') == 0))
rep2.Append((char) b);
else
rep2.Append(".");
}
for (col = rem; col < 16; ++col)
rep1.Append(" ").Append(col % 2 == 0?" ":"");
rep.Append(rep0).Append(" : ").Append(rep1).Append(": ").Append(rep2).Append(eol);
return rep.ToString();
}
/// <summary> Parse this ICCProfile into a RestrictedICCProfile
/// which is appropriate to the data in this profile.
/// Either a MonochromeInputRestrictedProfile or
/// MatrixBasedRestrictedProfile is returned
/// </summary>
/// <returns> RestrictedICCProfile
/// </returns>
/// <exception cref="ICCProfileInvalidException">no curve data
/// </exception>
public virtual RestrictedICCProfile parse()
{
// The next step is to determine which Restricted ICC type is used by this profile.
// Unfortunately, the only way to do this is to look through the tag table for
// the tags required by the two types.
// First look for the gray TRC tag. If the profile is indeed an input profile, and this
// tag exists, then the profile is a Monochrome Input profile
ICCCurveType grayTag = (ICCCurveType) tags[(System.Int32) kdwGrayTRCTag];
if (grayTag != null)
{
return RestrictedICCProfile.createInstance(grayTag);
}
// If it wasn't a Monochrome Input profile, look for the Red Colorant tag. If that
// tag is found and the profile is indeed an input profile, then this profile is
// a Three-Component Matrix-Based Input profile
ICCCurveType rTRCTag = (ICCCurveType) tags[(System.Int32) kdwRedTRCTag];
if (rTRCTag != null)
{
ICCCurveType gTRCTag = (ICCCurveType) tags[(System.Int32) kdwGreenTRCTag];
ICCCurveType bTRCTag = (ICCCurveType) tags[(System.Int32) kdwBlueTRCTag];
ICCXYZType rColorantTag = (ICCXYZType) tags[(System.Int32) kdwRedColorantTag];
ICCXYZType gColorantTag = (ICCXYZType) tags[(System.Int32) kdwGreenColorantTag];
ICCXYZType bColorantTag = (ICCXYZType) tags[(System.Int32) kdwBlueColorantTag];
return RestrictedICCProfile.createInstance(rTRCTag, gTRCTag, bTRCTag, rColorantTag, gColorantTag, bColorantTag);
}
throw new ICCProfileInvalidException("curve data not found in profile");
}
/// <summary> Output this ICCProfile to a RandomAccessFile</summary>
/// <param name="os">output file
/// </param>
//UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'"
public virtual void write(System.IO.FileStream os)
{
Header.write(os);
TagTable.write(os);
}
/* end class ICCProfile */
static ICCProfile()
{
kdwProfileSignature = GetTagInt("acsp");
kdwProfileSigReverse = GetTagInt("psca");
kdwInputProfile = GetTagInt("scnr");
kdwDisplayProfile = GetTagInt("mntr");
kdwRGBData = GetTagInt("RGB ");
kdwGrayData = GetTagInt("GRAY");
kdwXYZData = GetTagInt("XYZ ");
kdwGrayTRCTag = GetTagInt("kTRC");
kdwRedColorantTag = GetTagInt("rXYZ");
kdwGreenColorantTag = GetTagInt("gXYZ");
kdwBlueColorantTag = GetTagInt("bXYZ");
kdwRedTRCTag = GetTagInt("rTRC");
kdwGreenTRCTag = GetTagInt("gTRC");
kdwBlueTRCTag = GetTagInt("bTRC");
kdwCopyrightTag = GetTagInt("cprt");
kdwMediaWhiteTag = GetTagInt("wtpt");
kdwProfileDescTag = GetTagInt("desc");
}
static int GetTagInt(string tag)
{
byte[] tagBytes = ASCIIEncoding.ASCII.GetBytes(tag);
Array.Reverse(tagBytes);
return BitConverter.ToInt32(tagBytes, 0);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.