示例#1
0
        public bool Bypass(HttpSession <Application> session, Request req, RequestResponse rr)
        {
            string url        = req.Url;
            string baseUrl    = url.EndsWith("/") ? StringFunc.Substring(url, 0, url.Length - 1) : url;
            string domainName = baseUrl.Split("/")[2];

            string resolveUrl = ResolveUrl(rr.GetAsDoc(), domainName, baseUrl);

            if (string.IsNullOrEmpty(resolveUrl))
            {
                return(false);
            }
            Misc.Sleep(5500);

            rr = session.DispatchRequest(new GetRequest(resolveUrl));

            if (rr.Validate(200))
            {
                return(true);
            }
            if (rr.Validate(403))
            {
                //String captcha = new CaptchaService().recaptchaV2(c, "6LfBixYUAAAAABhdHynFUIMA_sa4s-XsJvnjtgB0", resolveUrl);
                //String url = "https://" + domainName + "/cdn-cgi/l/chk_captcha";

                Console.WriteLine("CAPTCHA ON CLOUDFARE!");
                return(false);
            }
            Console.WriteLine("Unexpected response (" + rr.ResponseCode + ")");
            return(false);
        }
示例#2
0
        private void WriteFilePart(IHttpStreamable httpStream, bool prepare, string key, FileLink value)
        {
            FileInfo fileInfo = (FileInfo)value.GetInfo();
            string   fileName = fileInfo.Name;

            if (NoMediaExtension)
            {
                fileName = StringFunc.Substring(fileName, 0, fileName.IndexOf(fileInfo.Extension));
            }
            httpStream.WriteLine("Content-Disposition: form-data; name=\"" + key + "\"; filename=\"" + fileName + "\"");
            httpStream.WriteLine("Content-Type: " + MimeType.GetByFile(value).Notation);

            if (!Chunked)
            {
                httpStream.WriteLine("Content-Transfer-Encoding: binary");
            }
            httpStream.WriteLine();
            httpStream.FlushUnderlying();

            if (!prepare)
            {
                WriteFile(httpStream, value);
            }
            httpStream.WriteLine();
            httpStream.FlushUnderlying();
        }
示例#3
0
        public static string BuildUpTime(int time, bool removeZeros = false)
        {
            StringBuilder result = new StringBuilder();

            if (HasHours(time))
            {
                result.Append(time / 3600000);
                result.Append(" hour");
                result.Append(StringFunc.Plural(time / 3600000));
                time %= 3600000;
            }
            else if (!removeZeros)
            {
                result.Append("0 hour");
            }

            if (HasMinutes(time))
            {
                result.Append(" ");
                result.Append(time / 60000);
                result.Append(" minute");
                result.Append(StringFunc.Plural(time / 60000));
                time %= 60000;
            }
            else if (!removeZeros)
            {
                result.Append(" 0 minute");
            }

            if (HasSeconds(time))
            {
                result.Append(" ");
                result.Append(time / 1000);
                result.Append(" second");
                result.Append(StringFunc.Plural(time / 1000));
                time %= 1000;
            }
            else if (!removeZeros)
            {
                result.Append(" 0 second");
            }

            if (HasMilliSeconds(time))
            {
                result.Append(" ");
                result.Append(time);
                result.Append(" millisecond");
                result.Append(StringFunc.Plural(time));
            }
            else if (!removeZeros)
            {
                result.Append(" 0 millisecond");
            }

            return(result.ToString().Trim());
        }
示例#4
0
        public static CBResult <string> stringNormal(StringFunc f, string arg2)
        {
            string b = f(arg2);

            return(new CBResult <string>()
            {
                breakloop = false,
                ans = b
            });
        }
示例#5
0
        private static string ResolveUrl(Document doc, string domainName, string baseUrl)
        {
            try {
                Element jschlEl = doc.Select("[name=jschl_vc]").First;

                if (jschlEl == null)
                {
                    Console.WriteLine("Failed to extract jsch element");
                    return(null);
                }
                string jschl_vc = jschlEl.Attr("value");
                string pass     = doc.Select("[name=pass]").First.Attr("value");

                Element scriptEl = doc.GetElementsByTag("script").First;

                if (scriptEl == null)
                {
                    Console.WriteLine("Failed to extract script element");
                    return(null);
                }
                string scriptHtml = scriptEl.Html;
                string content    = StringFunc.Substring(scriptHtml, scriptHtml.IndexOf("setTimeout(function(){") + 22, scriptHtml.Length).Trim();

                string part1 = StringFunc.Substring(content, 31, content.IndexOf("};") + 2);                 //@INFO: The first equation initially added to the builder var

                string[] part1Split = part1.Split("=");
                string   objName    = part1Split[0];
                string   objKey     = StringFunc.Substring(part1Split[1], 2, part1Split[1].IndexOf(":") - 1);
                string   objVar     = objName + "." + objKey;                                                                    //@INFO: The var of the object to use (name.key)

                string equationBlock = StringFunc.Substring(content, content.IndexOf(";" + objVar), content.IndexOf("a.value")); //The equation block

                double equationResult = (double)Javascript.ExecuteFunction("function test() { " + part1 + "" + equationBlock + " var aval = +" + objVar + ".toFixed(10); return aval;}", "test");
                //System.out.println(equationResult);
                double result = equationResult + domainName.Length;
                //System.out.println(result);
                string formatResult = string.Format("%.10f", result).Replace(",", ".");

                return(baseUrl + "/cdn-cgi/l/chk_jschl?jschl_vc=" + jschl_vc + "&pass="******"&jschl_answer=" + formatResult);
            } catch (Exception ex) {
                Console.WriteLine(ex.StackTrace);
            }
            return(null);
        }
示例#6
0
        public static void Main(string[] args)
        {
            CalllingWithPrimitives();

            // Use Release Build to use jsc to generate java program
            // Use Debug Build to develop on .net

            // doubleclicking on the jar will not show the console

            var        i       = 0;
            StringFunc GetText =
                delegate
            {
                return("Hello world (" + (i++) + ")");
            };


            StringAction h = Say;

            h(GetText());

            StringAction x = "hey!".Say;

            x(GetText());


            Do(() => Console.WriteLine(prefix + ":)"));

            WithClosure.Test();

            using ("Broadcasting...".Measure())
            {
                StringAction y = h;
                y += x;
                y("Broadcasting!!");

                y -= h;
                y("Broadcasting once?!!");
            }
        }
示例#7
0
 // The download functions needs to be encapsulated in some function --- This for non chained downloads.
 public void Request(List <DataRecord> Records, StringFunc Download, string URL)
 {
     records  = Records;
     download = Download;
     url      = URL;
 }
示例#8
0
        static void Main(string[] args)
        {
            int opcao;

            Console.WriteLine("Opção 1 : Exercício 1");
            Console.WriteLine("Opção 2 : Exemplo de Casting");
            Console.WriteLine("Opção 3 : Equação de Segundo Grau");
            Console.WriteLine("Opção 4 : Exemplo de Vetor");
            Console.WriteLine("Opção 5 : Hora Atual");
            Console.WriteLine("Opção 6 : Número positivo ou negativo");
            Console.WriteLine("Opção 7 : Número par ou ímpar");
            Console.WriteLine("Opção 8 : Multiplos ou não");
            Console.WriteLine("Opção 9 : Duração do Jogo");
            Console.WriteLine("Opção 10 : Cardápio da lancheria");
            Console.WriteLine("Opção 11 : Cardápio da lancheria");
            Console.WriteLine("Opção 12 : Quadrante");
            Console.WriteLine("Opção 13 : Maior entre 3");
            Console.WriteLine("Opção 14 : Raiz Quadrada com While");
            Console.WriteLine("Opção 15 : Senha");
            Console.WriteLine("Opção 16 : Coordenadas");
            Console.WriteLine("Opção 17 : Combustível");
            Console.WriteLine("Opção 18 : Soma com For");
            Console.WriteLine("Opção 19 : Impares entre X");
            Console.WriteLine("Opção 20 : Dentro ou Fora");
            Console.WriteLine("Opção 22 : Divisão Exata");
            Console.WriteLine("Opção 23 : Fatorial ");
            Console.WriteLine("Opção 24 : Divisores  ");
            Console.WriteLine("Opção 25 : Mais Velho  ");
            Console.WriteLine("Opção 26 : Maior Salário ");
            Console.WriteLine("Opção 27 : Produtos   ");
            Console.WriteLine("Opção 28 : Challenger ");
            Console.WriteLine("Opção 29 : Calcular Salário ");
            Console.WriteLine("Opção 30 : Aluno ");
            Console.WriteLine("Opção 31 : Convertendo Moeda ");
            Console.WriteLine("Opção 32 : Com Construtores ");
            Console.WriteLine("Opção 33 : Challenger    ");
            Console.WriteLine("Opção 34 : Vetor ");
            Console.WriteLine("Opção 35 : Vetor Classe   ");
            Console.WriteLine("Opção 36 : Vetor Challenger ");
            Console.WriteLine("Opção 38: Challneger Lista");
            Console.WriteLine("Opção 39: Challenger  Matriz");
            Console.WriteLine("Opção 40: Exemplo  Switch Case");
            Console.WriteLine("Opção 41: Funções String");
            Console.WriteLine("Opção 42: Funções DateTime");
            Console.WriteLine("Opção 43: Funções TimeSpan");
            Console.WriteLine("Opção 44: Exemplo DateTime");
            Console.WriteLine("Opção 45: Exemplo TimeSpan");
            Console.WriteLine("Opção 46 : Enum");

            Console.WriteLine("\nOpção 100 : Sair");

            Console.WriteLine("Digite uma opção válida");
            Console.Write("Digite a opão Desejada : ");
            opcao = int.Parse(Console.ReadLine());

            if (opcao == 1)
            {
                Exercicio1.Executar();
            }
            if (opcao == 2)
            {
                ExemploCasting.Executar();
            }
            if (opcao == 3)
            {
                EquacaoSegundoGrau.Executar();
            }
            if (opcao == 4)
            {
                Vetor.Executar();
            }
            if (opcao == 5)
            {
                HoraAtual.Executar();
            }
            if (opcao == 6)
            {
                NegativoOuPositivo.Executar();
            }
            if (opcao == 7)
            {
                NumeroPar.Executar();
            }
            if (opcao == 8)
            {
                Multiplos.Executar();
            }
            if (opcao == 9)
            {
                Duracao.Executar();
            }
            if (opcao == 10)
            {
                Cardapio.Executar();
            }
            if (opcao == 11)
            {
                QualIntervalo.Executar();
            }
            if (opcao == 12)
            {
                Quadrante.Executar();
            }
            if (opcao == 13)
            {
                MaiorEntre.Executar();
            }
            if (opcao == 14)
            {
                RaizQuadradaEterno.Executar();
            }
            if (opcao == 15)
            {
                Senha.Executar();
            }
            if (opcao == 16)
            {
                Coordenadas.Executar();
            }
            if (opcao == 17)
            {
                Combustivel.Executar();
            }
            if (opcao == 18)
            {
                SomaFor.Executar();
            }
            if (opcao == 19)
            {
                ImparesEntreX.Executar();
            }
            if (opcao == 20)
            {
                DentroFora.Executar();
            }
            if (opcao == 21)
            {
                MediaPonderada.Executar();
            }
            if (opcao == 22)
            {
                DivisaoExata.Executar();
            }
            if (opcao == 23)
            {
                Fatorial.Executar();
            }
            if (opcao == 24)
            {
                Divisores.Executar();
            }
            if (opcao == 25)
            {
                MaisVelho.Executar();
            }
            if (opcao == 26)
            {
                MaiorSalario.Executar();
            }
            if (opcao == 27)
            {
                Produtos.Executar();
            }
            if (opcao == 28)
            {
                Challenger.Executar();
            }
            if (opcao == 29)
            {
                CalculandoSalario.Executar();
            }
            if (opcao == 30)
            {
                Aluno.Executar();
            }
            if (opcao == 31)
            {
                ConversorMoeda.Executar();
            }
            if (opcao == 32)
            {
                ProdutoConstrutor.Executar();
            }
            if (opcao == 33)
            {
                AbrirConta.Executar();
            }
            if (opcao == 34)
            {
                VetorStruct.Executar();
            }
            if (opcao == 35)
            {
                VetorClass.Executar();
            }
            if (opcao == 36)
            {
                ChallengerVetor.Executar();
            }
            if (opcao == 37)
            {
                ModificadorRef.Executar();
            }
            if (opcao == 38)
            {
                ChallengerLista.Executar();
            }
            if (opcao == 39)
            {
                ChallengerMatriz.Executar();
            }
            if (opcao == 40)
            {
                SwitchCase.Executar();
            }
            if (opcao == 41)
            {
                StringFunc.Executar();
            }
            if (opcao == 42)
            {
                DateTimeSimples.Executar();
            }
            if (opcao == 43)
            {
                TimeSpanSimples.Executar();
            }
            if (opcao == 44)
            {
                ExercicioDateTime.Executar();
            }
            if (opcao == 45)
            {
                ExercicioTimeSpan.Executar();
            }
            if (opcao == 46)
            {
                Order.Executar();
            }
        }
示例#9
0
        private void ProcessIncomingMsg(string topic, string message)
        {
            if (topic == "pic/ts")
            {
                object[] args = new object[1];
                args[0] = message;
                StringFunc f = new StringFunc(DisplayPic);
                this.BeginInvoke(f, args);
                return;
            }

            string[] names = topic.Split('/');
            if (names.Length <= 2)
            {
                return;
            }
            if (names[0] != "robot")
            {
                return;
            }

            ShowSavedMessages();

            if (topic == "robot/roborio/log")
            {
                if (!checkBoxPauseRobotLog.Checked)
                {
                    AddLogLine(textBoxRobotLog, message);
                }
                return;
            }
            else
            {
                AddLogLine(textBoxMqttList, topic + ": " + message);
            }

            if (names[1] == "jetson")
            {
                AddLogLine(textBoxJetsonLog, topic + ": " + message);
            }

            if (topic == "robot/jetson/ping")
            {
                int    pingid = 0;
                bool   okay   = Int32.TryParse(message.Trim(), out pingid);
                string m      = "";
                if (okay && pingid == m_PingID)
                {
                    double ElapsedSecs = StopWatch.Stop(m_PingStartTime);
                    m = String.Format("Ping {0} to Jetson = {1:0.000} ms.", m_PingID, ElapsedSecs * 1000.0);
                }
                else
                {
                    m = String.Format("Invalid Ping Response.  Expected {0}, Got " + message.Trim(), m_PingID);
                }
                AddLogLine(textBox_MainLog, m);
            }

            if (names[1] != "roborio" && names[1] != "jetson")
            {
                string msg = topic + ": " + message;
                AddLogLine(textBox_MainLog, msg);
            }

            if (topic == "robot/jetson/targetparams")
            {
                object[] args = new object[1];
                args[0] = message;
                this.BeginInvoke(new StringFunc(LoadParams), args);
            }

            if (topic == "robot/rio/params")
            {
                object[] args = new object[1];
                args[0] = message;
                this.BeginInvoke(new StringFunc(LoadRioParams), args);
            }
        }
示例#10
0
        public Stream Decode(Stream inputStream)
        {
            List <byte> lineBuffer = new List <byte>();

            while (true)
            {
                byte b = (byte)inputStream.ReadByte();

                if (b < 0)
                {
                    Console.WriteLine("Malformed server response received, EOF reached unexpectedly");
                    return(null);
                }
                lineBuffer.Add(b);

                if (b != 10)                   //Keep collecting bytes if there's no linefeed (new line) \n indicated
                {
                    continue;
                }
                byte[] lineBufferArray = new byte[lineBuffer.Count];

                for (int i = 0; i < lineBufferArray.Length; i++)
                {
                    lineBufferArray[i] = lineBuffer[i];
                }
                string line = Encoding.ASCII.GetString(lineBufferArray).Trim(); //Build a string out of our collected bytes and trim off the line break
                lineBuffer.Clear();                                             //Clears the line buffer for the next read

                if (line == string.Empty)                                       //When an empty line is found it means we parsed all headers
                {
                    break;
                }
                if (line.Equals("0", StringComparison.Ordinal) ||
                    line.Equals(Delimiters.Linebreak, StringComparison.Ordinal))
                {
                    break;
                }
                if (line.StartsWith("HTTP", StringComparison.OrdinalIgnoreCase))                   //The status line of the response
                {
                    string[]      msgParts            = line.Split(" ");
                    string        httpProtocolVersion = msgParts[0];
                    string        responseCode        = msgParts[1];
                    StringBuilder responseMsgBuilder  = new StringBuilder();

                    for (int i = 2; i < msgParts.Length; i++)
                    {
                        responseMsgBuilder.Append(msgParts[i] + " ");
                    }
                    int      code     = MathUtil.ParseInt(responseCode);
                    HttpCode httpCode = HttpCode.GetForCode(code);
                    string   msg      = responseMsgBuilder.ToString().Trim();

                    if (string.IsNullOrEmpty(msg))
                    {
                        msg = httpCode.Message;
                    }
                    if (httpCode == HttpCode.Invalid)
                    {
                        msg = "[Unhandled code: " + code + "] - " + msg;
                    }
                    ResponseStatus = new ResponseStatus(HttpVersion.Parse(httpProtocolVersion), httpCode, msg);
                    continue;
                }
                string key   = StringFunc.Substring(line, 0, line.IndexOf(":")).Trim();
                string value = StringFunc.Substring(line, line.IndexOf(":") + 1, line.Length).Trim();

                if (!key.Equals(HeaderKeys.SetCookie, StringComparison.OrdinalIgnoreCase))
                {
                    Headers.Put(key, value);

                    if (HttpConfig.DebugMode)
                    {
                        Console.WriteLine("RESPONSE-HEADER => " + key + ": " + value);
                    }
                    continue;
                }
                Cookie cookie = ExtractCookie(value);
                Cookies.Add(cookie);

                if (HttpConfig.DebugMode)
                {
                    Console.WriteLine("RESPONSE-COOKIE => " + cookie.ToString());
                }
            }
            return(inputStream);
        }
示例#11
0
        private static Cookie ExtractCookie(string headerValue)
        {
            string[] fields = headerValue.Split(";");

            string key      = StringFunc.Substring(fields[0], 0, fields[0].IndexOf("=")).Trim();
            string value    = StringFunc.Substring(fields[0], fields[0].IndexOf("=") + 1, fields[0].Length);
            string expires  = null;
            string path     = "/";
            string domain   = "/";
            bool   secure   = false;
            bool   httpOnly = false;
            long   maxAge   = 0L;
            string sameSite = "Lax";

            for (int i = 1; i < fields.Length; i++)
            {
                string field = fields[i].Trim();

                if (field.Equals(CookieKeys.Secure, StringComparison.OrdinalIgnoreCase))
                {
                    secure = true;
                    continue;
                }
                if (field.Equals(CookieKeys.HttpOnly, StringComparison.OrdinalIgnoreCase))
                {
                    httpOnly = true;
                    continue;
                }
                if (!field.Contains("=", StringComparison.Ordinal))
                {
                    Console.WriteLine("Malformed cookie field: " + fields[i]);
                    continue;
                }
                string fieldKey   = StringFunc.Substring(field, 0, field.IndexOf("=")).Trim();
                string fieldValue = StringFunc.Substring(field, field.IndexOf("=") + 1, field.Length);

                if (fieldKey.Equals(CookieKeys.Expires, StringComparison.OrdinalIgnoreCase))
                {
                    expires = fieldValue;
                    continue;
                }
                if (fieldKey.Equals(CookieKeys.Domain, StringComparison.OrdinalIgnoreCase))
                {
                    domain = fieldValue;
                    continue;
                }
                if (fieldKey.Equals(CookieKeys.Path, StringComparison.OrdinalIgnoreCase))
                {
                    path = fieldValue;
                    continue;
                }
                if (fieldKey.Equals(CookieKeys.MaxAge, StringComparison.OrdinalIgnoreCase))
                {
                    maxAge = MathUtil.ParseLong(fieldValue, true, 0L);
                    continue;
                }
                if (fieldKey.Equals(CookieKeys.SameSite, StringComparison.OrdinalIgnoreCase))
                {
                    sameSite = fieldValue;
                    continue;
                }
                Console.WriteLine("Unhandled cookie field: " + fields[i]);
            }
            Cookie cookie = new Cookie(key, value, domain);

            cookie.Expires  = expires;
            cookie.Path     = path;
            cookie.Secure   = secure;
            cookie.MaxAge   = maxAge;
            cookie.SameSite = sameSite;

            return(cookie);
        }
示例#12
0
        //Linq to XML is an alternate set of classes for XML that enables the use of LINQ for XML data and also makes certain operations with XML
        //easier even if you are not using LINQ. LINQ to XML can have some advantages over XML DOM
        //For instance, LINQ to XML provides an easier way to create XML documents called functional construction, constructor calls nested
        //in a way that naturally reflects the structure of an XML document.
        static void Main(string[] args)
        {
            //Document contains elements, and each element contains attributes and other elements.
            //The first and only parameter you pass in XDocument is is XElement
            //XElement - constructor takes the name of the element as a string, followed by a list of the XML objects contained withing that element.
            //XAttribute takes only the name of the attribute and its value as parameters
            //Other Linq to XML constructors for all the XML node types:
            //XDeclaration() for the XML declaration at the start of an XML document, XComment() for an XML comment, and so on.
            XDocument xdoc = new XDocument(new XElement("customers",
                                                        new XElement("customer", new XAttribute("ID", "A"),
                                                                     new XAttribute("City", "New York"),
                                                                     new XAttribute("Region", "North America"),
                                                                     new XElement("order",
                                                                                  new XAttribute("Item", "Widget"),
                                                                                  new XAttribute("Price", 100)
                                                                                  ),
                                                                     new XElement("order",
                                                                                  new XAttribute("Item", "Tire"),
                                                                                  new XAttribute("Price", 200)
                                                                                  )
                                                                     ),
                                                        new XElement("customer", new XAttribute("ID", "B"),
                                                                     new XAttribute("City", "Mumbai"),
                                                                     new XAttribute("Region", "Asia"),
                                                                     new XElement("order",
                                                                                  new XAttribute("Item", "Oven"),
                                                                                  new XAttribute("Price", 501)
                                                                                  )

                                                                     )));

            WriteLine(xdoc); //Prints out XML using default ToString() method of XDocument()
            Write("Program finished, press Enter/Return to continue:");
            ReadLine();


            XElement xcust = new XElement("customers",
                                          new XElement("customer", new XAttribute("ID", "A"),
                                                       new XAttribute("City", "New York"),
                                                       new XAttribute("Region", "North America"),
                                                       new XElement("order",
                                                                    new XAttribute("Item", "Widget"),
                                                                    new XAttribute("Price", 100)
                                                                    ),
                                                       new XElement("order",
                                                                    new XAttribute("Item", "Tire"),
                                                                    new XAttribute("Price", 200)
                                                                    )
                                                       ),
                                          new XElement("customer", new XAttribute("ID", "B"),
                                                       new XAttribute("City", "Mumbai"),
                                                       new XAttribute("Region", "Asia"),
                                                       new XElement("order",
                                                                    new XAttribute("Item", "Oven"),
                                                                    new XAttribute("Price", 501)
                                                                    )

                                                       )
                                          );
            //Save, load, and display EXML element:

            /*
             * Both XElement and XDocument inherit from the Linq to XML container class, XContainer class which implements an XML node that can contain other XML nodes.
             * Both classes also implement Load() and Save() so most operations that can be performed by XDocument can also be performed by XElement and its children
             * XElement also supports the Load() and Parse() methods for loading XML from files and strings, respecitvely.
             */
            string xmlFileName  = @"c:\Users\HS1122\Desktop\C#\LINQ\fragment.xml";
            string xmlFileName2 = @"c:\Users\HS1122\Desktop\C#\LINQ\doc.xml";

            xcust.Save(xmlFileName);
            xdoc.Save(xmlFileName2);

            XElement  xcust2 = XElement.Load(xmlFileName);
            XDocument xdoc2  = XDocument.Load(xmlFileName2);

            WriteLine("Contents of xcust: ");
            WriteLine(xcust);

            Write("Program finished, press Enter/Return to continue:");
            ReadLine();


            //Unlike XML DOM LINQ to XML works with XML fragmets(partial or incomplete XMML documents) in very much the same way as complete XML documents.
            //Working with a fragment you simply work with XElement as the top-level  XML object instead of XDocument, when working with fragments, you cannot
            //add esoteric XML node types that apply to docs such as XComment, XDeclaration, and XProcessingInstruction for XML processing instructions

            /*
             * Linq to XML is just one example of a Linq provider, there are a number:
             * LINQ to Objects - queries on any kind of C# in-memory object, such as arrays, lists, collection types,
             * LINQ to XML - creating and manipulation of XML documents
             * LINQ to Entities => Enitity Framework
             * LINQ to DataSet => DataSet object was introduced in the first version of .Net framework, legacy,
             * LINQ to SQL => superseded by LINQ to Entities
             * PLINQ => Parallel Linq extends Linq to objects with a parallel programming library that can split up a query to execute simultaneously
             * LINQ to JSON => included in Newtonsoft package, creation and manipulation of json documents
             * Syntax and Methods covered here will apply to all of these
             *
             */
            //LINQ TO OBJECTS PROVIDOR

            string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe", "Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba", "Fatimah" };

            //Linq query statement in this program uses the LINQ declarative query syntax
            //4 Parts: the result variable delaration beginning with var, which is assigned using a query expression consisting of the from clause,
            //where clause, and the select clause.
            //It should be var because then you dont have to worry about whats returned by the query. If the query can reutrn multiple items, then it acts like
            //a collection of the objects in the query data source(The query result will be a type that implements the IEnumerable<T> interface)
            //The form clause specifies the data you are querying: => from n in names (n is a stand in like in foreach), by specifying from,
            //you are indicating you are going to query a subset of the collection.
            //a Linq data source must be enumerable, so support IEnumberable<T> interface which is supported for any C#  arry or collection of items.
            //specify condition of query using where clause => where n.StartsWith("S"), any boolean expression that can be applied to the items in
            //the data source can be specified in the where clause. where clause optional, it is a restriction operator in LINQ because it restricts the
            //results of the query.
            //select clause specifies which items appear in the  result set. Is required clause b/c you must specify which items from query appear in the
            //result set


            var queryResults = from n in names
                               where n.StartsWith("S")
                               select n;


            WriteLine("Names that start with S: ");
            //foreach loop is part of your code that actually executes the linq query!!!
            //The assignment of the query result variable only saves a plan for executing the query; with Linq, the data itself is not retrieved until
            //the results are accessed. =>Called deferred query execution or lazy evaluation of queries. Execution will be deferred for any query that
            //produces a sequence, or, list of results.
            foreach (var name in queryResults)
            {
                WriteLine(name);
            }
            ReadKey();

            /*Previous example done in LINQ query syntax, you can also rewrite example using Linq's method syntax(aka explicit syntax)
             * LINQ is implemented as a series of extension methods to collcetions, arrays, query results, and any other object that
             * implements the IEnumerable<T> interface.
             * See names variable?
             * there is a names.where(some bullshit parameter) function
             * For instance, the Where<T> method and most other methods are extension methods . They are LINQ extensions, such as
             * Where<T>, Union<T>,Take<T> and others. The from...where...select querey expression translated into a series of calls by
             * these methods.
             *
             * Most of the LINQ methods that use method syntax require that you pass a method of function to evaluate the query expression.
             * The method/fuction parameter is passed in the form of a delegate which typically refereces a method. But you can also create
             * using lambda expressions that encapsulate the delegate in an elegant manner.
             *
             * n => n < 0
             * This declares a method with single parameter n, and returns true if n is less than 0, false otherwise.
             *
             * (a,b) => a+b
             * 2 paramter method which returns sum of 2 params. You dont have to declare what type a and b are. They can be int, double
             * or string. C# compiler infers the types.
             */
            WriteLine();

            StringFunc StartWithS = new StringFunc(startWthS);

            string[] names2        = { "Alonso", "Zheng", "Smith", "Jones", "Smythe", "Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba", "Fatimah" };
            var      queryResults2 = names2.Where(n => n.StartsWith("S")); //If the lambda expression is true for an item it is included. C# compiler infers that
                                                                           //the where method should accept string from defn of input source
            var queryResults3 = names2.Where(startWthS);

            foreach (var name in queryResults2)
            {
                WriteLine(name);
            }
            WriteLine();
            foreach (var name in queryResults3)
            {
                WriteLine(name);
            }
            ReadKey();

            //You can also order query results
            //The orderby clause is optional like the where clause.
            //by default orderby orders in ascending order (A to Z) but you can specify descending order(from Z to A) simply by adding the descending keyword
            //orderby n descending
            //plus you can order by the last letter in the name isntead of normal alphabetical order, you just change the orderby clause to the following =>
            //orderby n.Substring(n.Length - 1)
            //Last letters in alphabetical order. Note only looks at last letter, so Smith can come before Singh and Singh can come before Smith
            var queryResults4 = from n in names2
                                where n.StartsWith("S")
                                orderby n
                                select n;

            WriteLine("Names beg with S ordered alphabetically");
            foreach (var name in queryResults4)
            {
                WriteLine(name);
            }
            ReadKey();

            //If you did the query down below but did n> 1000, too many numbers!!
            //Here are some aggregrate operaters to simplify operations:
            //Count() => Count of Results
            //Min() => Min val in Results
            //Max() => Max val in Results
            //Average() => Average val of numeric results
            //Sum() => Total of all  of numeric results
            //There are more aggregate operations such as Aggregate() for executing arbitrary code in a manner that enables you to code your own aggregate
            //function
            int[] numbers       = GenerateLotsOfNumbers(48);
            var   queryResults5 = from n in numbers
                                  where n > 1000
                                  //   orderby n ascending
                                  select n;

            WriteLine("Count of numbers > 1000");
            WriteLine(queryResults5.Count());

            WriteLine("Max of Numbers > 1000");
            WriteLine(queryResults5.Max());

            WriteLine("Min of Numbers > 1000");
            WriteLine(queryResults5.Min());

            WriteLine("Average of Numbers > 1000");
            WriteLine(queryResults5.Average());

            WriteLine("Sum of Numbers > 1000");
            WriteLine(queryResults5.Sum(n => (long)n));
            //32 bit int is what the default no parameter version of sum would return too small
            //lambda expression allows you convert result to long
            //There is a longcount. Other than that, If a 64 bit number expected from all the other operators,
            //require a lambda to 64 bit coversion as parameter

            var nums = new[] { 1, 2, 3, 4 };
            var sums = nums.Aggregate((a, b) => a + b);

            Console.WriteLine(sums); //Output is 10, a is the aggregate and b is the next element, so adds it like this:
            //1+2 = 3, 3 +3 = 6, 6+4 = 10
            var divide = nums.Aggregate((a, b) => a * b);

            Console.WriteLine(divide); // 1*2*3*4 = 24

            //Another type of query is the SELECT DISTINCT query in which you search for the unique values in your data,
            //query removes any repeated values from the result set.
            List <Customer> customers = new List <Customer> {
                new Customer {
                    ID = "A", City = "New York", Country = "USA", Region = "North America", Sales = 9999
                },
                new Customer {
                    ID = "B", City = "Mumbai", Country = "India", Region = "Asia", Sales = 8888
                },
                new Customer {
                    ID = "C", City = "Karachi", Country = "Pakistan", Region = "Asia", Sales = 7777
                },
                new Customer {
                    ID = "D", City = "Delhi", Country = "India", Region = "Asia", Sales = 6666
                },
                new Customer {
                    ID = "E", City = "São Paulo", Country = "Brazil", Region = "South America", Sales = 5555
                },
                new Customer {
                    ID = "F", City = "Moscow", Country = "Russia", Region = "Europe", Sales = 4444
                },
                new Customer {
                    ID = "G", City = "Seoul", Country = "Korea", Region = "Asia", Sales = 3333
                },
                new Customer {
                    ID = "H", City = "Istanbul", Country = "Turkey", Region = "Asia", Sales = 2222
                },
                new Customer {
                    ID = "I", City = "Shanghai", Country = "China", Region = "Asia", Sales = 1111
                },
                new Customer {
                    ID = "J", City = "Lagos", Country = "Nigeria", Region = "Africa", Sales = 1000
                },
                new Customer {
                    ID = "K", City = "Mexico City", Country = "Mexico", Region = "North America", Sales = 2000
                },
                new Customer {
                    ID = "L", City = "Jakarta", Country = "Indonesia", Region = "Asia", Sales = 3000
                },
                new Customer {
                    ID = "M", City = "Tokyo", Country = "Japan", Region = "Asia", Sales = 4000
                },
                new Customer {
                    ID = "N", City = "Los Angeles", Country = "USA", Region = "North America", Sales = 5000
                },
                new Customer {
                    ID = "O", City = "Cairo", Country = "Egypt", Region = "Africa", Sales = 6000
                },
                new Customer {
                    ID = "P", City = "Tehran", Country = "Iran", Region = "Asia", Sales = 7000
                },
                new Customer {
                    ID = "Q", City = "London", Country = "UK", Region = "Europe", Sales = 8000
                },
                new Customer {
                    ID = "R", City = "Beijing", Country = "China", Region = "Asia", Sales = 9000
                },
                new Customer {
                    ID = "S", City = "Bogotá", Country = "Colombia", Region = "South America", Sales = 1001
                },
                new Customer {
                    ID = "T", City = "Lima", Country = "Peru", Region = "South America", Sales = 2002
                }
            };
            //Because Distinct() is available only in method syntax, you make the call using method syntax
            //however you can call it in query syntax too!

            //method syntax
            var queryResults6 = customers.Select(c => c.Region).Distinct();

            //query syntax: var queryResults = (from c in customers select c.Region).Distinct();

            foreach (var item in queryResults6)
            {
                WriteLine(item);
            }
            Write("Program finished, press Enter/Return to continue:");
            ReadLine();
            ReadLine();
            //Ordering By Multiple Levels,  What if you wanted to query your results then order alphabetically by region
            //then order alphabetically opposite by country if they the same, then order alphabetically by city name. You can do
            //that like this:

            var queryResults7 = from c in customers
                                orderby c.Region, c.Country descending, c.City
            //orderby operates on a field by field basis
            //you can add descending to any fields listed here
                select new { c.ID, c.Region, c.Country, c.City };

            //The select statement uses an anonymous type to encapsulate a set of read only properties into a single object
            //without having to define a type. The type of each property is inferred by the compiler.
            //var v = new { Amount = 108, Message = "Hello" }; This shows an anonymous type initiliazed with 2 properties
            //named Amount and Message
            //If you do not specify member names in the anonymous type, the compiler gives the anonymous type members the
            //same name as the property being used to initialize them.
            foreach (var item in queryResults7)
            {
                WriteLine(item);
            }
            Write("Program finished, press Enter/Return to continue:");
            ReadLine();
            WriteLine();
            WriteLine();

            //Group Queries
            //Divides data into groups and enables you to sort, calculate aggregates, and compare by group
            //The data in a group is grouped by a key field, the field for which all the memebers of each group
            //share a value. In this, the key field is the Region
            //You watn to calculate a total for each group, so you group into a new result set named cg
            var groupQuery = from c in customers
                             group c by c.Region into cg
                             select new { TotalSales = cg.Sum(c => c.Sales), Region = cg.Key };
            //The group result set implements the LINQ IGrouping interface which supports the Key property
            //Always want to reference key somehow b/c it represents criteria by which each group in your
            //data was created
            var orderedResults = from cg in groupQuery
                                 orderby cg.TotalSales descending
                                 select cg;

            WriteLine("Total\t: By\nSales\t: Region\n-----\t ------");
            foreach (var item in orderedResults)
            {
                WriteLine($"{item.TotalSales}\t: {item.Region}");
            }

            //A data set such as the customers and orders list you just created, with a shared key field(ID), enables a join query
            //whereby you can query related data in both lists with a single query, joining the results togetehtor with the key field
            WriteLine();
            WriteLine();

            List <Order> orders = new List <Order> {
                new Order {
                    ID = "P", Amount = 100
                },
                new Order {
                    ID = "Q", Amount = 200
                },
                new Order {
                    ID = "R", Amount = 300
                },
                new Order {
                    ID = "S", Amount = 400
                },
                new Order {
                    ID = "T", Amount = 500
                },
                new Order {
                    ID = "U", Amount = 600
                },
                new Order {
                    ID = "V", Amount = 700
                },
                new Order {
                    ID = "W", Amount = 800
                },
                new Order {
                    ID = "X", Amount = 900
                },
                new Order {
                    ID = "Y", Amount = 1000
                },
                new Order {
                    ID = "Z", Amount = 1100
                }
            };

            //The query uses the join keyword to unite customers with their corresponding orders using the ID fields from
            //the Customer and Order classes, respectively. The query result only includes the data for objects that have the same
            //id field value as the corresponding id field in the other collection
            var queryResults8 = from c in customers
                                join o in orders on c.ID equals o.ID
                                select new
            {
                c.ID,
                c.City,
                SalesBefore = c.Sales,
                NewOrder    = o.Amount,
                SalesAfter  = c.Sales + o.Amount
            };

            foreach (var item in queryResults)
            {
                WriteLine(item);
            }



            ReadKey();
        }