Example #1
0
	/**
	 * Validate XML matches XSD. Stream-based method.
	 * 
	 * @param xsdStream resource based path to XSD file
	 * @param xmlStream resource based path to XML file
	 * @throws IOException io exception for loading files
	 * @throws SAXException sax exception for parsing files
	 */

    /// <exception cref="IOException"></exception>
    /// <exception cref="SAXException"></exception>
    public static void validateXMLSchema(StreamReader xsdStream, StreamReader xmlStream) {
        //SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        //Schema schema = factory.newSchema(new StreamSource(xsdStream));
        //Validator validator = schema.newValidator();
        //validator.validate(new StreamSource(xmlStream));

        //XmlReaderSettings booksSettings = new XmlReaderSettings();
        //booksSettings.Schemas.Add("http://www.contoso.com/books", "books.xsd");
        //booksSettings.ValidationType = ValidationType.Schema;
        //booksSettings.ValidationEventHandler += new ValidationEventHandler(booksSettingsValidationEventHandler);

        //XmlReader books = XmlReader.Create("books.xml", booksSettings);

        //while(books.Read()) {
        //}

        //XmlReader books = XmlReader.Create("books.xml", booksSettings);

        //while(books.Read()) {
        //}

        XmlReaderSettings schema = new XmlReaderSettings();
        schema.Schemas.Add("http://www.w3.org/2001/XMLSchema", xsdStream.ToString());
        schema.ValidationType = ValidationType.Schema;
        schema.ValidationEventHandler += new ValidationEventHandler(schemaValidationEventHandler);
        }
Example #2
0
        public static void Load(string filePath = "")
        {
            filePath = string.IsNullOrEmpty(filePath) ? ConfigFileName : filePath;

            if (!File.Exists(filePath)) {
                //TODO Create default config file.
                Logger.Error("Config file not found");
                return;
            }

            if (Properties == null) {
                Properties = new Dictionary<string, string>();
            }

            using (StreamReader sr = new StreamReader(filePath)) {
                string str;
                if (sr.ToString().Length == 0) {
                    Logger.Error("Empty config file");
                }
                while ((str = sr.ReadLine()) != null) {
                    var key = str.Split('=')[0].Replace(" ", "");
                    var value = str.Split('=')[1].Replace(" ", "");

                    if (Properties.ContainsKey(key)) {
                        Properties[key] = value;
                    } else {
                        Properties.Add(key, value);
                    }
                }
            }
        }
Example #3
0
 void app_BeginRequest(object sender, EventArgs e)
 {
     HttpContext.Current.Response.Clear();
     // Check if ToWord exists in the query string parameters
     if (HttpContext.Current.Request.QueryString["ToWord"] != null)
     {
         // Set the buffer to true
         HttpContext.Current.Response.Buffer = true;
         // Create a new HttpWebRequest to the same url
         HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(HttpContext.Current.Request.Url.ToString().Split('?')[0]);
         // Set the credentials to default credentials: used if you are under proxy server
         webRequest.Credentials = CredentialCache.DefaultCredentials;
         // Get the response as stream
         Stream stream = webRequest.GetResponse().GetResponseStream();
         // Set the content type of the response on msword
         HttpContext.Current.Response.ContentType = "application/msword";
         // Read the response as string
         string pageHTML = new StreamReader(stream).ReadToEnd();
         // Write it to the response
         HttpContext.Current.Response.Write(pageHTML.ToString());
         // Complete the Request
         ((HttpApplication)sender).CompleteRequest();
         // End the response.
         HttpContext.Current.Response.End();
     }
 }
Example #4
0
 public void LoadFile(string path)
 {
     using (StreamReader reader = new StreamReader(path))
     {
         reader.ReadToEnd();
         string fileContent = reader.ToString();
         Parse(fileContent);
     }
 }
Example #5
0
        public string GET(string method)
        {
            var request = (HttpWebRequest)WebRequest.Create(url+method);

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            return responseString.ToString();
        }
Example #6
0
        public String readFile(String fileName)
        {
            StreamReader objReader = new StreamReader(fileName, System.Text.Encoding.Default, true);
            objReader.ToString();
            String data = objReader.ReadToEnd();
            String dataSend = setEncodeString(data);

               // Console.WriteLine(dataSend);

            return dataSend;
        }
Example #7
0
        public String getTed(String fileName)
        {
            String ted = String.Empty;
            String xml = String.Empty;

            if (fileName != null)
            {
                StreamReader objReader = new StreamReader(fileName, System.Text.Encoding.Default, true);
                objReader.ToString();
                xml = objReader.ReadToEnd();
            }

            int start = xml.IndexOf("<TED");
            int end = xml.IndexOf("</TED>");

            int largo = (end+6) - start;

            ted = xml.Substring(start, largo);

            return ted;
        }
        public LibroCompra lectura()
        {
            LibroCompra lib = new LibroCompra();

            fileAdmin file = new fileAdmin();
            String fileName = file.nextFile(@"c:\IatFiles\file\", "*.json");

            if (fileName != null)
            {
                //Paso la ruta del fichero al constructor
                StreamReader objReader = new StreamReader(fileName, System.Text.Encoding.Default, true);
                objReader.ToString();
                String data = objReader.ReadToEnd();

                DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(LibroCompra));

                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(data));

                try
                {
                    lib = (LibroCompra)js.ReadObject(ms);
                }
                catch (Exception e)
                {

                    Console.WriteLine(e.Message);
                    MessageBox.Show("Error de lectura JSON" + e.Message);

                }

                objReader.Close();
                ms.Close();
                file.mvFile(fileName, "C:/IatFiles/file/librocompra/", "C:/IatFiles/fileProcess/");
                return lib;
            }
            else
            {
                return null;
            }
        }
Example #9
0
        public  string POST(string m_postData, string method)
        {
           
            var request = (HttpWebRequest)WebRequest.Create(url+method);

            var postData = m_postData;
            var data = Encoding.ASCII.GetBytes(postData);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            return responseString.ToString();

        }
        void timerUserSync_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                int.TryParse(ConfigurationManager.AppSettings["SyncUsersTime"], out timeUserSync);
                timerUserSync.Interval = timeUserSync * 1000;

                //Library.WriteErrorLog("Sync Users Logging Started ");

                // call api and save the data from Json to SQL on web api
                string con = ConfigurationManager.AppSettings["apiUrl"] + "JsonToSqlSync/1";
                var request = (HttpWebRequest)WebRequest.Create(con);
                var response = (HttpWebResponse)request.GetResponse();
                var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                string s = responseString.ToString();

                //Library.WriteDataLog(s);
                //Library.WriteErrorLog("Sync Users Logged Successfully ");
            }
            catch (Exception ex)
            {
                Library.WriteErrorLog("timerUserSync_Elapsed: " + ex.ToString());
                //Library.WriteDataLog(ex);

            }
        }
        void timerPingService_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                int.TryParse(ConfigurationManager.AppSettings["PingTime"], out timePing);
                timerPingService.Interval = timePing * 1000;
                string pingCheck = ConfigurationManager.AppSettings["startPingCheck"];
                string s = string.Empty;

                //Call Ping Status Check Controller
                if (pingCheck.ToUpper() == "true".ToUpper() || pingCheck.ToUpper() == "t".ToUpper())
                {
                    //Library.WriteErrorLog("Ping Data Logging Started " + timePing.ToString());
                    string conStatus = ConfigurationManager.AppSettings["apiUrl"] + "sitestatus";
                    HttpWebRequest requestStatus = (HttpWebRequest)WebRequest.Create(conStatus);
                    requestStatus.Timeout = 600 * 1000;
                    HttpWebResponse responseStatus = (HttpWebResponse)requestStatus.GetResponse();

                    var responseString = new StreamReader(responseStatus.GetResponseStream()).ReadToEnd();
                    s = responseString.ToString();
                    //Library.WriteDataLog(s);
                    //Library.WriteErrorLog("Ping Data Logged Successfully ");
                }

            }
            catch (Exception ex)
            {
                Library.WriteErrorLog("timerPingService_Elapsed: " + ex.ToString());
                //Library.WriteDataLog(ex);

            }
        }
        void timerMailQueueService_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                int.TryParse(ConfigurationManager.AppSettings["MailQueueScheduleTime"], out timeMailQueue);
                timerMailQueueService.Interval = timeMailQueue * 1000;
                string MailQueueCheck = ConfigurationManager.AppSettings["MailQueueServiceEnabled"];
                //Library.WriteErrorLog("Sync Daily Notifications Logging Started ");
                if (MailQueueCheck.ToUpper() == "true".ToUpper() || MailQueueCheck.ToUpper() == "t".ToUpper())
                {
                    // call api and save the data from Json to SQL on web api
                    string con = ConfigurationManager.AppSettings["apiUrl"] + "notifications/ExecuteMailQueue";
                    var request = (HttpWebRequest)WebRequest.Create(con);
                    var response = (HttpWebResponse)request.GetResponse();
                    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                    string s = responseString.ToString();
                }
                //Library.WriteDataLog(s);
                //Library.WriteErrorLog("Sync Daily Notifications Logged Successfully ");
            }
            catch (Exception ex)
            {
                Library.WriteErrorLog("timerMailQueueService_Elapsed: " + ex.ToString());

            }
        }
Example #13
0
        public Documento lectura(String fileJson, bool moveFile, String dirOrigen)
        {
            Documento doc = new Documento();
            fileAdmin file = new fileAdmin();
            String fileName = String.Empty;

            if (dirOrigen == "")
            {
                dirOrigen = @"C:\AdmToFebosFiles\files";
            }

            if (fileJson == "")
            {
                fileName = file.nextFile(dirOrigen, "*.json");
            }
            else
            {
                fileName = dirOrigen + fileJson;
            }

            if (fileName != null)
            {
                StreamReader objReader = new StreamReader(fileName,System.Text.Encoding.Default,true);
                objReader.ToString();
                String data = objReader.ReadToEnd();

                DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Documento));

                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(data));

                try
                {
                    doc = (Documento)js.ReadObject(ms);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    MessageBox.Show("Error de lectura JSON"+ e.Message);
                }

                // Datos del Emisor
                // Cargo datos en laclase Documento desde sqlite

                if (doc.RUTEmisor == null)
                {
                    try
                    {

                        SQLiteConnection myConn = new SQLiteConnection(strConn);
                        myConn.Open();

                        string sql = "select * from empresa";
                        SQLiteCommand command = new SQLiteCommand(sql, myConn);
                        SQLiteDataReader reader = command.ExecuteReader();
                        while (reader.Read())
                        {

                            doc.RUTEmisor = reader["RutEmisor"].ToString();
                            doc.RznSoc = reader["RznSoc"].ToString();
                            doc.GiroEmis = reader["GiroEmis"].ToString();
                            doc.Telefono = reader["Telefono"].ToString();
                            doc.CorreoEmisor = reader["CorreoEmisor"].ToString();
                            doc.Acteco = Convert.ToInt32(reader["Acteco"]);
                            doc.CdgSIISucur = Convert.ToInt32(reader["CdgSIISucur"]);
                            doc.DirMatriz = reader["DirMatriz"].ToString();
                            doc.CmnaOrigen = reader["CmnaOrigen"].ToString();
                            doc.CiudadOrigen = reader["CiudadOrigen"].ToString();
                            doc.DirOrigen = reader["DirOrigen"].ToString();
                            doc.NombreCertificado = reader["NomCertificado"].ToString();
                            doc.SucurEmisor = reader["SucurEmisor"].ToString();
                            doc.FchResol = reader["FchResol"].ToString();
                            doc.RutEnvia = reader["RutCertificado"].ToString();
                            doc.NumResol = reader["NumResol"].ToString();
                            doc.CondEntrega = reader["CondEntrega"].ToString();

                        }
                        myConn.Close();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: {0}", e.ToString());
                    }
                }
                else
                {
                    try
                    {

                        SQLiteConnection myConn = new SQLiteConnection(strConn);
                        myConn.Open();

                        string sql = "select * from empresa where empresa.RutEmisor = '"+ doc.RUTEmisor.ToString() +"'";
                        SQLiteCommand command = new SQLiteCommand(sql, myConn);
                        SQLiteDataReader reader = command.ExecuteReader();
                        while (reader.Read())
                        {

                            doc.Telefono = reader["Telefono"].ToString();
                            doc.CorreoEmisor = reader["CorreoEmisor"].ToString();
                            doc.Acteco = Convert.ToInt32(reader["Acteco"]);
                            doc.DirRegionalSII = reader["sucurSII"].ToString();
                            doc.DirMatriz = reader["DirMatriz"].ToString();
                            doc.NombreCertificado = reader["NomCertificado"].ToString();
                            doc.SucurEmisor = reader["SucurEmisor"].ToString();
                            doc.FchResol = reader["FchResol"].ToString();
                            doc.RutEnvia = reader["RutCertificado"].ToString();
                            doc.NumResol = reader["NumResol"].ToString();
                            doc.CondEntrega = reader["CondEntrega"].ToString();
                        }

                        myConn.Close();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: {0}", e.ToString());
                    }
               }

                objReader.Close();
                ms.Close();
                if (moveFile)
                {
                    file.mvFile(fileName, dirOrigen, "C:/AdmToFebosFiles/fileProcess/");
                }

                Caf caf = new Caf();

                if(!caf.isValid(doc))
                {
                    doc = null;
                }

                if (fileJson == "")
                {
                    doc.fileName = fileName;
                }
                else
                {
                    doc.fileName = fileJson;
                }
                return doc;
            }
            else
            {
                return null;
            }
        }
Example #14
0
		private static bool AddNewClassNameToCompileSection(StringBuilder sb, string line,
			bool isAdded, StreamReader sr)
		{
			sb.AppendLine(line);
			if (!line.Contains("<Compile Include=") || isAdded)
				return isAdded;
			if (sr.ToString().Contains("<Compile Include=" + '"' + sceneClassName + ".cs"))
				return false;
			sb.AppendLine("<Compile Include=" + '"' + sceneClassName + ".cs" + '"' + " />");
			return true;
		}
Example #15
0
        public Customer searchCustomer(int customerID, string firstName, string lastName, string phoneNumber)
        {
            XmlDocument xml = new XmlDocument();
            Customer customer = new Customer();

            var request = (HttpWebRequest)WebRequest.Create(SERVICE_URL + "Customers/" + customerID);

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            xml.LoadXml(responseString.ToString());

            XmlNodeList nodes = xml.GetElementsByTagName("Customer");

            foreach (XmlNode node in nodes)
            {
                XmlNodeList children = node.ChildNodes;

                foreach (XmlNode child in children)
                {
                    if (child.Name == "custID")
                    {
                        customer.customerID = Convert.ToInt32(child.InnerText);
                    }
                    else if (child.Name == "firstName")
                    {
                        customer.firstName = child.InnerText;
                    }
                    else if (child.Name == "lastName")
                    {
                        customer.lastName = child.InnerText;
                    }
                    else if (child.Name == "phoneNumber")
                    {
                        customer.phoneNumber = child.InnerText;
                    }
                }
            }

            return customer;
        }
 private EuLinksResponse PostRequestPlainText(String s)
 {
     EuLinksResponse e = null;
     var request = (HttpWebRequest)WebRequest.Create("http://techno.eucases.eu:8080/nlp-toolkit/rest/textminingservice/analyse");
     var postData = s;
     request.Method = "POST";
     request.Timeout = 2000000;
     request.ContentType = "text/plain";
     request.Accept = "application/json";
     byte[] byteArray = Encoding.UTF8.GetBytes(postData);
     request.ContentLength = byteArray.Length;
     using (var stream = request.GetRequestStream())
     {
         stream.Write(byteArray, 0, byteArray.Length);
     }
     var response = (HttpWebResponse)request.GetResponse();
     var res = new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
     e = JsonConvert.DeserializeObject<EuLinksResponse>(res.ToString());
     return e;
 }
Example #17
0
        private void OuvrirFichierCSV()
        {
            this.splitContainerPrincipal.Enabled = false;
            this.Cursor = Cursors.No;

            try
            {
                // Ouverture du fichier
                openCsvFileDialog.InitialDirectory = tbRepertoire.Text.ToString();

                if (DialogResult.OK == openCsvFileDialog.ShowDialog())
                {
                    tbNomFichierExport.Text = openCsvFileDialog.SafeFileName;
                    tbRepertoire.Text = openCsvFileDialog.FileName.Replace(openCsvFileDialog.SafeFileName, "");
                    StreamReader srFichier = new StreamReader(openCsvFileDialog.OpenFile(),System.Text.Encoding.Default);

                    //ChargerFichierCSVdansTampon(srFichier);
                    GestionnaireCSV.CaractèreSéparateur = tbCaractèreSéparateur.Text;
                    GestionnaireCSV.ControleNbColonnes = cbControlerNbColonnes.Checked;
                    GestionnaireCSV.TrimSpaces = cbTrimSpaces.Checked;

                    DataTable dtFichier = GestionnaireCSV.OuvrirFichierCSV(srFichier);
                    srFichier.Close();

                    FusionnerTamponCourant(dtFichier, "Fusion avec " + srFichier.ToString(), srFichier.ToString());

                    tabTampons.SelectedTab.Text = openCsvFileDialog.SafeFileName;
                    ActualiserAffichageSelonTampon();
                }
            }
            catch (Exception exception)
            {

                // Gestion des erreurs
                MessageBox.Show(
                    exception.Message,
                    "Erreur de chargement fichier",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error
                 );
            }

            this.splitContainerPrincipal.Enabled = true;
            this.Cursor = Cursors.Default;
        }
        static void Main(string[] args)
        {
            TextReader tr;
            TextWriter tw;
            string defaultEndpoint = "http://localhost:53033/validate/html";
            string defaultReadfile = @"C:\Users\Administrator\Documents\GitHub\LeanKit.Utilities\Validation.TestUtility\test.txt";
            string defaultWritefile = @"C:\Users\Administrator\Documents\GitHub\LeanKit.Utilities\Validation.TestUtility\test2.txt";
            string ep;
            string connectionString = null;
            string query = null;


            //handle options
            var options = new Options();
            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                if (options.inputFile != null)
                {
                    try
                    {
                        tr = new StreamReader(options.inputFile);
                        Console.WriteLine(String.Format("Input file is set as {0}", tr.ToString()));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(@"Cannot locate this file. Setting input at default value.");
                        tr = new StreamReader(defaultReadfile);

                    }
                }
                else
                {

                    tr = new StreamReader(defaultReadfile);
                    Console.WriteLine(@"Input file is set as C:\Users\Administrator\Documents\GitHub\LeanKit.Utilities\Validation.TestUtility\test.txt");

                }
                if (options.outputFile != null)
                {
                    tw = new StreamWriter(options.outputFile);
                    Console.WriteLine(String.Format("Output file is set as {0}", tw.ToString()));
                }
                else
                {
                    tw = new StreamWriter(defaultWritefile);
                    Console.WriteLine(defaultWritefile);
                }
                if (options.url != null)
                {
                    string url = options.url;
                    Console.WriteLine(String.Format(@"The url which will be scrapped is {0}", url));
                }
                if (options.endpoint != null)
                {
                    ep = options.endpoint;
                }
                else
                {

                    ep = defaultEndpoint;
                    Console.WriteLine(String.Format(@"The api endpoint set is{0}", defaultEndpoint));
                }
                //Check and set database variables
                if (options.dbserver != null && options.dbname != null && options.dbuser != null && options.dbpassword != null && options.dbquery != null)
                {
                    connectionString = String.Format(@"Data Source = {0}; Initial Catalog ={1}; Persist Security Info = true; User ID={2};Password={3}", options.dbserver, options.dbname, options.dbuser, options.dbpassword);
                    query = options.dbquery;
                }

            }
            else
            {
                string url;
                tr = new StreamReader(defaultReadfile);
                tw = new StreamWriter(defaultWritefile);
                ep = defaultEndpoint;
                connectionString = null;

            }

            ////////////////////////////////////////

            if (options.url != null)        //if scraping a url
            {

                Task<String> resp = scraper(options.url);

                if (resp.Result != null)
                {
                    Task<String> apiresp = ApiRequest(resp.Result, ep);
                    if (apiresp.Result != null)
                    {
                        string s = apiresp.Result;
                        tw.WriteLine("\tResult:\t{0}\n", s);
                    }
                    else
                    {
                        tw.WriteLine("\tResult: Format accepted\n");
                    }
                }
                else
                {
                    Console.WriteLine("No conent returned by requested URL\n");
                }
            }
            else if (options.dbserver != null && options.dbname != null && options.dbuser != null && options.dbpassword != null && options.dbquery != null) //else if testing against database
            {
                sqlTester(connectionString, query, tw, ep);

            }
            else    //else Basic check against file
            {
                string xssrequest;
                while ((xssrequest = tr.ReadLine()) != null)
                {
                    Task<String> resp = ApiRequest(xssrequest, ep);

                    if (resp != null)
                    {
                        string s = resp.Result;
                        tw.WriteLine("Result:\t{0}\n", s);
                    }

                }
            }



            //close files
            if (tr != null)
            {
                tr.Close();
            }
            tw.Close();

            Console.ReadLine();

        }
Example #19
0
        private List<SMapSensorReading> sendHTTPPostMultipolEndpoints(string endpoint, string body)
        {
            var request = (HttpWebRequest)WebRequest.Create(endpoint);

            var data = Encoding.ASCII.GetBytes(body);

            request.Method = "POST";
            request.ContentType = "application/raw";
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            var jsonObj = JsonConvert.DeserializeObject<List<SMapSensorReading>>(responseString.ToString());
            return jsonObj;
        }
Example #20
0
        internal void LoadStimWithWave(StreamReader olstimFile, int numStimToRead)
        {
            int j = 0;
            char delimiter = ' ';
            string[] splitWave;
            while ( j <= numStimToRead - 1)
            {
                line = olstimFile.ReadLine();
                if (line == null)
                    throw new Exception("error while loading stimuli from file " + olstimFile.ToString() + ": stim " + j + " of " + numStimToRead + " is missing. End of file: " + olstimFile.EndOfStream);

                // load stim time
                TimeVector[j] = Convert.ToUInt64(line);

                // load stime chan
                line = olstimFile.ReadLine();
                ChannelVector[j] = Convert.ToInt32(line);

                // load stim waveform
                if (cannedWaveform == null)
                {
                    line = olstimFile.ReadLine();
                    if (line == null)
                        throw new Exception("error while loading stimuli from file " + olstimFile.ToString() + ": stim " + j + " of " + numStimToRead + " is missing. End of file: " + olstimFile.EndOfStream);

                    splitWave = line.Split(delimiter);
                    for (int i = 0; i < splitWave.Length; ++i)
                    {
                        WaveMatrix[j, i] = Convert.ToDouble(splitWave[i]);
                    }
                }
                else
                {
                    for (int i = 0; i < cannedWaveform.Length; ++i)
                    {
                        WaveMatrix[j, i] = cannedWaveform[i];
                    }
                }
                j++;
            }
        }
Example #21
0
        public XmlDocument globalSearch(Dictionary<string, string> query)
        {
            XmlDocument xml = new XmlDocument();
            string formatedQuery = null;
            string trimmedQuery = null;
            string responseString = null;

            foreach (KeyValuePair<string, string> pair in query)
            {
                formatedQuery += pair.Key + "=" + pair.Value + "|";
            }

            if (formatedQuery.EndsWith("|"))
            {
                trimmedQuery = formatedQuery.TrimEnd('|');
            }

            var request = (HttpWebRequest)WebRequest.Create(SERVICE_URL + "search/" + trimmedQuery);

            try
            {
                var response = (HttpWebResponse)request.GetResponse();

                responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            }
            catch(Exception e)
            {
                responseString = e.Message;
            }

            xml.LoadXml(responseString.ToString());

            return xml;
        }
Example #22
0
        public Product searchProduct(int productID, string productName, float price, float productWeight, bool soldOut)
        {
            XmlDocument xml = new XmlDocument();
            Product product = new Product();

            var request = (HttpWebRequest)WebRequest.Create(SERVICE_URL + "Products/" + productID);

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            xml.LoadXml(responseString.ToString());

            XmlNodeList nodes = xml.GetElementsByTagName("Product");

            foreach (XmlNode node in nodes)
            {
                XmlNodeList children = node.ChildNodes;

                foreach (XmlNode child in children)
                {
                    if (child.Name == "prodID")
                    {
                        product.productID = Convert.ToInt32(child.InnerText);
                    }
                    else if (child.Name == "prodName")
                    {
                        product.productName = child.InnerText;
                    }
                    else if (child.Name == "price")
                    {
                        float tempValue;
                        float.TryParse(child.InnerText, out tempValue);
                        product.price = tempValue;
                    }
                    else if (child.Name == "prodWeight")
                    {
                        float tempValue;
                        float.TryParse(child.InnerText, out tempValue);
                        product.productWeight = tempValue;
                    }
                    else if (child.Name == "inStock")
                    {
                        bool tempValue;
                        bool.TryParse(child.InnerText, out tempValue);
                        product.soldOut = tempValue;
                    }
                }
            }

            return product;
        }
Example #23
0
        public Order searchOrder(int orderID, int customerID, string poNumber, string orderDate)
        {
            XmlDocument xml = new XmlDocument();
            Order order = new Order();

            var request = (HttpWebRequest)WebRequest.Create(SERVICE_URL + "Orders/" + orderID);

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            xml.LoadXml(responseString.ToString());

            XmlNodeList nodes = xml.GetElementsByTagName("Order");

            foreach (XmlNode node in nodes)
            {
                XmlNodeList children = node.ChildNodes;

                foreach (XmlNode child in children)
                {
                    if (child.Name == "orderID")
                    {
                        order.orderID = Convert.ToInt32(child.InnerText);
                    }
                    else if (child.Name == "custID")
                    {
                        order.customerID = Convert.ToInt32(child.InnerText);
                    }
                    else if (child.Name == "poNumber")
                    {
                        order.poNumber = child.InnerText;
                    }
                    else if (child.Name == "orderDate")
                    {
                        order.orderDate = child.InnerText;
                    }
                }
            }

            return order;
        }
 /*private static string HtmlToPlainText(string html)
 {
     const string tagWhiteSpace = @"(>|$)(\W|\n|\r)+<";//matches one or more (white space or line breaks) between '>' and '<'
     const string stripFormatting = @"<[^>]*(>|$)";//match any character between '<' and '>', even when end tag is missing
     const string lineBreak = @"<(br|BR)\s{0,1}\/{0,1}>";//matches: <br>,<br/>,<br />,<BR>,<BR/>,<BR />
     var lineBreakRegex = new Regex(lineBreak, RegexOptions.Multiline);
     var stripFormattingRegex = new Regex(stripFormatting, RegexOptions.Multiline);
     var tagWhiteSpaceRegex = new Regex(tagWhiteSpace, RegexOptions.Multiline);
     var text = html;
     //Decode html specific characters
     text = System.Net.WebUtility.HtmlDecode(text);
     //Remove tag whitespace/line breaks
     text = tagWhiteSpaceRegex.Replace(text, "><");
     //Replace <br /> with line breaks
     text = lineBreakRegex.Replace(text, Environment.NewLine);
     //Strip formatting
     text = stripFormattingRegex.Replace(text, string.Empty);
     return text;
 }*/
 /// <summary>
 /// Get document hint/tooltip
 /// </summary>
 /// <param name="lang">short string language</param>
 /// <param name="celex">CELEX number of the document</param>
 /// <param name="rf">Ref; an anchor within the document body, referenced by its CELEX; not mandatory</param>
 /// <returns>The doc hint/tooltip</returns>
 public string GetDocHint(string lang, string celex, string rf)
 {
     //http://app.eurocases.eu/api/Doc/ParHint/{LangId}/{docNumber}/{toPar}
     string u = "http://app.eurocases.eu/api/Doc/ParHint/" + l2lid(lang) + "/" + LCID2LangId(LCID).ToString() + "/" + celex + ((rf == "") ? "" : "/" + rf), c = "";
     if (u == "") return "";
     int x = Environment.TickCount;
     if (x - LastUrlMom < 3000 && LastCalledUrl == u) return "";
     LastUrlMom = x;
     LastCalledUrl = u;
     HttpWebRequest q = (HttpWebRequest)WebRequest.Create(u);
     try
     {
         q.Method = "GET";
         q.Timeout = 2000;
         q.ContentType = "text/plain";
         q.Accept = "application/json";
         HttpWebResponse r = (HttpWebResponse)q.GetResponse();
         var s = new StreamReader(r.GetResponseStream(), Encoding.UTF8).ReadToEnd();
         c = s.ToString();
     }
     catch (Exception e)
     {
         c = "Exception fetching the hint: " + e.Message;
     }
     return c;
 }
 private string strCite(int aType) {
     Word.Hyperlink h = GetCurrentHyperlink();
     if (h == null) return "";
     rUrl r = GetRUrl(h);
     //if(r.IsTerm)return "";
     string u = "http://app.eurocases.eu/api/Doc/Cite/" + r.langid + "/" + r.celex + "/" + aType.ToString(), c = "";
     HttpWebRequest q = (HttpWebRequest)WebRequest.Create(u);
     try
     {
         q.Method = "GET";
         q.Timeout = 2000;
         q.ContentType = "text/plain";
         q.Accept = "application/json";
         HttpWebResponse p = (HttpWebResponse)q.GetResponse();
         var s = new StreamReader(p.GetResponseStream(), Encoding.UTF8).ReadToEnd();
         c = s.ToString();
     }
     catch (Exception e){}
     return c;
 }
Example #26
0
        public bool isValid(Documento doc)
        {
            bool valid = true;

            String xmlCaf = String.Empty;
            String cafDir = String.Empty;

            fileAdmin file = new fileAdmin();

            string rut = doc.RUTEmisor;

            try
            {
                switch (doc.TipoDTE)
                {
                    case 33: cafDir = @"C:\IatFiles\cafs\" + rut + @"\factura\";
                        break;
                    case 61: cafDir = @"C:\IatFiles\cafs\" + rut + @"\notacredito\";
                        break;
                    case 56: cafDir = @"C:\IatFiles\cafs\" + rut + @"\notadebito\";
                        break;
                    case 52: cafDir = @"C:\IatFiles\cafs\" + rut + @"\Guia\";
                        break;
                    case 34: cafDir = @"C:\IatFiles\cafs\" + rut + @"\facturaexenta\";
                        break;
                }

                xmlCaf = file.nextFile(cafDir, "*.xml");

                String xml = String.Empty;

                if (xmlCaf != null)
                {
                    StreamReader objReader = new StreamReader(xmlCaf, System.Text.Encoding.Default, true);
                    objReader.ToString();
                    xml = objReader.ReadToEnd();
                }

                int start = xml.IndexOf("<TD") + 4;
                int end = xml.IndexOf("</TD>");
                int largo = end - start;

                // Valida tipo de documento
                String td = xml.Substring(start, largo);
                if (td != doc.TipoDTE.ToString()) valid = false;

                start = xml.IndexOf("<FA>") + 4;
                end = xml.IndexOf("</FA>");
                largo = end - start;
                // Valida FECHA de documento
                String fch = xml.Substring(start, largo);

                DateTime fchCaf = DateTime.ParseExact(fch, "yyyy-MM-dd",
                                       System.Globalization.CultureInfo.InvariantCulture);

                DateTime fEmis = DateTime.ParseExact(fch, "yyyy-MM-dd",
                       System.Globalization.CultureInfo.InvariantCulture);

                if (fEmis > fchCaf)
                {
                    valid = false;
                }

                start = xml.IndexOf("<D>") + 3;
                end = xml.IndexOf("</D>");
                largo = end - start;
                String d = xml.Substring(start, largo);

                start = xml.IndexOf("<H>") + 3;
                end = xml.IndexOf("</H>");
                largo = end - start;
                String h = xml.Substring(start, largo);

                // Valida Folio del documento dentro del rango CAF
                int ds = Convert.ToInt32(d);
                int hs = Convert.ToInt32(h);

                // TO DO: Descomentar esta linea para el proceso de producción
            //    if (!((folio < hs) && (folio >ds)) ) valid = false;

                // OTRAS VALIDACIONES
                if (doc.CiudadRecep == null || doc.CiudadRecep == String.Empty ) valid = false;
                if (doc.CmnaRecep == null || doc.CmnaRecep == String.Empty) valid = false;

            }
            catch (Exception e)
            {
                Console.WriteLine("The file CAF could not be read:");
                Console.WriteLine(e.Message);
            }

            return valid;
        }
 private JsonResp PostRequestPlainText(String s)
 {
     JsonResp e = null;
     //http://techno.eucases.eu/FrontEndREST/api/Links/PutHtmlLinks/
     string surl = bUseHtml ? "http://techno.eucases.eu/FrontEndREST/api/Links/PutLinksHtmlPipeline" : "http://techno.eucases.eu/FrontEndREST/api/Links/PutLinksTextPipeline";
     // Alternative : http://techno.eucases.eu/FrontEndREST/api/Links/PutLinksTextPipeline (plain text)
     var request = (HttpWebRequest)WebRequest.Create(surl);
     var postData = s;
     request.Method = "POST";
     request.Timeout = 2000000;
     request.ContentType = "text/plain";
     request.Accept = "application/json";
     byte[] byteArray = Encoding.UTF8.GetBytes(postData);
     request.ContentLength = byteArray.Length;
     using (var stream = request.GetRequestStream())
         stream.Write(byteArray, 0, byteArray.Length);
     var response = (HttpWebResponse)request.GetResponse();
     var res = new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
     e = JsonConvert.DeserializeObject<JsonResp>(res.ToString());
     var tmp = e.results.entity.ToList();
     e.results.entity.Clear();
     e.results.entity.AddRange(tmp.OrderByDescending(x => x.begin));
     //e.results.entity.Reverse();
     return e;
 }
Example #28
0
        public Cart searchCart(int orderID, int productID, int quantity)
        {
            XmlDocument xml = new XmlDocument();
            Cart cart = new Cart();

            var request = (HttpWebRequest)WebRequest.Create(SERVICE_URL + "Carts/" + orderID);

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            xml.LoadXml(responseString.ToString());

            XmlNodeList nodes = xml.GetElementsByTagName("cart");

            foreach (XmlNode node in nodes)
            {
                XmlNodeList children = node.ChildNodes;

                foreach (XmlNode child in children)
                {
                    if (child.Name == "orderID")
                    {
                        cart.orderID = Convert.ToInt32(child.InnerText);
                    }
                    else if (child.Name == "prodID")
                    {
                        cart.productID = Convert.ToInt32(child.InnerText);
                    }
                    else if (child.Name == "quantity")
                    {
                        cart.quantity = Convert.ToInt32(child.InnerText);
                    }
                }
            }

            return cart;
        }