Ejemplo n.º 1
3
        public static string ExtractTextFromPdf(string path)
        {
            ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();

            using (PdfReader reader = new PdfReader(path))
            {
                StringBuilder text = new StringBuilder();

                for (int page = 1; page <= reader.NumberOfPages; page++)
                {
                    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();

                    string currentText = PdfTextExtractor.GetTextFromPage(reader, page, strategy);

                    currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
                    text.Append(currentText);
                }

                System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
                file.WriteLine(text);

                file.Close();

                return text.ToString();
            }
        }
Ejemplo n.º 2
2
        public void TryPrint(string zplCommands)
        {
            try
            {
                // Open connection
                System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
                client.Connect(this.m_IPAddress, this.m_Port);

                // Write ZPL String to connection
                System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream());
                writer.Write(zplCommands);
                writer.Flush();

                // Close Connection
                writer.Close();
                client.Close();
            }
            catch (Exception ex)
            {
                this.m_ErrorCount += 1;
                if(this.m_ErrorCount < 10)
                {
                    System.Threading.Thread.Sleep(5000);
                    this.TryPrint(zplCommands);
                }
                else
                {
                    throw ex;
                }
            }
        }
Ejemplo n.º 3
0
 private void button3_Click(object sender, EventArgs e)
 {
     //http://vspro1.wordpress.com/2011/02/28/export-to-a-text-file-from-a-datagridview-control/
     System.IO.StreamWriter file = new System.IO.StreamWriter(@"TextFile.txt");
     try
     {
         string sLine = "";
         //This for loop loops through each row in the table
         for (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
         {
             //This for loop loops through each column, and the row number
             //is passed from the for loop above.
             for (int c = 0; c <= dataGridView1.Columns.Count - 1; c++)
             {
                 sLine = sLine + dataGridView1.Rows[r].Cells[c].Value;
                 if (c != dataGridView1.Columns.Count - 1)
                 {
                     //A comma is added as a text delimiter in order
                     //to separate each field in the text file.
                     //You can choose another character as a delimiter.
                     sLine = sLine + ",";
                 }
             }
             //The exported text is written to the text file, one line at a time.
             file.WriteLine(sLine);
             sLine = "";
         }
         file.Close();
        // System.Windows.Forms.MessageBox.Show("Export Complete.", "Program Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
     catch (System.Exception err)
     {
         System.Windows.Forms.MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         file.Close();
     }
     DialogResult show1 = MessageBox.Show("Muon Mo Folder Khong","Important",MessageBoxButtons.YesNo,MessageBoxIcon.Information);
     switch (show1)
     {
         case DialogResult.Abort:
             break;
         case DialogResult.Cancel:
             break;
         case DialogResult.Ignore:
             break;
         case DialogResult.No:
             break;
         case DialogResult.None:
             break;
         case DialogResult.OK:
             break;
         case DialogResult.Retry:
             break;
         case DialogResult.Yes:
             System.Diagnostics.Process.Start(System.Environment.CurrentDirectory);
             break;
         default:
             break;
     }
 }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            System.IO.StreamWriter outputFile1 = new System.IO.StreamWriter(@"d:\T2Integers");
            System.IO.StreamWriter outputFile2 = new System.IO.StreamWriter(@"d:\T2Doubless");
            int number = 0;
            bool result;

            
 
            do
            {
                Console.WriteLine("Give a number: ");
                string line = Console.ReadLine();
               result = int.TryParse(line, out number);
                if (result)
                {
                    
                    outputFile1.WriteLine(line);
                }
                else 
                {
                    
                    outputFile2.WriteLine(line);
                }

            } while (!number.Equals(""));
            outputFile1.Close();
            outputFile2.Close();
        }
Ejemplo n.º 5
0
        private void ExportToExcel()
        {
            try
            {
                Utils.Log.InfoFormat("Exporting case list to Excel ({0} cases)", dropCaseList.Items.Count);

                String tempTabSep = System.IO.Path.GetTempPath() + "cases_" + (Guid.NewGuid()).ToString() + ".txt";
                // create a writer and open the file
                System.IO.TextWriter tw = new System.IO.StreamWriter(tempTabSep);

                for (int i = 1; i < dropCaseList.Items.Count; ++i)
                {
                    Case c = (Case)dropCaseList.Items[i];
                    tw.WriteLine("({0:D}) {1}\t{2}h\t{3}", c.ID, c.Name, c.Estimate.TotalHours, c.AssignedTo);
                }

                tw.Close();
                System.Diagnostics.Process.Start("excel.exe", "\"" + tempTabSep + "\"");
            }
            catch (System.Exception x)
            {
                MessageBox.Show("Sorry, couldn't launch Excel");
                Utils.Log.Error(x.ToString());
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Saves the colourz
        /// </summary>
        public void save()
        {
            if (!System.IO.Directory.Exists(Constants.CACHE_PATH))
            {
                System.IO.Directory.CreateDirectory(Constants.CACHE_PATH);
            }

            if (!System.IO.Directory.Exists(Constants.CACHE_PATH))
            {
                Console.WriteLine("Created directory");
                System.IO.Directory.CreateDirectory(Constants.CACHE_PATH);
            }

            System.IO.File.WriteAllBytes(Constants.CACHE_PATH + "Saved Colours.txt", new byte[0]);
            System.IO.StreamWriter file = new System.IO.StreamWriter(Constants.CACHE_PATH + "Saved Colours.txt", true);
            
            string saveText = "";
            for(int i = 0; i < stack.Children.Count; i++)
            {
                SavedColour s = (SavedColour)stack.Children[i];

                if(i != stack.Children.Count)
                    saveText += s.hex + ";";
            }
            file.WriteLine(saveText);
            file.Flush();
            file.Close();
        }
Ejemplo n.º 7
0
 private void ButtonPhoto_Click(object sender, EventArgs e)
 {
     var flickr = new Flickr(Program.ApiKey, Program.SharedSecret, Program.AuthToken);
     // Referrers
     DateTime day = DateTime.Today;
     var statfile = new System.IO.StreamWriter("stats_dom.csv");
     var reffile = new System.IO.StreamWriter("stats_referrers.csv");
     while (day > Program.LastUpdate)
     {
         try
         {
             var s = flickr.StatsGetPhotoDomains(day, 1, 100);
             day -= TimeSpan.FromDays(1);
             StatusLabel.Text = "Chargement des domaines " + day.ToShortDateString();
             Application.DoEvents();
             statfile.Write(Utility.toCSV(s, day.ToShortDateString()));
             foreach (StatDomain dom in s)
             {
                 var r = flickr.StatsGetPhotoReferrers(day, dom.Name, 1, 100);
                 reffile.Write(Utility.toCSV(r, day.ToShortDateString() + ";" + dom.Name));
             }
         }
         catch (FlickrApiException ex)
         {
             MessageBox.Show("Erreur lors du chargement des domaines référents du "
                 + day.ToShortDateString() + " : " + ex.OriginalMessage,
                 "Erreur", MessageBoxButtons.OK);
             break;
         }
     }
     statfile.Close();
 }
Ejemplo n.º 8
0
        private void SaveBtn_Click(object sender, EventArgs e)
        {
            string path = pathText.Text;

            if (path.Length < 1 || path.Trim().Length < 1) {
                MessageBox.Show("Invalid path name.", "Invalid path");
                return;
            }

            foreach (char c in System.IO.Path.GetInvalidFileNameChars()) {
                if (path.Contains(c)) {
                    MessageBox.Show("Invalid character '" + c + "' in file path.", "Invalid path");
                    return;
                }
            }

            if (!System.IO.Path.HasExtension(path))
                path += ".lua";

            if (!overwriteCheckBox.Checked && System.IO.File.Exists(path)) {
                MessageBox.Show("File '" + path + "' already exists.", "File already exists");
                return;
            }

            string lua = Derma.GenerateLua();

            System.IO.TextWriter file = new System.IO.StreamWriter(path);
            file.Write(lua);
            file.Close();

            MessageBox.Show("Lua generated to file '" + path + "'.", "Success");

            this.Close();
        }
Ejemplo n.º 9
0
 private void WriteLog (Exception e)
 {
     var ws = new System.IO.StreamWriter("error.log",true );
     ws.WriteLine(e);
     ws.WriteLine("");
     ws.Close();
 }
        public void Send(object sender, EventArgs args)
        {
            try
            {
                var publishArgs = args as Sitecore.Events.SitecoreEventArgs;

                var publisher = publishArgs.Parameters[0] as Sitecore.Publishing.Publisher;

                var publisherOptions = publisher.Options;

                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("localhost");

                mail.From = new MailAddress("*****@*****.**");
                mail.To.Add("*****@*****.**");
                mail.Subject = "Someone published the item " + publisherOptions.RootItem.Paths.FullPath;
                mail.Body = publisherOptions.RootItem.Fields["body"].Value;
                SmtpServer.Send(mail);

                string lines = publisherOptions.RootItem.Fields["body"].Value;

                // Write the string to a file.
                System.IO.StreamWriter file = new System.IO.StreamWriter("D:\\Git\\Eduserv-Github-Example\\Source\\Website\\BritishLibrary.Website\\test.xml");
                file.WriteLine(lines);

                file.Close();

            }
            catch (Exception ex)
            {
                Console.WriteLine("Seems some problem!");
            }
        }
Ejemplo n.º 11
0
        public static void Write(String metodo, Exception ex)
        {
            String fecha = DateTime.Now.ToString("dd/MM/yyyy hh:MM:ss");

            String archivo = "C:\\TEMP\\ErrorBaseDatos" + DateTime.Now.ToString("dd/MM/yyyy") + ".txt";
            try
            {

                System.IO.StreamWriter file = new System.IO.StreamWriter(@archivo, true);
                file.WriteLine("------------------------------------------");
                file.WriteLine("Método :" + metodo);
                file.WriteLine("Fecha  :" + fecha);
                file.WriteLine("Detalle");
                file.WriteLine("\n");
                file.WriteLine("Message " + ex.Message);
                file.WriteLine("\n");
                file.WriteLine("StackTrace " + ex.StackTrace);
                file.WriteLine("\n");
                file.WriteLine("Source " + ex.Source);
                file.WriteLine("\n");
                file.WriteLine("ToString() " + ex.ToString());
                file.WriteLine("------------------------------------------");
                file.WriteLine("\n");
                file.Close();
            }
            catch { }
        }
Ejemplo n.º 12
0
        private void AddFileEventLog(string message, EventLogEntryType logType = EventLogEntryType.Information, string moduleName = "", int codeErreur = 0, bool fromWindowsLogEvent = false)
        {
            System.IO.StreamWriter w = null;
            System.Text.StringBuilder str = new System.Text.StringBuilder();

            try {
                string strPath = System.IO.Path.GetDirectoryName(_logFilePath);
                if (!System.IO.Directory.Exists(strPath))
                    System.IO.Directory.CreateDirectory(strPath);

                w = new System.IO.StreamWriter(_logFilePath, true, System.Text.Encoding.Default);

                str.AppendFormat("[{0,-10:G} - {1,-8:G}]", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString());
                str.AppendFormat(" {0}", Const.DEFAULT_APPLICATION_NAME);
                if (!string.IsNullOrEmpty(moduleName))
                    str.AppendFormat(" ({0})", moduleName);
                str.AppendFormat(" - {0}", logType.ToString());
                if (codeErreur != 0)
                    str.AppendFormat(" - Code : {0}", codeErreur);

                str.Append("\r\n");
                str.Append(message);
                str.Append("\r\n");

                w.WriteLine(str.ToString());
            } catch (Exception ex) {
                if (!fromWindowsLogEvent) {
                    AddWindowsEventLog("Impossible d'écrire dans le fichier de log : " + _logFilePath + "\r\n" + message + "\r\nException : " + ex.Message, EventLogEntryType.Error, moduleName, 0, true);
                }
            } finally {
                if ((w != null))
                    w.Close();
            }
        }
Ejemplo n.º 13
0
 public void save()
 {
     System.IO.StreamWriter m_stwSave = new System.IO.StreamWriter(".\\CCDate.dat", false);
     m_stwSave.WriteLine(strCCKey);
     m_stwSave.WriteLine(strSaveKey);
     m_stwSave.Close();
 }
Ejemplo n.º 14
0
        private void submitButton_Click(object sender, RoutedEventArgs e)
        {
            var login = loginTextBox.Text;
            var pass = passwordTextBox.Password;

            Action<String> status = s => {
                statusLabel.Content = s;
                statusLabel.ToolTip = s;
            };

            try {
                channelFactory = new DuplexChannelFactory<IService>(new ClientImplementation(_MainWindow), "DnDServiceEndPoint");
                server = channelFactory.CreateChannel();

                if (server.Login(login, pass)) {
                    _MainWindow.InitializeServer(channelFactory, server);
                    this.DialogResult = true;
                } else {
                    statusLabel.Content = "Login lub hasło nie są poprawne!";
                    return;
                }

            } catch (Exception ex) {
                statusLabel.Content = "Nastąpił błąd! Spróbuj ponownie";
                System.IO.StreamWriter file = new System.IO.StreamWriter("log.txt");
                file.WriteLine(ex.ToString());
                file.Close();
                return;
            }
            this.Close();
        }
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            //string xml;
               Contact contact = new Contact();

            contact.companyName = txtCompany.Text;
            contact.firstName = txtFName.Text;
            contact.middleName = txtMName.Text;
            contact.lastName = txtLName.Text;
            contact.liscence = txtLicense.Text;
            contact.phone = txtPhone.Text;
            contact.cell = txtCell.Text;
            contact.email = txtEmail.Text;
            contact.buildingLiscence = txtBuildingLicense.Text;
            contact.streetNumber = txtStreetNumber.Text;
            contact.streetName = txtStreetName.Text;
            contact.type = txtType.Text;
            contact.streetName2 = txtStreetName2.Text;
            contact.city = txtCity.Text;
            contact.state = txtState.Text;
            contact.zip = txtZip.Text;
            System.IO.StreamWriter file = new System.IO.StreamWriter(@"Contact.xml");
            System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(contact.GetType());
            x.Serialize(file, contact);
            file.Close();
        }
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            RadioButton rbFullScreen = UIHelpers.FindChild<RadioButton>(this, "rbFullScreen");

            if (rbFullScreen.IsChecked.Value)
            {
                Settings.GetInstance().Mode = Settings.ScreenMode.Fullscreen;
                PageNavigator.MainWindow.WindowStyle = WindowStyle.None;
                PageNavigator.MainWindow.WindowState = WindowState.Maximized;
                PageNavigator.MainWindow.Focus();
            }
            else
            {
                Settings.GetInstance().Mode = Settings.ScreenMode.Windowed;
            }

            ComboBox cbLanguage = UIHelpers.FindChild<ComboBox>(this, "cbLanguage");
            AppSettings.GetInstance().setLanguage((Language)cbLanguage.SelectedItem);

            System.IO.StreamWriter file = new System.IO.StreamWriter(AppSettings.getCommonApplicationDataPath() + "\\game.settings");
            file.WriteLine(AppSettings.GetInstance().getLanguage().Name);
            file.WriteLine(Settings.GetInstance().Mode);
            file.Close();

            //PageNavigator.NavigateTo(new PageStartMenu());
        }
Ejemplo n.º 17
0
 private void button1_Click(object sender, EventArgs e)
 {
     System.IO.StreamWriter sw = new System.IO.StreamWriter("nastr.txt");
     sw.WriteLine(textBox1.Text);
     sw.WriteLine(textBox2.Text);
     sw.Close();
 }
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            string[] funcListUrls = {
                                        //"http://www.xqueryfunctions.com/xq/c0008.html",
                                        //"http://www.xqueryfunctions.com/xq/c0011.html",
                                        //"http://www.xqueryfunctions.com/xq/c0002.html",
                                        //"http://www.xqueryfunctions.com/xq/c0013.html",
                                        //"http://www.xqueryfunctions.com/xq/c0015.html",
                                        "http://www.xqueryfunctions.com/xq/c0026.html",
                                        "http://www.xqueryfunctions.com/xq/c0033.html",
                                        "http://www.xqueryfunctions.com/xq/c0021.html",
                                        "http://www.xqueryfunctions.com/xq/c0023.html",
                                        "http://www.xqueryfunctions.com/xq/c0072.html"
                                    };

            foreach (string funcListUrl in funcListUrls)
            {
                FuncList[] funcLists = ParseFuncList(funcListUrl);
                foreach (FuncList funcList in funcLists)
                {
                    System.IO.StreamWriter testFile = new System.IO.StreamWriter(TESTCASE_FILE, true);
                    testFile.WriteLine("\n<!-- " + funcList.funcName + " - " + funcList.subcat + ": " + funcList.funclist.Length + " cases -->");
                    testFile.Close();
                    testFile = null;
                    foreach (string name in funcList.funclist)
                    {
                        string url = "http://www.xqueryfunctions.com/xq/functx_" + name + ".html";
                        Console.WriteLine("Parsing " + url + " ...");
                        ParseURL(funcList.funcName, funcList.subcat, url);
                    }
                }
            }
        }
Ejemplo n.º 19
0
        private void buttonSiguiente_Click(object sender, EventArgs e)
        {
            if (opcion == 0)
            {
                if (textBoxNombre.Text == "" || (radioButtonMasculino.Checked == false && radioButtonFemenino.Checked == false))
                    MessageBox.Show("Es necesario llenar los campos de Nombre y Sexo");
                else
                {
                    string sexo = "";
                    if (radioButtonMasculino.Checked == true) sexo = "Masculino";
                    if (radioButtonFemenino.Checked == true) sexo = "Femenino";

                    string text = usuario + "|" + textBoxNombre.Text + "|" + textBoxCURP.Text + "|" + textBoxRFC.Text + "|" + textBoxCelular.Text + "|" + textBoxTelefono.Text + "|" + textBoxDireccion.Text + "|" + sexo.ToString() + "|" + textBoxLugarDeNacimiento.Text + "|" + textBoxNacFecha1.Text + "|" + textBoxNacFecha2.Text + "|" + textBoxNacFecha3.Text + "|" + textBoxEdad.Text + "|" + textBoxEmailLaboral.Text + "|" + textBoxEmailPersonal.Text + "|" + textBoxTipoDeSangre.Text + "|" + textBoxNumeroDeEmergencia.Text + "|" + textBoxContactoDeEmergencia.Text + "|" + textBoxParentesco.Text + "|" + textBoxDireccionDelContacto.Text + "|" + textBoxOtrasOcupaciones.Text + "|" + textBoxOtrasOcupaciones.Text + "|" + textBoxEstadoCivil.Text + "|" + textBoxStatusFamiliar.Text + "|";

                    System.IO.StreamWriter file = new System.IO.StreamWriter("BDP_ELYON.elyon", true);
                    file.WriteLine(text);
                    file.Flush();
                    file.Close();
                    this.Close();
                }
            }
            if (opcion == 1) {
                string sexo = "";
                if (radioButtonMasculino.Checked == true) sexo = "Masculino";
                if (radioButtonFemenino.Checked == true) sexo = "Femenino";

                string text = usuario + "|" + textBoxNombre.Text + "|" + textBoxCURP.Text + "|" + textBoxRFC.Text + "|" + textBoxCelular.Text + "|" + textBoxTelefono.Text + "|" + textBoxDireccion.Text + "|" + sexo.ToString() + "|" + textBoxLugarDeNacimiento.Text + "|" + textBoxNacFecha1.Text + "|" + textBoxNacFecha2.Text + "|" + textBoxNacFecha3.Text + "|" + textBoxEdad.Text + "|" + textBoxEmailLaboral.Text + "|" + textBoxEmailPersonal.Text + "|" + textBoxTipoDeSangre.Text + "|" + textBoxNumeroDeEmergencia.Text + "|" + textBoxContactoDeEmergencia.Text + "|" + textBoxParentesco.Text + "|" + textBoxDireccionDelContacto.Text + "|" + textBoxOtrasOcupaciones.Text + "|" + textBoxOtrasOcupaciones.Text + "|" + textBoxEstadoCivil.Text + "|" + textBoxStatusFamiliar.Text + "|";

                editarArchivo(1, text);

                this.Close();
            }
        }
Ejemplo n.º 20
0
 public static void WriteException(String pMethod, Exception pException)
 {
     String date = DateTime.Now.ToString("dd/MM/yyyy hh:MM:ss");
     String archieve = "C:\\TEMP\\MIToolDatabaseLog" + DateTime.Now.ToString("dd/MM/yyyy") + ".txt";            
     try
     {
         System.IO.StreamWriter file = new System.IO.StreamWriter(archieve, true);
         file.WriteLine("------------------------------------------");
         file.WriteLine("Method :" + pMethod);
         file.WriteLine("Date :" + date);
         file.WriteLine("Detail");
         file.WriteLine("\n");
         file.WriteLine("Message " + pException.Message);
         file.WriteLine("\n");
         file.WriteLine("StackTrace " + pException.StackTrace);
         file.WriteLine("\n");
         file.WriteLine("Source " + pException.Source);
         file.WriteLine("\n");
         file.WriteLine("ToString() " + pException.ToString());
         file.WriteLine("------------------------------------------");
         file.WriteLine("\n");
         file.Close();
     }
     catch { }
 }
Ejemplo n.º 21
0
 private void GravarDados(ClienteInfo cli)
 {
     System.IO.StreamWriter sw = new System.IO.StreamWriter(cli.NomeArquivo(),true);
     //aqui a data é formatada
     sw.WriteLine(cli.Nome + ";" +cli.Email + ";" + cli.Telefone + ";" + cli.ClienteDesde.ToShortDateString());
     sw.Close();
 }
Ejemplo n.º 22
0
        public void generateDmcColors()
        {
            System.IO.StreamReader inFile = new System.IO.StreamReader(webPageDirectory);
            System.IO.StreamWriter outFile = new System.IO.StreamWriter(dmcDirectory, true);
            string line = "", dmc = "", name = "", color = "";

            while ((line = inFile.ReadLine()) != null)
            {
                if (line.Trim().StartsWith("<TD><FONT face=\"arial, helvetica, sans-serif\" size=2>") && !line.Trim().EndsWith("Select view")) //find dmc
                {
                    dmc = line.Trim().Split(new string[] { "<TD><FONT face=\"arial, helvetica, sans-serif\" size=2>" }, StringSplitOptions.None)[1];
                    dmc = dmc.Split(new string[] { "<" }, StringSplitOptions.None)[0];
                }
                else if (line.Trim().StartsWith("<TD noWrap><FONT face=\"arial, helvetica, sans-serif\" size=2>"))  //find name
                {
                    //issue with line continuation
                    name = line.Trim().Split(new string[] { "<TD noWrap><FONT face=\"arial, helvetica, sans-serif\" size=2>" }, StringSplitOptions.None)[1];
                    name = name.Split(new string[] { "<" }, StringSplitOptions.None)[0];
                    if (!line.Trim().EndsWith("</FONT></TD>"))
                    {
                        line = inFile.ReadLine();
                        name = name + " " + line.Trim().Split(new string[] { "<" }, StringSplitOptions.None)[0];
                    }
                }
                else if (line.Trim().StartsWith("<TD bgColor=") && line.Trim().Contains(">&nbsp;</TD>"))
                {
                    color = line.Trim().Split(new string[] { "<TD bgColor=" }, StringSplitOptions.None)[1];
                    color = color.Split(new string[] { ">" }, StringSplitOptions.None)[0];
                    outFile.WriteLine(dmc + ";" + name + ";" + color);
                }
            }
            inFile.Close();
            outFile.Close();
            Console.ReadLine();
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Prends en parametres le nom et une chaine de caracteres
 /// Ecrit la chaine de caracteres dans le fichier
 /// Cree le fichier si il n'existe pas
 /// </summary>
 /// <param name="name">Nom du fichier</param>
 /// <param name="content">Contenu du fichier</param>
 public static void writeFile(string name, string content)
 {
     try
     {
         System.IO.StreamWriter outstream = new System.IO.StreamWriter(name);
         outstream.Write(content);
         outstream.Close();
     }
     catch (System.IO.DirectoryNotFoundException)
     {
         try
         {
             System.IO.Directory.CreateDirectory(name);
             System.IO.Directory.Delete(name);
             writeFile(name, content);
         }
         catch (Exception)
         {
             Console.WriteLine("FileStream.writeFile : Erreur lors de la creation du repertoire " + name);
         }
     }
     catch (Exception)
     {
         Console.WriteLine("FileStream.writeFile : Erreur lors de l'ecriture dans le fichier " + name);
     }
 }
Ejemplo n.º 24
0
        public BIM.BusinessEntities.VerificadorPLD ServicioVerificadorPLD(BIM.BusinessEntities.BitacoraPLD parametros)
        {
            BIM.BusinessEntities.VerificadorPLD result = null;
            try
            {
                result = (new VerificadorPLDLogic()).ServicioVerificadorPLD(parametros);
            }
            catch (Exception ex)
            {
#if(DEBUG)


                const string fic = @"C:\inetpub\wwwroot\PLD\Prueba.txt";
                string texto = ex.Message;

                System.IO.StreamWriter sw = new System.IO.StreamWriter(fic);
                sw.WriteLine(texto);
                sw.Close();

                
                //Console.WriteLine("Error en VerificadorPLDServices.ServicioVerificadorPLD: " + ex.Message);

                //if (!EventLog.SourceExists(cs))
                //    EventLog.CreateEventSource(cs, "Application");

                //EventLog.WriteEntry(cs, ex.Message, EventLogEntryType.Error);
#else
                    EventLogManager.LogErrorEntry("Error en VerificadorPLDServices.ServicioVerificadorPLD: " + ex.Message);
                    //TODO: Codificar envío de notificación de error al EventLog
#endif
            }
            return result;
        }
Ejemplo n.º 25
0
 private void receives(object state)
 {
     while (true)
     {
         try
         {
             NETcollectionUdp[] netclist = getUdpList();
             foreach (NETcollectionUdp tempnetc in netclist)
             {
                 IPEndPoint anyEndPoint = new IPEndPoint(IPAddress.Any, 0);
                 EndPoint remoteEndPoint = anyEndPoint;
                 if (tempnetc.Soc != null)
                 {
                     byte[] data;
                     if (tempnetc.Soc.Available > 1)
                     {
                         data = new byte[tempnetc.Soc.Available];
                         int recv = tempnetc.Soc.Receive(data, 0, data.Length, SocketFlags.None);
                         tempnetc.Soc.SendTo(data, tempnetc.Iep);
                     }
                 }
             }
             System.Threading.Thread.Sleep(100);
         }
         catch (Exception e)
         {
             System.IO.StreamWriter sw = new System.IO.StreamWriter("send.txt", true);
             sw.WriteLine(e.Message);
             sw.Close();
         }
     }
 }
        public static void Error()
        {
            IntPtr ptr;

            Assert.Throws<Exception>(() => DynamicLibrary.Open("NOT_EXISTING"));

            string failure = "FAILURE";
            var fs = new System.IO.StreamWriter(System.IO.File.OpenWrite(failure));
            fs.Write("foobar");
            fs.Close();

            Assert.IsTrue(System.IO.File.Exists(failure));
            Assert.Throws<Exception>(() => DynamicLibrary.Open(failure));

            System.IO.File.Delete(failure);

            var dl = DynamicLibrary.Open(DynamicLibrary.Decorate("uv"));

            Assert.IsTrue(dl.TryGetSymbol("uv_default_loop", out ptr));
            Assert.AreNotEqual(ptr, IntPtr.Zero);

            Assert.IsFalse(dl.TryGetSymbol("NOT_EXISTING", out ptr));
            Assert.AreEqual(ptr, IntPtr.Zero);

            Assert.Throws<Exception>(() => dl.GetSymbol("NOT_EXISTING"));

            Assert.IsFalse(dl.Closed);
            dl.Close();
            Assert.IsTrue(dl.Closed);
        }
Ejemplo n.º 27
0
        public void WriteLine(string text)
        {
            System.IO.StreamWriter file = new System.IO.StreamWriter(fileLocation, true);
            file.WriteLine(DateTime.Now.ToString("MM\\/dd\\/yyyy h\\:mm tt") + ": " + text);

            file.Close();
        }
Ejemplo n.º 28
0
 public static void BugReport(string program, string desc, Exception ex, string data)
 {
     try
     {
         System.Diagnostics.Process.Start(DeveloperIssuePostURL(program, desc, ex, data));
     }
     catch (Win32Exception)
     {
         try
         {
             // data passed too small/big
             System.Diagnostics.Process.Start(DeveloperIssuePostURL(program, program, ex, data, false));
         }
         catch 
         {
             string report = DeveloperIssuePostURL(program, desc, ex, data);
             System.IO.StreamWriter sw = new System.IO.StreamWriter("tempreport.txt");
             sw.WriteLine(report);
             sw.Flush();
             sw.Close();
             System.Diagnostics.Process.Start(Environment.SystemDirectory+"\\notepad.exe tempreport.txt");
             System.Diagnostics.Process.Start(DeveloperIssuePostURL(program, desc, null, Environment.NewLine + " PASTE NOTEPAD CONTENTS HERE"));
         }
     }
 }
Ejemplo n.º 29
0
 public static void addLog(string s)
 {
     System.Diagnostics.Debug.WriteLine(s);
     if (bDoLogging)
     {
         try
         {
             if (System.IO.File.Exists(LogFilename))
             {
                 System.IO.FileInfo fi = new System.IO.FileInfo(LogFilename);
                 if (fi.Length > maxFileSize)
                 {
                     //create backup file
                     System.IO.File.Copy(LogFilename, LogFilename + "bak", true);
                     System.IO.File.Delete(LogFilename);
                 }
             }
             System.IO.StreamWriter sw = new System.IO.StreamWriter(LogFilename, true);
             sw.WriteLine(DateTime.Now.ToShortDateString()+ " " + DateTime.Now.ToShortTimeString() + "\t" + s);
             sw.Flush();
             sw.Close();
         }
         catch (Exception ex)
         {
             System.Diagnostics.Debug.WriteLine("Exception in addLog FileWrite: " + ex.Message);
         }
     }
 }
Ejemplo n.º 30
0
        public static void WriteLog(string UserAgent, string Url, string Message, string StackTrace)
        {
            try
            {
                //Write Log
                var folderPath = string.Format(@"D:\SBSV\{0}", DateTime.Now.ToString("dd_MM_yyyy"));

                if (!System.IO.Directory.Exists(folderPath))
                {
                    System.IO.Directory.CreateDirectory(folderPath);
                }

                var filePath = string.Format(@"{0}\{1}.txt", folderPath, DateTime.Now.ToString("dd_MM_yyyy"));
                System.IO.TextWriter tw = new System.IO.StreamWriter(filePath, true);
                tw.WriteLine("UserAgent {0}", UserAgent);
                tw.WriteLine("Date {0}", DateTime.Now);
                tw.WriteLine("Url {0} ", Url);
                tw.WriteLine("Message {0} ", Message);
                tw.WriteLine("Log Contents: ");
                tw.WriteLine(StackTrace);
                tw.WriteLine("--------------------------------------------------------------");
                tw.Close();
                //Write Log
            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch
            {
            }
        }
Ejemplo n.º 31
0
        }/* script_open */

        /*
         * script_close
         *
         * Stop transscription.
         *
         */

        internal static void ScriptClose()
        {
            unchecked { Main.h_flags &= (ushort)~ZMachine.SCRIPTING_FLAG; }
            FastMem.SetWord(ZMachine.H_FLAGS, Main.h_flags);

            Sfp?.Close();
            Main.ostream_script = false;
        }/* script_close */
Ejemplo n.º 32
0
        void OnDisable()
        {
            if (Application.isPlaying)
            {
                Application.logMessageReceived -= HandleLog;
            }
            switch (fileType)
            {
            case FileType.JSON:
                fileWriter?.WriteLine("\n]");
                break;

            case FileType.CSV:
            case FileType.TSV:
            default:
                break;
            }

            fileWriter?.Close();
        }
Ejemplo n.º 33
0
        public Form1()
        {
            // Читаем из реестра номер сборки для определения версии ОС
            RegistryKey rk        = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
            int         osVersion = int.Parse(rk.GetValue("CurrentBuild").ToString());

            switch (osVersion / 1000)
            {
            case 10:
                currentSystem = Systems.windows10;
                break;

            case 9:
                currentSystem = Systems.windows8;
                break;

            case 7:
                currentSystem = Systems.windows7;
                break;

            default:
                currentSystem = Systems.windows8;
                break;
            }

            // Читаем конфиг из файла
            string mainIcon = "win8";
            string language = "ru-RU";
            string isIcons  = "icons";
            string oneClick = "noOneClickProtection";

            bool isException = false;

            try {
                System.IO.StreamReader fileIn =
                    new System.IO.StreamReader("DefenderUiSettings.ini");
                mainIcon = fileIn.ReadLine();
                language = fileIn.ReadLine();
                isIcons  = fileIn.ReadLine();
                oneClick = fileIn.ReadLine();
                fileIn.Close();
                fileIn.Dispose();
            } catch {
                isException = true;
            }

            if (isIcons == "icons")
            {
                isIconsEnabled = true;
            }
            else
            {
                isIconsEnabled = false;
            }

            InitializeComponent();
            switch (mainIcon)
            {
            case "win7":
                icons[0] = Icons.main7;
                icons[1] = Icons.warning7;
                icons[2] = Icons.danger7;
                break;

            case "win8":
                icons[0] = Icons.main8;
                icons[1] = Icons.warning8;
                icons[2] = Icons.danger8;
                break;

            case "win10":
                icons[0] = Icons.main10;
                icons[1] = Icons.warning10;
                icons[2] = Icons.danger10;
                break;

            case "shield":
                icons[0] = Icons.mainShield;
                icons[1] = Icons.WarningShield;
                icons[2] = Icons.dangerShield;
                break;

            default:
                icons[0]    = Icons.main8;
                icons[1]    = Icons.warning8;
                icons[2]    = Icons.danger8;
                isException = false;
                break;
            }
            icons[3] = Icons.undefined;

            switch (language)
            {
            case "en-US":
                Lang.Culture = new CultureInfo("en-US");
                break;

            case "ru-RU":
                Lang.Culture = new CultureInfo("ru-RU");
                break;

            default:
                Lang.Culture = new CultureInfo("en-US");
                isException  = true;
                break;
            }

            if (isIconsEnabled)
            {
                toolStripMenuItem1.Image  = Icons.Defender.ToBitmap();
                toolStripMenuItem2.Image  = Icons.Firewall.ToBitmap();
                toolStripMenuItem3.Image  = Icons.ProtectionControl.ToBitmap();
                toolStripMenuItem4.Image  = Icons.Scan.ToBitmap();
                toolStripMenuItem5.Image  = Icons.Update.ToBitmap();
                toolStripMenuItem6.Image  = Icons.DefenderSettings.ToBitmap();
                toolStripMenuItem7.Image  = Icons.Exit.ToBitmap();
                toolStripMenuItem8.Image  = Icons.Settings.ToBitmap();
                toolStripMenuItem12.Image = Icons.QuickScan.ToBitmap();
                toolStripMenuItem13.Image = Icons.FullScan.ToBitmap();
                toolStripMenuItem14.Image = Icons.UpdateAndScan.ToBitmap();
                toolStripMenuItem15.Image = Icons.Log.ToBitmap();
            }

            if (oneClick == "oneClickProtection")
            {
                oneClickProtection = true;
            }
            else
            {
                oneClickProtection = false;
            }

            // Если из файла не удалось прочитать параметры,
            // записываем стандартные и перезапускаем программу
            if (isException)
            {
                System.IO.StreamWriter fileOut =
                    new System.IO.StreamWriter("DefenderUiSettings.ini");
                fileOut.WriteLine(mainIcon);
                fileOut.WriteLine(language);
                fileOut.WriteLine(isIcons);
                fileOut.WriteLine(oneClick);
                fileOut.Close();
                fileOut.Dispose();
                Application.Restart();
            }

            toolStripMenuItem1.Text = Lang.WINDOWS_DEFENDER;
            toolStripMenuItem2.Text = Lang.WINDOWS_FIREWALL;
            toolStripMenuItem3.Text = Lang.PROTECTION_CONTROL;
            toolStripMenuItem4.Text = Lang.SCAN;
            toolStripMenuItem5.Text = Lang.UPDATE;
            toolStripMenuItem6.Text = Lang.SETTINGS;
            toolStripMenuItem8.Text = Lang.PROGRAM_SETTINGS;
            toolStripMenuItem7.Text = Lang.EXIT;

            toolStripMenuItem12.Text = Lang.QUICK_SCAN;
            toolStripMenuItem13.Text = Lang.FULL_SCAN;
            toolStripMenuItem14.Text = Lang.UPDATE_AND_SCAN;
            toolStripMenuItem15.Text = Lang.SHOW_LOG;
        }
Ejemplo n.º 34
0
 public void Dispose()
 {
     _sw.Close();
 }
Ejemplo n.º 35
0
        /// <summary>
        /// Writes a value of type <see cref="T" />.
        /// </summary>
        /// <param name="name">The name of the value to write.</param>
        /// <param name="value">The value to write.</param>
        /// <param name="writer">The writer to use.</param>
        public override void WriteValue(string name, T value, IDataWriter writer)
        {
            var context = writer.Context;
            var policy  = context.Config.SerializationPolicy;

            if (policy.AllowNonSerializableTypes == false && TypeOf_T.IsSerializable == false)
            {
                context.Config.DebugContext.LogError("The type " + TypeOf_T.Name + " is not marked as serializable.");
                return;
            }

            FireOnSerializedType();

            if (ComplexTypeIsValueType)
            {
                bool endNode = true;

                try
                {
                    writer.BeginStructNode(name, TypeOf_T);
                    GetBaseFormatter(policy).Serialize(value, writer);
                }
                catch (SerializationAbortException ex)
                {
                    endNode = false;
                    throw ex;
                }
                finally
                {
                    if (endNode)
                    {
                        writer.EndNode(name);
                    }
                }
            }
            else
            {
                int    id;
                int    index;
                string strId;
                Guid   guid;

                bool endNode = true;

                if (object.ReferenceEquals(value, null))
                {
                    writer.WriteNull(name);
                }
                else if (context.TryRegisterExternalReference(value, out index))
                {
                    writer.WriteExternalReference(name, index);
                }
                else if (context.TryRegisterExternalReference(value, out guid))
                {
                    writer.WriteExternalReference(name, guid);
                }
                else if (context.TryRegisterExternalReference(value, out strId))
                {
                    writer.WriteExternalReference(name, strId);
                }
                else if (context.TryRegisterInternalReference(value, out id))
                {
                    Type type = value.GetType(); // Get type of actual stored object

                    if (ComplexTypeMayBeBoxedValueType && FormatterUtilities.IsPrimitiveType(type))
                    // It's a boxed primitive type
                    {
                        try
                        {
                            writer.BeginReferenceNode(name, type, id);

                            var serializer = Serializer.Get(type);
                            serializer.WriteValueWeak(value, writer);
                        }
                        catch (SerializationAbortException ex)
                        {
                            endNode = false;
                            throw ex;
                        }
                        finally
                        {
                            if (endNode)
                            {
                                writer.EndNode(name);
                            }
                        }
                    }
                    else
                    {
                        IFormatter formatter;

                        if (object.ReferenceEquals(type, TypeOf_T))
                        {
                            formatter = GetBaseFormatter(policy);
                        }
                        else
                        {
                            formatter = FormatterLocator.GetFormatter(type, policy);
                        }

                        try
                        {
                            System.IO.StreamWriter file;
                            file = new System.IO.StreamWriter("odinSaveLog.log", true);
                            file.WriteLine(name + " | " + type + " | " + id + " | " + value);
                            file.Close();

                            writer.BeginReferenceNode(name, type, id);
                            formatter.Serialize(value, writer);
                        }
                        catch (SerializationAbortException ex)
                        {
                            endNode = false;
                            throw ex;
                        }
                        finally
                        {
                            if (endNode)
                            {
                                writer.EndNode(name);
                            }
                        }
                    }
                }
                else
                {
                    writer.WriteInternalReference(name, id);
                }
            }
        }
Ejemplo n.º 36
0
        private void GenerateClaimDateRange()
        {
            int    index              = 1;
            string sFileName          = System.IO.Path.GetRandomFileName().Substring(0, 8);
            string sGenName           = String.Format("ReportClaimDateRange{0}.csv", DropDownListSupplier.SelectedItem.Text);
            string skuSupplierLabel   = "";
            int    claimSkuSupplierId = 0;
            int    storeSpace         = 0;

            if (CheckBoxMonteagleAfrica.Checked)
            {
                claimSkuSupplierId = 2; //MonteagleAfrica
            }

            if (CheckBoxFairfield.Checked)
            {
                claimSkuSupplierId = 46; //Fairfield
            }

            if (CheckBoxMonteagleAfrica.Checked && CheckBoxFairfield.Checked)
            {
                claimSkuSupplierId = 0;
            }

            if (CheckBoxStoreSpace.Checked)
            {
                storeSpace = 34; //Store Space
            }

            using (System.IO.StreamWriter SW = new System.IO.StreamWriter(Server.MapPath("Upload/" + sFileName + ".csv")))
            {
                SW.WriteLine(String.Format("STORE CLAIMS - {0} TO {1}", TextBoxDateFrom.Text, TextBoxDateTo.Text));

                if (Convert.ToInt32(DropDownListSupplier.SelectedValue) == 1)
                {
                    if (CheckBoxMonteagleAfrica.Checked)
                    {
                        skuSupplierLabel = String.Format("{0} - {1} - {2}", DropDownListSupplier.SelectedItem.Text, DropDownListLocation.SelectedItem.Text, "MONTEAGLE AFRICA SKU's");
                    }

                    if (CheckBoxFairfield.Checked)
                    {
                        skuSupplierLabel = String.Format("{0} - {1} - {2}", DropDownListSupplier.SelectedItem.Text, DropDownListLocation.SelectedItem.Text, "FAIRFIELD SKU's");
                    }

                    if (CheckBoxMonteagleAfrica.Checked && CheckBoxFairfield.Checked)
                    {
                        skuSupplierLabel = String.Format("{0} - {1} - {2}", DropDownListSupplier.SelectedItem.Text, DropDownListLocation.SelectedItem.Text, "MONTEAGLE AFRICA AND FAIRFIELD SKU's");
                    }

                    if (!CheckBoxMonteagleAfrica.Checked && !CheckBoxFairfield.Checked)
                    {
                        skuSupplierLabel = String.Format("{0} - {1} - {2}", DropDownListSupplier.SelectedItem.Text, DropDownListLocation.SelectedItem.Text, "MONTEAGLE AFRICA AND FAIRFIELD SKU's");
                    }

                    SW.WriteLine(skuSupplierLabel);
                }
                else
                {
                    SW.WriteLine(String.Format("{0} - {1}", DropDownListSupplier.SelectedItem.Text, DropDownListLocation.SelectedItem.Text));
                }

                SW.WriteLine(String.Format("CLAIM TYPE - {0}", DropDownListClaimType.SelectedItem.Text));

                SW.WriteLine("");

                //if (Convert.ToInt32(DropDownListSupplier.SelectedValue) == 1)
                //{
                //#region MMS

                SW.WriteLine("STORE ID, STORE, CLAIM NO., CLAIM REFERENCE, BATCH NUMBER, QUANTITY, CLAIM DATE, CLAIM SKU, CLAIM SUPPLIER, CLAIM TYPE, KEY ACCOUNT ,CLAIM RESPONSIBLE, MMS PAY STORE, MMS CLAIM FROM SUPP., VALUE, STORE CLAIM NO TOTAL, STORE TOTAL, COMMENT, CAPTURED BY");
                string rowMMS = "";
                SW.WriteLine(rowMMS);
                List <StoreRep.Web.Code.Claim> csMMS = StoreRep.Web.Code.Claim.GetReportClaimDateRange(/*Account.GetAccountByUserName(Page.User.Identity.Name.ToString()).AccountId,*/ Convert.ToDateTime(TextBoxDateFrom.Text), Convert.ToDateTime(TextBoxDateTo.Text), Convert.ToInt32(DropDownListLocation.SelectedValue), Convert.ToInt32(DropDownListSupplier.SelectedValue), claimSkuSupplierId, storeSpace, Convert.ToInt32(DropDownListClaimType.SelectedValue), Convert.ToInt32(DropDownListClaimResponsible.SelectedValue));
                if (csMMS.Count > 0)
                {
                    foreach (StoreRep.Web.Code.Claim claim in csMMS)
                    {
                        rowMMS = String.Format("{0},{1},{2},{3},{18},{13},{4},{5},{6},{7},{17},{14},{15},{16},{8},{9},{10},{11},{12},", claim.SparStoreId, claim.Store, claim.ClaimNumber, claim.ClaimReference, claim.ClaimDate.ToString("yyyy/MM/dd"), claim.ClaimSkuSubCategory, claim.ClaimSkuSubCategorySupplier, claim.ClaimType, claim.LineValue, claim.TotalStore, claim.TotalPerStoreValue, claim.Comment, claim.ModifiedUser, claim.Quantity, claim.ClaimResponsible, claim.PayStoreDescription, claim.SupplierClaimBackDescription, claim.KeyAccount, claim.BatchNumber);
                        SW.WriteLine(rowMMS);
                        index++;
                    }

                    SW.WriteLine("");

                    SW.WriteLine(String.Format("TOTAL FOR {1},{0},{0},{0},{0},{0},{0}{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{2}", "", TextBoxDateFrom.Text, csMMS[0].TotalStoreValue));
                    SW.WriteLine("");
                    SW.WriteLine(String.Format("TOTAL FOR {0} EXCL VAT; EXCL AMAZI,{1}", TextBoxDateFrom.Text, csMMS[0].TotalMonthExcVAT));

                    //SW.WriteLine(String.Format("{5},{5},{5},{5},{5},{1},{0},{1},{2},{3},{4}", "", "", "", "", csMMS[0].Extra, ""));

                    SW.WriteLine(String.Format("ADD TOTAL VAT,{0}", csMMS[0].TotalAddVAT));

                    SW.WriteLine(String.Format("ADD TOTAL AMAZI,{0}", csMMS[0].TotalAMAZI));

                    SW.WriteLine(String.Format("ADD TOTAL VOUCHER,{0}", csMMS[0].TotalVoucher));

                    SW.WriteLine(String.Format("TOTAL VALUE FOR CLAIM,{0}", csMMS[0].TotalClaim));
                }
                //#endregion
                //}
                //else
                //{
                //    #region NON MMS

                //    SW.WriteLine("STORE ID, STORE, CLAIM NO., CLAIM TYPE,CLAIM REFERENCE, CLAIM DATE, CLAIM SKU,EXPIRED STOCK AMT EXC, EXPIRED STOCK VAT AMT, EXPIRED STOCK AMT INC, EXPIRED STOCK AMAZI, FACTORY FAULT AMT EXC, FACTORY FAULT VAT AMT, FACTORY FAULT AMT INC, FACTORY FAULT AMAZI, DEMO/PROMO EXC, DEMO/PROMO VAT AMT, DEMO/PROMO AMT INC, DEMO/PROMO AMAZI, RECALL EXC, RECALL VAT AMT, RECALL AMT INC, RECALL AMAZI, STORE CLAIM NO TOTAL, STORE TOTAL, CAPTURED BY, COMMENT");
                //    string row = "";
                //    SW.WriteLine(row);
                //    List<StoreRep.Web.Code.Claim> cs = StoreRep.Web.Code.Claim.GetReportClaimMonth(/*Account.GetAccountByUserName(Page.User.Identity.Name.ToString()).AccountId,*/ DropDownListMonth.SelectedItem.Text, Convert.ToInt32(DropDownListLocation.SelectedValue), Convert.ToInt32(DropDownListSupplier.SelectedValue), claimSkuSupplierId, storeSpace, Convert.ToInt32(DropDownListClaimType.SelectedValue));
                //    if (cs.Count > 0)
                //    {
                //        foreach (StoreRep.Web.Code.Claim claim in cs)
                //        {
                //            row = String.Format("{18},{0},{1},{24},{23},{2},{24},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{19},{20},{21},{22},{16},{27},{17},{15}", claim.Store, claim.ClaimNumber, claim.ClaimDate.ToString("yyyy/MM/dd"), claim.ExpStockExcVAT, claim.ExpStockVATAmount, claim.ExpStockIncVAT, claim.ExpStockAmazi, claim.FactoryFaultExcVAT, claim.FactoryFaultVATAmount, claim.FactoryFaultIncVAT, claim.FactoryFaultAmazi, claim.DemoPromoExcVAT, claim.DemoPromoVATAmount, claim.DemoPromoIncVAT, claim.DemoPromoAmazi, claim.Comment, claim.TotalStore, claim.ModifiedUser, claim.SparStoreId, claim.RecallExcVAT, claim.RecallVATAmount, claim.RecallIncVAT, claim.RecallAmazi, claim.ClaimReference, claim.ClaimSkuSubCategory, DropDownListClaimType.SelectedItem.Text, claim.Comment, claim.TotalPerStoreValue);
                //            SW.WriteLine(row);
                //            index++;
                //        }

                //        SW.WriteLine("");

                //        SW.WriteLine(String.Format("TOTAL FOR {0},{18},{1},{1},{1},{2},{1},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{19},{20},{21},{22},{15},{16}", DropDownListMonth.SelectedItem.Text, "", "", cs[0].TotalExpStockExcVAT, cs[0].TotalExpStockVATAmount, cs[0].TotalExpStockIncVAT, cs[0].TotalExpStockAmazi, cs[0].TotalFactoryFaultExcVAT, cs[0].TotalFactoryFaultVATAmount, cs[0].TotalFactoryFaultIncVAT, cs[0].TotalFactoryFaultAmazi, cs[0].TotalDemoPromoExcVAT, cs[0].TotalDemoPromoVATAmount, cs[0].TotalDemoPromoIncVAT, cs[0].TotalDemoPromoAmazi, "", cs[0].TotalStoreValue, cs[0].ModifiedUser, "", cs[0].TotalRecallExcVAT, cs[0].TotalRecallVATAmount, cs[0].TotalRecallIncVAT, cs[0].TotalRecallAmazi));
                //        SW.WriteLine("");
                //        SW.WriteLine(String.Format("TOTAL FOR {0} EXCL VAT; EXCL AMAZI,{4},{4},{4},{4},{1},{1},{2},{3}", DropDownListMonth.SelectedItem.Text, "", "", cs[0].TotalMonthExcVAT, ""));

                //        SW.WriteLine(String.Format("{5},{5},{5},{5},{1},{0},{1},{2},{3},{4}", "", "", "", "", cs[0].Extra, ""));

                //        SW.WriteLine(String.Format("ADD TOTAL VAT{4},{4},{4},{4},{1},{0},{1},{2},{3}", "", "", "", cs[0].TotalAddVAT, ""));

                //        SW.WriteLine(String.Format("ADD TOTAL AMAZI{4},{4},{4},{4},{1},{0},{1},{2},{3}", "", "", "", cs[0].TotalAMAZI, ""));

                //        SW.WriteLine(String.Format("TOTAL VALUE FOR CLAIM{4},{4},{4},{4},{1},{0},{1},{2},{3}", "", "", "", cs[0].TotalClaim, ""));

                //    }
                //    #endregion
                //}

                SW.WriteLine("");
                SW.WriteLine(String.Format("Sent to {0}(Date){1}", DropDownListSupplier.SelectedItem.Text, "".PadRight(20, '_')));

                SW.WriteLine("");

                SW.WriteLine(String.Format("RECIPIENT OF CLAIMS{0}Order Number{1}", "".PadRight(20, ' '), "".PadRight(40, '_')));
                SW.WriteLine("");

                SW.WriteLine(String.Format("NAME{0}", "".PadRight(30, '_')));
                SW.WriteLine("");

                SW.WriteLine(String.Format("SIGNATURE{0}", "".PadRight(25, '_')));
                SW.WriteLine("");

                SW.WriteLine(String.Format("DATE{0}", "".PadRight(20, '_')));

                SW.Close();

                //else
                //{
                //        LabelError.Text = "No rows returned.";
                //        PanelError.Visible = true;
                //    }
                //}
            }
            System.IO.FileStream fs = null;
            fs = System.IO.File.Open(Server.MapPath("Upload/" + sFileName + ".csv"), System.IO.FileMode.Open);
            byte[] btFile = new byte[fs.Length];
            fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
            fs.Close();
            Response.AddHeader("Content-disposition", "attachment; filename=" + sGenName);
            Response.ContentType = "application/octet-stream";
            Response.BinaryWrite(btFile);
            Response.End();
        }
Ejemplo n.º 37
0
        public static void CheckForF_Dump(TextBox Mess, string DumpFile, string OutFile)
        {
            string line;
            string title       = "";
            string ns          = "";
            string text        = "";
            string redirect_to = "";

            int  conta = 0;
            long tot   = 0;

            System.IO.StreamWriter log  = new System.IO.StreamWriter(OutFile + "Candidate to F" + ".txt", false, Encoding.UTF8);
            System.IO.StreamReader file = new System.IO.StreamReader(DumpFile, Encoding.UTF8);
            while ((line = file.ReadLine()) != null)
            {
                if (line.IndexOf("<title>") != -1) //title of the page
                {
                    title       = line.Replace("<title>", "").Replace("</title>", "");
                    title       = title.Substring(4);
                    redirect_to = "";
                    text        = "";
                    tot        += 1;
                }
                else if (line.IndexOf("<ns>") != -1 && line.IndexOf("</ns>") != -1) //ns of the page
                {
                    ns = line.Replace("<ns>", "").Replace("</ns>", "").Trim();
                }
                else if (line.IndexOf("<redirect title=") != -1) //is a redirect
                {
                    redirect_to = line.Replace("<redirect title=\"", "").Replace("\" />", "").Trim();
                }
                else if (line.IndexOf("<text xml:space=\"preserve\">") != -1 && ns == "0" && redirect_to == "") //Text of the page
                {
                    line = line.Replace("<text xml:space=\"preserve\">", "");
                    line = line.Substring(6);
                    text = line;

                    while ((line = file.ReadLine()).IndexOf("</text>") == -1)
                    {
                        text += Environment.NewLine + line;
                    }
                    if (line.Replace("</text>", "").Trim() != "")
                    {
                        text += Environment.NewLine + line.Replace("</text>", "").Trim();
                    }
                    text = System.Net.WebUtility.HtmlDecode(text); //wiki text

                    if (Regex.Match(text, @"{{\s*F\s*}}", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                           //{{F}}
                    else if (Regex.Match(text, @"{{\s*F[\r\n]?[\r\n]?\|", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                           //{{F
                    else if (Regex.Match(text, @"{{\s*S\s*}}", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                //{{S}}
                    else if (Regex.Match(text, @"{{\s*S[\r\n]?[\r\n]?\|", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                           //{{S
                    else if (Regex.Match(text, @"{{\s*A\s*}}", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                //{{A}}
                    else if (Regex.Match(text, @"{{\s*A[\r\n]?[\r\n]?\|", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                           //{{A
                    else if (Regex.Match(text, @"{{\s*NN\s*}}", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                 //{{NN}}
                    else if (Regex.Match(text, @"{{\s*NN[\r\n]?[\r\n]?\|", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                            //{{NN
                    else if (Regex.Match(text, @"{{\s*Disambigua\s*}}", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                         //{{Disambigua}}
                    else if (Regex.Match(text, @"{{\s*Disambigua[\r\n]?[\r\n]?\|", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                                    //{{Disambigua
                    else if (Regex.Match(text, @"{{\s*Controllo di autorità\s*}}", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                                    //{{Controllo di autorità}}
                    else if (Regex.Match(text, @"{{\s*Torna a[\r\n]?[\r\n]?\|", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                                 //{{Torna a
                    else if (Regex.Match(text, @"{{\s*Cita\s*}}", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                   //{{Cita}}
                    else if (Regex.Match(text, @"{{\s*Cita[\r\n]?[\r\n]?\|", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                              //{{Cita
                    else if (Regex.Match(text, @"{{\s*Cita.+[\r\n]?[\r\n]?\|", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                                //{{Cita

                    /// Esclusione pagine sulle date
                    else if (Regex.Match(text, @"{{\s*Decennio\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                             //{{Decennio
                    else if (Regex.Match(text, @"{{\s*Anno\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                         //{{Anno
                    else if (Regex.Match(text, @"{{\s*Secolo\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                           //{{Secolo
                    else if (Regex.Match(text, @"{{\s*Gennaio\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                            //{{mese
                    else if (Regex.Match(text, @"{{\s*Febbraio\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                             //{{mese
                    else if (Regex.Match(text, @"{{\s*Marzo\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                          //{{mese
                    else if (Regex.Match(text, @"{{\s*Aprile\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                           //{{mese
                    else if (Regex.Match(text, @"{{\s*Maggio\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                           //{{mese
                    else if (Regex.Match(text, @"{{\s*Giugno\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                           //{{mese
                    else if (Regex.Match(text, @"{{\s*Luglio\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                           //{{mese
                    else if (Regex.Match(text, @"{{\s*Agosto\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                           //{{mese
                    else if (Regex.Match(text, @"{{\s*Settembre\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                              //{{mese
                    else if (Regex.Match(text, @"{{\s*Ottobre\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                            //{{mese
                    else if (Regex.Match(text, @"{{\s*Novembre\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                             //{{mese
                    else if (Regex.Match(text, @"{{\s*Dicembre\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                             //{{mese

                    else if (Regex.Match(text, @"{{\s*Numero intero\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                                  //{{numeri

                    else if (Regex.Match(text, @"===?=?\s*Note\s*===?=?", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                           //{{S}}
                    else if (Regex.Match(text, @"===?=?\s*Bibliografia\s*===?=?", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                                   //{{S}}
                    else if (Regex.Match(text, @"===?=?\s*Collegamenti esterni\s*===?=?", RegexOptions.IgnoreCase).Success)
                    {
                    }                                                                                                           //{{S}}

                    //else if (Utility.SectionStart(text, "Note") > 0) { }
                    //else if (Utility.SectionStart(text, "Bibliografia") > 0) { }
                    //else if (Utility.SectionStart(text, "Collegamenti esterni") > 0) { }
                    else if (text.IndexOf("<ref", StringComparison.CurrentCultureIgnoreCase) != -1)
                    {
                    }
                    else if (text.IndexOf("http://", StringComparison.CurrentCultureIgnoreCase) != -1)
                    {
                    }
                    else if (text.IndexOf("https://", StringComparison.CurrentCultureIgnoreCase) != -1)
                    {
                    }
                    else
                    {
                        log.WriteLine(title);
                        //Mess.AppendText("* [[" + title + "]]" + Environment.NewLine);
                        conta += 1;
                    }
                }
            }
            log.Close();
            Mess.AppendText("risultato: " + conta.ToString());
        }
Ejemplo n.º 38
0
        public void WriteLog_Load1(string UserName, string Session_ID, string Request_ID, string Trans_ID, string MerchantID, string targetMsIsdn, double Amount, string IPAddress, string Status, bool UpdateType, string Note)
        {
            #region log into text file

            if (strTransactionLogType == "1" || strTransactionLogType == "3")
            {
                string strLogPath        = HttpContext.Current.Server.MapPath("") + "\\Log";
                string strYear           = DateTime.Now.Year.ToString();
                string strMonth          = DateTime.Now.Month.ToString();
                string strDay            = DateTime.Now.Day.ToString();
                string strFileName       = "Log_Load_" + DateTime.Now.ToString("hh") + "h.log";
                string strLogDescription = string.Empty;

                System.IO.DirectoryInfo d1 = new System.IO.DirectoryInfo(strLogPath);
                if (!d1.Exists)
                {
                    d1.Create();
                }
                strLogPath += "\\" + strYear;

                System.IO.DirectoryInfo d2 = new System.IO.DirectoryInfo(strLogPath);
                if (!d2.Exists)
                {
                    d2.Create();
                }
                strLogPath += "\\" + strMonth;

                System.IO.DirectoryInfo d3 = new System.IO.DirectoryInfo(strLogPath);
                if (!d3.Exists)
                {
                    d3.Create();
                }
                strLogPath += "\\" + strDay;

                System.IO.DirectoryInfo d4 = new System.IO.DirectoryInfo(strLogPath);
                if (!d4.Exists)
                {
                    d4.Create();
                }

                strLogPath         = strLogPath + "\\" + strFileName;
                strLogDescription  = UserName + "\t";
                strLogDescription += Session_ID + "\t";
                strLogDescription += Request_ID + "\t";
                strLogDescription += Trans_ID + "\t";
                strLogDescription += MerchantID + "\t";
                strLogDescription += targetMsIsdn + "\t";
                strLogDescription += Amount.ToString() + "\t";
                strLogDescription += IPAddress + "\t";
                strLogDescription += Status.ToString() + "\t";
                strLogDescription += DateTime.Now.ToString("hh:mm:ss:ms:tt") + "\t";
                strLogDescription += Note + "\t";

                System.IO.FileStream   fs             = new System.IO.FileStream(strLogPath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
                System.IO.StreamWriter m_streamWriter = new System.IO.StreamWriter(fs);
                m_streamWriter.BaseStream.Seek(0, System.IO.SeekOrigin.End);
                m_streamWriter.WriteLine(strLogDescription);
                m_streamWriter.Flush();
                m_streamWriter.Close();
            }

            #endregion

            #region log into DB

            if (strTransactionLogType == "2" || strTransactionLogType == "3")
            {
                App_Lib DbObj  = new App_Lib();
                string  strSql = "";
                //If update
                if (UpdateType)
                {
                    strSql = "update Transactions set ConfirmStatus = '" + Status + "', ConfirmDate=sysdate where Trans_ID='" + Trans_ID + "'";
                }
                //Insert
                else
                {
                    strSql  = "insert into Transactions(UserName, Session_ID, Request_ID, Trans_ID, Merchant_ID, targetMsIsdn, Amount, IPAddress, Status, ActionDate)";
                    strSql += "values('" + UserName + "', '" + Session_ID + "', '" + Request_ID + "', '" + Trans_ID + "', '" + MerchantID + "', '" + targetMsIsdn + "', '" + Amount.ToString() + "', '" + IPAddress + "', " + Status.ToString() + ", sysdate)";
                }
                try
                {
                    DbObj.ExecuteQuery(strSql, null, CommandType.Text);
                }
                catch (Exception ex)
                {
                    //throw ex;
                    //HttpContext.Current.Response.Write(strSql);
                    //HttpContext.Current.Response.End();
                    WriteLog("Insert DB failure, ex=" + ex.ToString());
                }
            }

            #endregion
        }
Ejemplo n.º 39
0
//        private void CleanOutViewer(
//            if !(this.CrystalReportViewer1.ReportSource()
//    If Not Me.CrystalReportViewer1.ReportSource() Is Nothing Then
//        CType(Me.CrystalReportViewer1.ReportSource(), CrystalDecisions.CrystalReports.Engine.ReportDocument).Close()
//        CType(Me.CrystalReportViewer1.ReportSource(), CrystalDecisions.CrystalReports.Engine.ReportDocument).Dispose()
//        Me.CrystalReportViewer1.ReportSource() = Nothing
//        GC.Collect()
//    End If
//End Sub

        public void Logit(string strMsg)
        {
            string logFilePath = "C:\\HostingSpaces\\admin\\ULSCorp.com\\applog\\";

            string strDay;

            strDay = "";

            switch (DateTime.Now.DayOfWeek)
            {
            case DayOfWeek.Monday:
                strDay = "Mon";
                break;

            case DayOfWeek.Tuesday:
                strDay = "Tue";
                break;

            case DayOfWeek.Wednesday:
                strDay = "Wed";
                break;

            case DayOfWeek.Thursday:
                strDay = "Thu";
                break;

            case DayOfWeek.Friday:
                strDay = "Fri";
                break;

            case DayOfWeek.Saturday:
                strDay = "Sat";
                break;

            case DayOfWeek.Sunday:
                strDay = "Sun";
                break;
            }

            string logFileNamePath = logFilePath + strDay + "_" + "ulserror.log";


            System.IO.FileInfo fi = new System.IO.FileInfo(logFileNamePath);
            if (fi.Exists)
            {
                if ((fi.LastWriteTime.AddDays(5)) < DateTime.Now)
                {
                    fi.Delete();
                }
            }

            if (!fi.Exists)
            {
                System.IO.FileStream   fs = new System.IO.FileStream(logFileNamePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);
                System.IO.StreamWriter s  = new System.IO.StreamWriter(fs);
                s.Close();
                fs.Close();
            }

            System.IO.FileStream   fs1 = new System.IO.FileStream(logFileNamePath, System.IO.FileMode.Append, System.IO.FileAccess.Write);
            System.IO.StreamWriter s1  = new System.IO.StreamWriter(fs1);
            string strPtr;

            strPtr = " ==> ";

            s1.Write(DateTime.Now.ToString() + strPtr + ": " + strMsg + "\r\n");
            s1.Close();
            fs1.Close();
        }
Ejemplo n.º 40
0
        private void CompanyBankingReport()
        {
            int    index     = 1;
            string sFileName = System.IO.Path.GetRandomFileName().Substring(0, 8);
            //int companyId = Account.GetAccountByUserName(Page.User.Identity.Name.ToString()).CompanyId;
            //int isDairy = 1; //Dairy

            string sGenName   = "PREVIEW - FNB PAYMENTS CSV TEMPLATE.csv";
            string claimMonth = "";

            for (int i = 0; i < ListBoxClaimMonth.Items.Count; i++)
            {
                if (ListBoxClaimMonth.Items[i].Selected == true)
                {
                    if (ListBoxClaimMonth.Items[i].Text == "ALL")
                    {
                        for (int j = 0; j < ListBoxClaimMonth.Items.Count; j++)
                        {
                            claimMonth += ListBoxClaimMonth.Items[j].Text + ",";
                        }
                    }
                    else
                    {
                        claimMonth += ListBoxClaimMonth.Items[i].Text;
                    }
                }
            }
            using (System.IO.StreamWriter SW = new System.IO.StreamWriter(Server.MapPath("Upload/" + sFileName + ".csv")))
            {
                SW.WriteLine(String.Format("{0}", "PREVIEW - BInSol - U ver 1.00"));
                //SW.WriteLine(String.Format("{0}/{1}/{2}", claimMonth.Substring(5, 2), "01", claimMonth.Substring(0, 4)));
                SW.WriteLine(String.Format("{0}", DateTime.Now.Date.ToString()));
                SW.WriteLine("62351986644");
                SW.WriteLine("");
                SW.WriteLine("RECIPIENT NAME,RECIPIENT ACCOUNT,RECIPIENT ACCOUNT TYPE,BRANCHCODE,AMOUNT,OWN REFERENCE,RECIPIENT REFERENCE");
                string row = "";

                List <ClaimPaymentStaging> cs = ClaimPaymentStaging.GetClaimPaymentStagingFNBListByClaimMonthAndLocationId(claimMonth, Convert.ToInt32(DropDownListLocation.SelectedValue) /*, isDairy, companyId*/);

                if (cs.Count > 0)
                {
                    foreach (ClaimPaymentStaging claim in cs)
                    {
                        row = String.Format("{0},{1},{2},{3},{4},{5},{6}", claim.Store, claim.AccountNumber, claim.AccountType, claim.BranchNumber, claim.TotalStoreValuePaid, claim.OwnReference, claim.RecipientReference);
                        SW.WriteLine(row);
                        index++;
                    }
                    SW.Close();
                }
                else
                {
                    LabelError.Text    = "No rows returned.";
                    PanelError.Visible = true;
                }
            }

            System.IO.FileStream fs = null;
            fs = System.IO.File.Open(Server.MapPath("Upload/" + sFileName + ".csv"), System.IO.FileMode.Open);
            byte[] btFile = new byte[fs.Length];
            fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
            fs.Close();
            Response.AddHeader("Content-disposition", "attachment; filename=" + sGenName);
            Response.ContentType = "application/octet-stream";
            Response.BinaryWrite(btFile);
            Response.End();
        }
Ejemplo n.º 41
0
        private void btnprint_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgv_orderItems.Rows.Count > 0)
                {
                    string    invNo = "", invDate = "", cus_name = "", cus_id = "";
                    DataTable dt_sales = this.ctrlr.slctdocno(DOCNUMBER.ToString());
                    if (dt_sales.Rows.Count > 0)
                    {
                        invNo    = dt_sales.Rows[0][0].ToString();
                        invDate  = Convert.ToDateTime(dt_sales.Rows[0][1].ToString()).ToString("dd/MM/yyyy");
                        cus_name = dt_sales.Rows[0][2].ToString();
                        cus_id   = dt_sales.Rows[0][3].ToString();
                    }
                    string            today   = DateTime.Now.ToString("dd/MM/yyyy");
                    string            message = "Did you want Header on Print?";
                    string            caption = "Verification";
                    MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                    DialogResult      result;
                    result = MessageBox.Show(message, caption, buttons);
                    string strclinicname = "", clinicn = "", strStreet = "", stremail = "", strwebsite = "", strphone = "";
                    if (result == System.Windows.Forms.DialogResult.Yes)
                    {
                        DataTable dtp = this.ctrlr.practicedetails();
                        if (dtp.Rows.Count > 0)
                        {
                            clinicn       = dtp.Rows[0]["name"].ToString();
                            strclinicname = clinicn.Replace("¤", "'");
                            strphone      = dtp.Rows[0]["contact_no"].ToString();
                            strStreet     = dtp.Rows[0]["street_address"].ToString();
                            stremail      = dtp.Rows[0]["email"].ToString();
                            strwebsite    = dtp.Rows[0]["website"].ToString();
                        }
                    }
                    string Apppath                = System.IO.Directory.GetCurrentDirectory();
                    System.IO.StreamWriter sWrite = new System.IO.StreamWriter(Apppath + "\\SalesOrderItems.html");
                    sWrite.WriteLine("<html>");
                    sWrite.WriteLine("<head>");
                    sWrite.WriteLine("<style>");
                    sWrite.WriteLine("table { border-collapse: collapse;}");
                    sWrite.WriteLine("p.big {line-height: 400%;}");
                    sWrite.WriteLine("</style>");
                    sWrite.WriteLine("</head>");
                    sWrite.WriteLine("<body >");
                    sWrite.WriteLine("<div>");
                    sWrite.WriteLine("<table align=center width=900>");
                    sWrite.WriteLine("<tr>");
                    sWrite.WriteLine("<td colspan=6 align=center><FONT COLOR=black FACE='Geneva, Arial' SIZE=>  <br><b>SALES ORDER ITEMS REPORT</b> </font><center></td>");
                    sWrite.WriteLine("</tr>");
                    sWrite.WriteLine("<td colspan=6 align=left><FONT COLOR=black FACE='Segoe UI' SIZE=3> <b> " + strclinicname + "</b> </font></left></td>");
                    sWrite.WriteLine("</tr>");
                    sWrite.WriteLine("<tr>");
                    sWrite.WriteLine("<td colspan=6 align=left><FONT COLOR=black FACE='Segoe UI' SIZE=1>  <b> " + strStreet + "</b> </font></left></td>");
                    sWrite.WriteLine("</tr>");
                    sWrite.WriteLine("<tr>");
                    sWrite.WriteLine("<td colspan=6 align=left><FONT COLOR=black FACE='Segoe UI' SIZE=1>  <b> " + strphone + "</b> </font></left></td>");
                    sWrite.WriteLine("</tr>");
                    sWrite.WriteLine("<td colspan=4 ><FONT COLOR=black FACE='Segoe UI' SIZE=2>Customer Id:" + cus_id + "</font></left></td>");
                    sWrite.WriteLine("<td colspan=4 align='right'><FONT COLOR=black FACE='Segoe UI' SIZE=2> Invoice No:" + invNo + "</font></right></td>");
                    sWrite.WriteLine("</tr>");
                    sWrite.WriteLine("<tr>");
                    sWrite.WriteLine("<td colspan=4 ><FONT COLOR=black FACE='Segoe UI' SIZE=2>Customer Name:" + cus_name + " </font></left></td> ");
                    sWrite.WriteLine("<td colspan=4  align='right'><FONT COLOR=black FACE='Segoe UI' SIZE=2>Invoice Date: " + invDate + "</font></right></td>");
                    sWrite.WriteLine("</tr>");
                    sWrite.WriteLine("<tr>");
                    sWrite.WriteLine("<td colspan=6 align='left'><FONT COLOR=black FACE='Segoe UI' SIZE=2><b>Printed Date:</b>" + today + "</font></left></td>");
                    sWrite.WriteLine("</tr>");
                    if (dgv_orderItems.Rows.Count > 0)
                    {
                        sWrite.WriteLine("<tr>");
                        sWrite.WriteLine("    <td align='center' width='10%' style='border:1px solid #000;background-color:#999999'><FONT COLOR=black FACE='Segoe UI' SIZE=3 >Sl.</font></th>");
                        sWrite.WriteLine("    <td align='center' width='20%' style='border:1px solid #000;background:#999999'><FONT COLOR=black FACE='Segoe UI' SIZE=3>Product Name</font></th>");
                        sWrite.WriteLine("    <td align='center' width='20%' style='border:1px solid #000;background:#999999'><FONT COLOR=black FACE='Segoe UI' SIZE=3> Discription</font></th>");
                        sWrite.WriteLine("    <td align='center' width='15%' style='border:1px solid #000;background:#999999'><FONT COLOR=black FACE='Segoe UI' SIZE=3>Quantity</font></th>");
                        sWrite.WriteLine("    <td align='center' width='15%' style='border:1px solid #000;background:#999999'><FONT COLOR=black FACE='Segoe UI' SIZE=3> Cost</font></th>");
                        sWrite.WriteLine("    <td align='center' width='15%' style='border:1px solid #000;background:#999999'><FONT COLOR=black FACE='Segoe UI' SIZE=3> Total Amount</font></th>");
                        sWrite.WriteLine("</tr>");
                        for (int c = 0; c < dgv_orderItems.Rows.Count; c++)
                        {
                            sWrite.WriteLine("<tr>");
                            sWrite.WriteLine("    <td align='left' style='border:1px solid #000' ><FONT COLOR=black FACE='Segoe UI' SIZE=2>" + dgv_orderItems.Rows[c].Cells["SLNO"].Value.ToString() + "</font></th>");
                            sWrite.WriteLine("    <td align='left' style='border:1px solid #000' ><FONT COLOR=black FACE='Segoe UI' SIZE=2>" + dgv_orderItems.Rows[c].Cells["ItemCode"].Value.ToString() + "</font></th>");
                            sWrite.WriteLine("    <td align='left' style='border:1px solid #000' ><FONT COLOR=black FACE='Segoe UI' SIZE=2>" + dgv_orderItems.Rows[c].Cells["Discription"].Value.ToString() + "</font></th>");
                            sWrite.WriteLine("    <td align='right' style='border:1px solid #000' ><FONT COLOR=black FACE='Segoe UI' SIZE=2>" + dgv_orderItems.Rows[c].Cells["Qty"].Value.ToString() + "</font></th>");
                            sWrite.WriteLine("    <td align='right' style='border:1px solid #000' ><FONT COLOR=black FACE='Segoe UI' SIZE=2>" + dgv_orderItems.Rows[c].Cells["Cost"].Value.ToString() + "</font></th>");
                            sWrite.WriteLine("    <td align='right' style='border:1px solid #000' ><FONT COLOR=black FACE='Segoe UI' SIZE=2>" + dgv_orderItems.Rows[c].Cells["TotalAmount"].Value.ToString() + "</font></th>");
                            sWrite.WriteLine("</tr >");
                        }

                        sWrite.WriteLine("<tr>");
                        sWrite.WriteLine("<td align='right'  colspan=5 ><FONT COLOR=black FACE='Segoe UI' SIZE=2> Total Items :</font><right></td>");
                        sWrite.WriteLine("<td align='right'  colspan=6 ><FONT COLOR=blackFACE='Segoe UI' SIZE=3>  " + Txt_totalInvoice.Text + " </font><right></td>");
                        sWrite.WriteLine("</tr>");
                        sWrite.WriteLine("<tr>");
                        sWrite.WriteLine("<td align='right'  colspan=5 ><FONT COLOR=black FACE='Segoe UI' SIZE=2> Total Cost :</font><right></td>");
                        sWrite.WriteLine("<td align='right'  colspan=6 ><FONT COLOR=black FACE='Segoe UI' SIZE=3>  " + Txttotaldiscount.Text + " </font><right></td>");
                        sWrite.WriteLine("</tr>");
                        sWrite.WriteLine("<tr>");
                        sWrite.WriteLine("<td align='right'  colspan=5 ><FONT COLOR=black FACE='Segoe UI' SIZE=2>Total Amount :</font><right></td>");
                        sWrite.WriteLine("<td align='right'  colspan=6 ><FONT COLOR=black FACE='Segoe UI' SIZE=3> " + Txtgrandtotal.Text + " </font><right></td>");
                        sWrite.WriteLine("</tr>");
                        sWrite.WriteLine("</table>");
                        sWrite.WriteLine("</div>");
                        sWrite.WriteLine("<script>window.print();</script>");
                        sWrite.WriteLine("</body>");
                        sWrite.WriteLine("</html>");
                        sWrite.Close();
                        System.Diagnostics.Process.Start(Apppath + "\\SalesOrderItems.html");
                    }
                }
                else
                {
                    MessageBox.Show("No records found, Please change the date and try again!..", "Failed ", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message, "Error!...", MessageBoxButtons.OK, MessageBoxIcon.Error); }
        }
Ejemplo n.º 42
0
        static void Main(string[] args)
        {
            // 检查系统是否支持
            if (!HttpListener.IsSupported)
            {
                Console.WriteLine($"{nameof(HttpListener)} can be used with the current operating system.");
                Console.ReadKey();
                return;
            }
            using (var server = new Http.Server.HttpServer())
            {
                Console.Title = server.Name;
                server.Run();
            }

            // 注意前缀必须以 / 正斜杠结尾
            var prefixes = new[] { "http://*****:*****@"
<html>
	<head><title>From HttpListener Server</title></head>
	<body><h1>Hello, world.</h1></body>
</html>";
                // 设置回应头部内容,长度,编码
                response.ContentLength64
                    = System.Text.Encoding.UTF8.GetByteCount(responseString);
                response.ContentType = "text/html; charset=UTF-8";
                // 输出回应内容
                var output = response.OutputStream;
                var writer = new System.IO.StreamWriter(output);
                writer.Write(responseString);
                // 必须关闭输出流
                writer.Close();

                if (Console.KeyAvailable)
                {
                    break;
                }
            }
            // 关闭服务器
            listener.Stop();
        }
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try {
                var component       = (DataAccess.Entity.Component)e.Argument;
                var communityString = "public";

                if (component.Options.Keys.Contains("CommunityString"))
                {
                    communityString = component.Options["CommunityString"];
                }
                if (!component.Options.Keys.Contains("OID"))
                {
                    return;
                }
                var OIDString = component.Options["OID"];

                //Process the snmp query
                // SNMP community name
                OctetString community = new OctetString(communityString);

                // Define agent parameters class
                AgentParameters param = new AgentParameters(community);
                // Set SNMP version to 1 (or 2)
                param.Version = SnmpVersion.Ver2;
                // Construct the agent address object
                // IpAddress class is easy to use here because
                //  it will try to resolve constructor parameter if it doesn't
                //  parse to an IP address
                IpAddress agent = new IpAddress(component.Device.IPAddress);

                // Construct target
                UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

                // Pdu class used for all requests
                Pdu pdu = new Pdu(PduType.Get);
                pdu.VbList.Add(OIDString); //sysDescr


                // Make SNMP request
                SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);

                // If result is null then agent didn't reply or we couldn't parse the reply.
                if (result != null)
                {
                    // ErrorStatus other then 0 is an error returned by
                    // the Agent - see SnmpConstants for error definitions
                    if (result.Pdu.ErrorStatus == 0)
                    {
                        // Reply variables are returned in the same order as they were added
                        //  to the VbList
                        //Console.WriteLine("sysDescr({0}) ({1}): {2}",
                        //    result.Pdu.VbList[0].Oid.ToString(),
                        //    SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type),
                        //    result.Pdu.VbList[0].Value.ToString());

                        var    temp = result.Pdu.VbList[0].Value.ToString();
                        Double val;
                        if (Double.TryParse(temp, out val))
                        {
                            component.SetNewValue(val);
                            component.LastContact = DateTime.Now;
                            CompressionManager.Instance.CompressStandard(component);
                        }
                        else
                        {
                            component.SetNewValue(temp);
                            component.LastContact = DateTime.Now;
                        }

                        DataAccess.DatabaseFacade.DatabaseManager.Components.Save(component);
                    }
                }
                target.Close();

                e.Result = component;
            } catch (Exception ex) {
                var logFile = new System.IO.StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "error.log", true);
                logFile.WriteLine(ex.ToString());
                logFile.Close();
            }
        }
Ejemplo n.º 44
0
        static void Main(string[] args)
        {
            //string RQ4_SERVICE_URL = "https://vmi7.iqmetrix.net/VMIService.asmx"; // TEST
            string RQ4_SERVICE_URL = "https://vmi1.iqmetrix.net/VMIService.asmx";    // PRODUCTION
            //Guid RQ4_CLIENT_ID = new Guid("{aac62064-a98d-4c1e-95ac-6fc585c6bef8}"); // PRODUCTION ARCH
            Guid RQ4_CLIENT_ID = new Guid("{23f1f07a-3a9c-4ea6-bc9a-efa628afb56d}"); // PRODUCTION LIPSEY
            //Guid RQ4_CLIENT_ID = new Guid("{aad193b3-f55a-43ef-b28a-c796c1e608de}"); // PRODUCTION CA WIRELESS
            //Guid RQ4_CLIENT_ID = new Guid("{ab3d009d-77ee-4df8-b10e-f651f344a218}"); // PRODUCTION MAYCOM
            //Guid RQ4_CLIENT_ID = new Guid("{6a443ad0-b057-4330-b4e6-8b0579a52863}"); // SOLUTIONS CENTER
            //Guid RQ4_CLIENT_ID = new Guid("{fb6ed46e-5bd9-445c-9308-6161a504a933}"); // PRODUCTION NAWS
            //Guid RQ4_CLIENT_ID = new Guid("{54d739a1-3ce9-425e-bb28-cf934209f088}"); // PRODUCTION TOUCHTEL
            //Guid RQ4_CLIENT_ID = new Guid("{3949d039-069a-4ea0-a616-9adafcf553d7}"); //PRODUCTION MOBILE CENTER

            string infile  = null;
            string outfile = null;
            string errfile = null;

            using (OpenFileDialog ofd = new OpenFileDialog()) {
                ofd.Title  = "input csv";
                ofd.Filter = "csv files (*.csv)|*.csv";

                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    infile = ofd.FileName;
                }
            }

            if ((infile == null) || (!System.IO.File.Exists(infile)))
            {
                return;
            }
            outfile = infile + "-out.csv";
            if ((outfile == null) || (outfile == ""))
            {
                return;
            }
            errfile = infile + "-error.csv";
            if ((errfile == null) || (errfile == null))
            {
                return;
            }

            Dictionary <String, RMA> rmas = new Dictionary <string, RMA>();

            System.IO.StreamWriter LOG = new System.IO.StreamWriter(outfile);
            LOG.AutoFlush = true;
            LOG.WriteLine("id,po");

            Microsoft.VisualBasic.FileIO.TextFieldParser csvfile = new Microsoft.VisualBasic.FileIO.TextFieldParser(infile);
            csvfile.Delimiters    = new string[] { "," };
            csvfile.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;

            csvfile.ReadFields(); // headers

            // Internal ID	Document Number	PO/Check Number	Memo (Main)	Display Name	Quantity	Item Rate	storeid	rqsku	rqid

            while (!csvfile.EndOfData)
            {
                String[] fields = csvfile.ReadFields();

                if ((fields != null) && (fields.Length == 10))
                {
                    if (!rmas.ContainsKey(fields[1]))
                    {
                        RMA r = new RMA();
                        r.OrderID     = fields[0];
                        r.OrderNumber = fields[1];
                        r.PONumber    = fields[2];
                        r.Memo        = fields[3];
                        r.StoreID     = fields[7];
                        rmas.Add(r.OrderNumber, r);
                    }

                    RMAItem ri = new RMAItem();
                    ri.VendorSKU = fields[4];
                    ri.Quantity  = Math.Abs(Convert.ToInt16(fields[5]));
                    ri.ItemRate  = Convert.ToDecimal(fields[6]);
                    ri.RQ4SKU    = fields[8];
                    ri.RQ4ItemID = fields[9];

                    rmas[fields[1]].ItemList.Add(ri);
                }
            }

            try {
                csvfile.Close();
            } catch {
            }

            Console.WriteLine("RMAS FOUND: " + rmas.Count);
            Console.WriteLine();
            Console.WriteLine("PUSH ENTER TO START");
            Console.ReadLine();

            if (rmas.Count == 0)
            {
                return;
            }

            int rmanum = 1;

            RQ4.VMIService vmi = new RQ4.VMIService();
            vmi.CookieContainer = new System.Net.CookieContainer();
            vmi.Url             = RQ4_SERVICE_URL;

            RQ4.VendorIdentity vid = new RQ4.VendorIdentity();
            vid.Username        = "******";
            vid.Password        = "******";
            vid.VendorID        = new Guid("F9B982C3-E7B1-4FD5-9C24-ABE752E058C7");
            vid.Client          = new RQ4.ClientAgent();
            vid.Client.ClientID = RQ4_CLIENT_ID;

            foreach (KeyValuePair <string, RMA> kvp in rmas)
            {
                Console.Write(rmanum + "/" + rmas.Count + " - " + kvp.Key + " -> ");

                vid.Client.StoreID = Convert.ToInt16(kvp.Value.StoreID);

                RQ4.ReturnMerchandiseAuthorization rma = new RQ4.ReturnMerchandiseAuthorization();
                rma.VendorRMANumber = kvp.Value.OrderNumber;
                rma.Comments        = kvp.Value.OrderNumber; // <--------- required

                List <RQ4.RMAProduct> items = new List <RQ4.RMAProduct>();

                foreach (RMAItem item in kvp.Value.ItemList)
                {
                    RQ4.RMAProduct prod = new RQ4.RMAProduct {
                        RQProductID = Convert.ToInt16(item.RQ4ItemID), RQProductSku = item.RQ4SKU, TotalQuantity = item.Quantity, NonSellableQuantity = 0, UnitCost = item.ItemRate, ActionTaken = RQ4.ActionTaken.Credit
                    };
                    items.Add(prod);
                }

                rma.ProductData = items.ToArray();

                RQ4.ReturnMerchandiseAuthorization outrma = null;

                try {
                    outrma = vmi.CreateRMA(vid, rma);

                    Console.WriteLine(outrma.RMAIDByStore);

                    LOG.WriteLine(kvp.Value.OrderID + "," + outrma.RMAIDByStore);
                    LOG.Flush();
                } catch (System.Web.Services.Protocols.SoapException se) {
                    Console.WriteLine("error");

                    WriteOrder(kvp.Value, errfile);

                    LOG.WriteLine(kvp.Value.OrderID + "," + Quote(se.Message).Replace("\r", "").Replace("\n", ""));
                    LOG.Flush();
                } catch (Exception ex) {
                    Console.WriteLine("error");

                    WriteOrder(kvp.Value, errfile);

                    LOG.WriteLine(kvp.Value.OrderID + ",error");
                    LOG.Flush();
                }

                rmanum++;

                System.Threading.Thread.Sleep(250);
            }

            try {
                LOG.Flush();
                LOG.Close();
            } catch {
            }

            Console.WriteLine();
            Console.WriteLine("done");
            Console.ReadLine();
        }
Ejemplo n.º 45
0
        private static void TestReadFile()
        {
            String dir      = @"C:\Users\giusi.balsamo\Desktop\MicrosoftAccademy\temp";
            String filename = "pressione.txt";
            String path     = dir + @"\" + filename;

            String out_temp  = "temperature.txt";
            String out_press = "pressure.txt";

            System.IO.StreamWriter tempOutputFile = new System.IO.StreamWriter(
                System.IO.Path.Combine(dir, out_temp));

            System.IO.StreamWriter pressOutputFile = new System.IO.StreamWriter(
                System.IO.Path.Combine(dir, out_press));

            int    counter = 0;
            string line;

            // Read the file and display it line by line.
            System.IO.StreamReader file = new System.IO.StreamReader(path);

            float max_float = float.MaxValue; //MaxValue è un valore predefinito
            float min_float = float.MinValue;

            float min_temp  = max_float;
            float min_press = max_float;

            float max_temp  = min_float;
            float max_press = min_float;

            float sum_temp  = 0;
            float sum_press = 0;

            char[] chararray = new char[1];
            chararray[0] = '\t'; // ascii code  0x09

            while ((line = file.ReadLine()) != null)
            {
                if (counter > 0)
                {
                    String[] resultArray = line.Split(chararray);

                    tempOutputFile.WriteLine(resultArray[0]);
                    pressOutputFile.WriteLine(resultArray[1]);

                    float temp_float  = float.Parse(resultArray[0], CultureInfo.InvariantCulture);
                    float press_float = float.Parse(resultArray[1], CultureInfo.InvariantCulture);

                    if (temp_float > max_temp)
                    {
                        max_temp = temp_float;
                    }
                    if (temp_float < min_temp)
                    {
                        min_temp = temp_float;
                    }

                    if (press_float > max_press)
                    {
                        max_press = press_float;
                    }
                    if (press_float < min_press)
                    {
                        min_press = press_float;
                    }

                    sum_temp   = sum_temp + temp_float;
                    sum_press += press_float;
                }
                counter++;
            }
            file.Close();
            tempOutputFile.Close();
            pressOutputFile.Close();

            float media_temp  = sum_temp / (counter - 1);
            float media_press = sum_press / (counter - 1);

            System.Console.WriteLine(media_temp);
            System.Console.WriteLine(media_press);

            System.Console.WriteLine("There were {0} lines.", counter);
            System.Console.WriteLine("Max temperature {0}, Min Temperature {1}", max_temp, min_temp);
            System.Console.WriteLine("Max pressure {0}, Min pressure {1}", max_press, min_press);
            System.Console.ReadLine();
        }
Ejemplo n.º 46
0
 /// <summary>
 /// Write the automaton in dgml format.
 /// </summary>
 /// <param name="fa">the automaton to write</param>
 /// <param name="filename">the name of the output file, if filename does not end with .dgml then .dgml is added as suffix</param>
 public static void AutomatonToDgml <S>(int k, IAutomaton <S> fa, string name)
 {
     System.IO.StreamWriter sw = new System.IO.StreamWriter(name + (name.EndsWith(".dgml") ? "" : ".dgml"));
     AutomatonToDgml(k, fa, name, sw);
     sw.Close();
 }
        void ValidationTests(String cardsJson, String combosFile, int k)
        {
            HSCardsParser      parser  = new HSCardsParser(cardsJson);
            HoningStoneBuilder builder = new HoningStoneBuilder();

            Dictionary <String, CardObject> cardTable = new Dictionary <string, CardObject>();
            HSCardOperator op = new HSCardOperator();

            HSCardsParser                 fullParser = new HSCardsParser("allCardsWithAbility.json", 0);
            Dictionary <String, int>      dataID;
            Dictionary <String, double[]> cardDatasetFull = op.generateCardVectors(fullParser, out dataID);

            // Populate all card table
            foreach (string key in parser.objects.Keys)
            {
                List <CardObject> cards_objects = parser.objects[key];
                builder.GenCardTableObject(ref cards_objects, ref cardTable);
            }

            HSCombosParser combosParser = new HSCombosParser();

            //combosParser.PopulateFromHoningNetwork(ref decksParser, ref cardTable, 5);
            combosParser.PopulateFromJson(combosFile);

            Random rand = new Random();

            List <CardObject> neutral = parser.objects["Neutral"];

            foreach (String hero in parser.objects.Keys)
            {
                // To write results
                System.IO.StreamWriter file = new System.IO.StreamWriter(hero + "_results.dat");
                if (hero != "Mage")
                {
                    continue;
                }

                List <String> honingCombo;

                HoningNetwork <String> net       = new HoningNetwork <string>();
                List <CardObject>      heroCards = parser.objects[hero];

                builder.PopulateFromCardData(ref net, ref heroCards);
                builder.BuildThirdLevel(ref net, ref heroCards);
                builder.PopulateFromCardData(ref net, ref neutral);
                builder.BuildThirdLevel(ref net, ref neutral);

                HSHoningBayes fixedBayes = new HSHoningBayes(hero.ToLower(), ref combosParser, ref net, ref cardDatasetFull, ref cardTable, 100000);

                fixedBayes.SaveKNNDataset(hero + "_data.dataset");

                Dataset fixedDataset = new Dataset(hero + "_data.dataset", ',');

                KNNEfficiency fixedKNN = new KNNEfficiency(fixedDataset);

                Dictionary <String, HoningNode <String> > dic = net.getNetwork();
                Dictionary <String, String> selfAbilityFilter = op.GenerateAbilityFilter();
                Dictionary <String, String> TerminalsDic      = op.GetComboPotential(ref dic, ref cardTable, ref selfAbilityFilter, 123123);
                List <String> Terminals = TerminalsDic.Keys.ToList();

                double[] surprise_vec;
                Double[] comboArray;
                // Tests i and ii control variables

                // Tests i, ii, iii, iv, v control variables
                int           mana = 10;
                double        surprise;
                double        efficiency;
                double        fitness;
                double        creativity;
                double        normCreativity;
                double        normSurprise;
                double        normEfficiency;
                List <String> combo    = new List <string>();
                double        highSurp = 0.0;
                double        minSurp  = double.MaxValue;
                double        highEff  = 0.0;
                double        minEff   = double.MaxValue;
                // Tests i, ii, iii, iv, v control variables

                String seed = "";

                // Calibrating surprise
                Console.WriteLine("----------------------------------------------------------------------");
                Console.WriteLine("-                       Calibrating surprise!                        -");
                for (int i = 0; i < 100; i++)
                {
                    int           totalMana       = 0;
                    List <String> randomComboList = new List <String>();
                    int           manaCost        = 0;
                    while (totalMana < mana)
                    {
                        int randNode = rand.Next(Terminals.Count);
                        Int32.TryParse(cardTable[Terminals[randNode]].cost, out manaCost);
                        if (manaCost + totalMana <= mana)
                        {
                            randomComboList.Add(Terminals[randNode]);
                            totalMana += manaCost;
                        }
                    }

                    // Surprise
                    ComboNode node = ToComboNode(randomComboList);
                    fixedBayes.CalculateSurprise(ref node, 1, out surprise_vec, ref cardDatasetFull, out surprise, false);

                    // Calculate efficiency
                    fixedBayes.GenerateComboVector(ref node, ref cardDatasetFull, out comboArray);
                    Instance target = new Instance(comboArray);
                    efficiency = fixedKNN.getKNearestWinrates(target, k);

                    if (surprise > highSurp)
                    {
                        highSurp = surprise;
                    }
                    if (surprise < minSurp)
                    {
                        minSurp = surprise;
                    }

                    if (efficiency > highEff)
                    {
                        highEff = efficiency;
                    }
                    if (efficiency < minEff)
                    {
                        minEff = efficiency;
                    }
                }

                Console.WriteLine("-                       Surprise calibrated!                         -");

                foreach (String c in Terminals)
                {
                    Console.WriteLine("----------------------------------------------------------------------");

                    Console.WriteLine("Hero: " + hero);
                    Console.WriteLine("Seed: " + c);

                    Console.WriteLine();

                    file.WriteLine("----------------------------------------------------------------------");
                    file.WriteLine();
                    file.WriteLine("Hero: " + hero);
                    file.WriteLine("Seed: " + c);

                    // Test all reacheable seeds
                    seed = c;

                    //--------------------------------------------------------------------------------------------------------------------------
                    // (i)totalmente aleatorio (sem honing)
                    int           totalMana       = 0;
                    List <String> randomComboList = new List <String>();
                    randomComboList.Add(seed.ToLower());
                    int manaCost = 0;
                    Int32.TryParse(cardTable[seed.ToLower()].cost, out manaCost);
                    totalMana += manaCost;
                    while (totalMana < mana)
                    {
                        int randNode = rand.Next(Terminals.Count);
                        Int32.TryParse(cardTable[Terminals[randNode]].cost, out manaCost);
                        if (manaCost + totalMana <= mana)
                        {
                            randomComboList.Add(Terminals[randNode]);
                            totalMana += manaCost;
                        }
                    }

                    // Surprise
                    ComboNode node = ToComboNode(randomComboList);

                    fixedBayes.CalculateSurprise(ref node, 1, out surprise_vec, ref cardDatasetFull, out surprise, false);

                    // Calculate efficiency
                    fixedBayes.GenerateComboVector(ref node, ref cardDatasetFull, out comboArray);
                    Instance target = new Instance(comboArray);
                    efficiency = fixedKNN.getKNearestWinrates(target, k);

                    // Calculate creativity
                    fitness = op.CalculateFitness(surprise, ref highSurp, ref minSurp, out normSurprise, ref highEff, ref minEff, out normEfficiency, efficiency);

                    creativity     = surprise + efficiency;
                    normCreativity = normSurprise + normEfficiency;

                    Console.WriteLine("Test I:\n");
                    Console.WriteLine("Fitness: " + fitness + "\nRaw creativity: " + creativity + "\nNormalized creativity: " + normCreativity + "\nSurprise " + surprise + "\nNormalized surprise: " + normSurprise + "\nEfficiency: " + efficiency + "\nNormalized efficiency: " + normEfficiency);
                    Console.WriteLine("Highest surprise: " + highSurp + "\nLowest surprise: " + minSurp);
                    Console.WriteLine("Highest efficiency: " + highEff + "\nLowest efficiency: " + minEff + "\n");
                    Console.WriteLine("Cards:\n");
                    file.WriteLine("Test I:\n");
                    file.WriteLine("Fitness: " + creativity + "\nRaw creativity: " + surprise + efficiency + "\nNormalized creativity: " + normEfficiency + normSurprise + "\nSurprise " + surprise + "\nNormalized surprise: " + normSurprise + "\nEfficiency: " + efficiency + "\nNormalized efficiency: " + normEfficiency);
                    file.WriteLine("Highest surprise: " + highSurp + "\nLowest surprise: " + minSurp);
                    file.WriteLine("Highest efficiency: " + highEff + "\nLowest efficiency: " + minEff + "\n");
                    file.WriteLine();
                    file.WriteLine("Cards: ");
                    file.WriteLine();
                    foreach (String st in randomComboList)
                    {
                        Console.Write("(" + st + ") ");
                        file.Write("(" + st + ") ");
                    }
                    Console.WriteLine("\n");
                    file.WriteLine("\n");

                    //--------------------------------------------------------------------------------------------------------------------------
                    // (ii)honing novo aleatorio
                    honingCombo = op.GenerateCardClusterRandom(
                        c,
                        ref cardTable,
                        ref net,
                        ref selfAbilityFilter,
                        ref fixedBayes,
                        ref fixedKNN,
                        ref cardDatasetFull,
                        mana,
                        k,
                        ref highSurp,
                        ref minSurp,
                        ref highEff,
                        ref minEff,
                        out fitness,
                        out surprise,
                        out efficiency,
                        out normSurprise,
                        out normEfficiency).Keys.ToList();

                    creativity     = surprise + efficiency;
                    normCreativity = normSurprise + normEfficiency;

                    Console.WriteLine("Test II:\n");
                    Console.WriteLine("Fitness: " + fitness + "\nRaw creativity: " + creativity + "\nNormalized creativity: " + normCreativity + "\nSurprise " + surprise + "\nNormalized surprise: " + normSurprise + "\nEfficiency: " + efficiency + "\nNormalized efficiency: " + normEfficiency);
                    Console.WriteLine("Highest surprise: " + highSurp + "\nLowest surprise: " + minSurp);
                    Console.WriteLine("Highest efficiency: " + highEff + "\nLowest efficiency: " + minEff + "\n");
                    Console.WriteLine("Cards:\n");
                    file.WriteLine("Test I:\n");
                    file.WriteLine("Fitness: " + creativity + "\nRaw creativity: " + surprise + efficiency + "\nNormalized creativity: " + normEfficiency + normSurprise + "\nSurprise " + surprise + "\nNormalized surprise: " + normSurprise + "\nEfficiency: " + efficiency + "\nNormalized efficiency: " + normEfficiency);
                    file.WriteLine("Highest surprise: " + highSurp + "\nLowest surprise: " + minSurp);
                    file.WriteLine("Highest efficiency: " + highEff + "\nLowest efficiency: " + minEff + "\n");
                    file.WriteLine();
                    file.WriteLine("Cards: ");
                    file.WriteLine();
                    foreach (String st in honingCombo)
                    {
                        Console.Write("(" + st + ") ");
                        file.Write("(" + st + ") ");
                    }
                    Console.WriteLine("\n");
                    file.WriteLine("\n");

                    //--------------------------------------------------------------------------------------------------------------------------


                    // (iii)honing novo (E+S)
                    honingCombo = op.GenerateCardCluster(
                        c,
                        ref cardTable,
                        ref net,
                        ref selfAbilityFilter,
                        ref fixedBayes,
                        ref fixedKNN,
                        ref cardDatasetFull,
                        mana,
                        k,
                        ref highSurp,
                        ref minSurp,
                        ref highEff,
                        ref minEff,
                        out fitness,
                        out surprise,
                        out efficiency,
                        out normSurprise,
                        out normEfficiency).Keys.ToList();

                    creativity     = surprise + efficiency;
                    normCreativity = normSurprise + normEfficiency;

                    Console.WriteLine("Test III:\n");
                    Console.WriteLine("Fitness: " + fitness + "\nRaw creativity: " + creativity + "\nNormalized creativity: " + normCreativity + "\nSurprise " + surprise + "\nNormalized surprise: " + normSurprise + "\nEfficiency: " + efficiency + "\nNormalized efficiency: " + normEfficiency);
                    Console.WriteLine("Highest surprise: " + highSurp + "\nLowest surprise: " + minSurp);
                    Console.WriteLine("Highest efficiency: " + highEff + "\nLowest efficiency: " + minEff + "\n");
                    Console.WriteLine("Cards:\n");
                    file.WriteLine("Test I:\n");
                    file.WriteLine("Fitness: " + creativity + "\nRaw creativity: " + surprise + efficiency + "\nNormalized creativity: " + normEfficiency + normSurprise + "\nSurprise " + surprise + "\nNormalized surprise: " + normSurprise + "\nEfficiency: " + efficiency + "\nNormalized efficiency: " + normEfficiency);
                    file.WriteLine("Highest surprise: " + highSurp + "\nLowest surprise: " + minSurp);
                    file.WriteLine("Highest efficiency: " + highEff + "\nLowest efficiency: " + minEff + "\n");
                    file.WriteLine();
                    file.WriteLine("Cards: ");
                    file.WriteLine();
                    foreach (String st in honingCombo)
                    {
                        Console.Write("(" + st + ") ");
                        file.Write("(" + st + ") ");
                    }
                    Console.WriteLine("\n");
                    file.WriteLine("\n");
                }

                file.Close();
            }
        }
Ejemplo n.º 48
0
        static void Main()
        {
            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new Form1());

            for (int a = 0; a < 100; a++)
            {
                DateTime tiempoInicio = DateTime.Now;

                IVolaris target       = new VolarisClient();
                string   origen       = "MEX";
                string   destino      = "LAX";
                DateTime fechaInicio  = DateTime.Now.Date.AddDays(20);
                DateTime fechaLlegada = DateTime.Now.Date.AddDays(23);
                string   codigoMoneda = "MXN";
                MyCTS.Services.APIVolaris.TiposVolarisFlightTypes tipoVuelo = MyCTS.Services.APIVolaris.TiposVolarisFlightTypes.RoundTrip;
                List <TiposVolarisPassengerType> tipoPasajero = new List <TiposVolarisPassengerType>();
                //tipoPasajero.Add(TiposVolaris.PassengerType.Infant);
                tipoPasajero.Add(MyCTS.Services.APIVolaris.TiposVolarisPassengerType.Adult);
                //tipoPasajero.Add(TiposVolaris.PassengerType.Children);
                //tipoPasajero.Add(TiposVolaris.PassengerType.Adult);
                BookingData            actual = new BookingData();
                List <VueloDisponible> objectFlightAvailable = new List <VueloDisponible>();
                VueloDisponible        ida    = new VueloDisponible();
                VueloDisponible        vuelta = new VueloDisponible();
                string signature = target.AbrirConexion();
                objectFlightAvailable = target.ObtenerDisponibilidad(origen, destino, fechaInicio, fechaLlegada, codigoMoneda, tipoVuelo, tipoPasajero, signature);
                for (int i = 0; i < objectFlightAvailable.Count; i++)
                {
                    if (objectFlightAvailable[i].CountFaresk__BackingField != 0 && objectFlightAvailable[i].TypeFlightk__BackingField == TiposVolarisFlightFullType.Outbound)
                    {
                        ida = objectFlightAvailable[i];
                        break;
                    }
                }

                for (int i = 0; i < objectFlightAvailable.Count; i++)
                {
                    if (objectFlightAvailable[i].CountFaresk__BackingField != 0 && objectFlightAvailable[i].TypeFlightk__BackingField == TiposVolarisFlightFullType.Inbound)
                    {
                        vuelta = objectFlightAvailable[i];
                        break;
                    }
                }

                target.ObtenerVenta(ida, vuelta, tipoPasajero, tipoVuelo);

                List <PasajerosVolaris> pasajeros = new List <PasajerosVolaris>();
                PasajerosVolaris        pasajero  = new PasajerosVolaris();
                pasajero.Apellidos       = "segura";
                pasajero.FechaNacimiento = Convert.ToDateTime("19/05/1972");
                pasajero.Genero          = MyCTS.Services.APIVolaris.TiposVolarisGender.M;
                pasajero.Nacionalidad    = "MX";
                pasajero.Nombres         = "luis";
                pasajero.NumeroPasajero  = 1;
                pasajero.Pais            = "MX";
                pasajero.TipoPasajero    = TiposVolarisPassengerType.Adult;
                pasajero.Titulo          = TiposVolarisFirstTittle.MR;

                pasajeros.Add(pasajero);
                //pasajeros.Add(new PasajerosVolaris( (TiposVolaris.FirstTittle.MR, "luis", "segura", TiposVolaris.Gender.M, tipoPasajero[0], Convert.ToDateTime("19/05/1972"), "MX", "MX"));
                int c = target.AgregarPasajeros(pasajeros, signature);

                actual = target.GetBookingFromState(signature);

                DateTime tiempoFin = DateTime.Now;

                System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(actual.GetType());
                System.IO.StreamWriter file = new System.IO.StreamWriter(@"c:\RESP\PruebaAplicacionBookingResponse " + tiempoInicio.ToString("yyyy_MM_dd_HH_mm_ss") + tiempoFin.ToString("yyyy_MM_dd_HH_mm_ss") + ".xml");
                writer.Serialize(file, actual);
                file.Close();
            }
        }
Ejemplo n.º 49
0
        public void WriteLog_Load(
            string USERNAME, string SESSION_ID, string REQUEST_ID, string MERCHANT_ID
            , string IPADDRESS, string STATUS, string TRANS_ID, string MESSAGE_TYPE_ID
            , string MSISDN, double TRANSACTION_AMOUNT, string CLIENT_ID, string SYSTEM_TRACE_AUDIT_NUMBER
            , string REQUEST_TRANSMISSION_TIME, string RESPONSE_TRANSMISSION_TIME, string RESPONSE_CODE, string NOTE
            , string SERVICE_PROVIDER_CODE
            )
        {
            #region log into text file

            if (strTransactionLogType == "1" || strTransactionLogType == "3")
            {
                string strLogPath        = HttpContext.Current.Server.MapPath("") + "\\Log";
                string strYear           = DateTime.Now.Year.ToString();
                string strMonth          = DateTime.Now.Month.ToString();
                string strDay            = DateTime.Now.Day.ToString();
                string strFileName       = "Log_Load_" + DateTime.Now.ToString("hh") + "h.log";
                string strLogDescription = string.Empty;

                System.IO.DirectoryInfo d1 = new System.IO.DirectoryInfo(strLogPath);
                if (!d1.Exists)
                {
                    d1.Create();
                }
                strLogPath += "\\" + strYear;

                System.IO.DirectoryInfo d2 = new System.IO.DirectoryInfo(strLogPath);
                if (!d2.Exists)
                {
                    d2.Create();
                }
                strLogPath += "\\" + strMonth;

                System.IO.DirectoryInfo d3 = new System.IO.DirectoryInfo(strLogPath);
                if (!d3.Exists)
                {
                    d3.Create();
                }
                strLogPath += "\\" + strDay;

                System.IO.DirectoryInfo d4 = new System.IO.DirectoryInfo(strLogPath);
                if (!d4.Exists)
                {
                    d4.Create();
                }

                strLogPath         = strLogPath + "\\" + strFileName;
                strLogDescription  = USERNAME + "\t" + SESSION_ID + "\t" + REQUEST_ID + "\t" + MERCHANT_ID + "\t";
                strLogDescription += IPADDRESS + "\t" + STATUS + "\t" + TRANS_ID + "\t" + MESSAGE_TYPE_ID + "\t";
                strLogDescription += SERVICE_PROVIDER_CODE + "\t" + MSISDN + "\t" + TRANSACTION_AMOUNT + "\t" + CLIENT_ID + "\t";
                strLogDescription += SYSTEM_TRACE_AUDIT_NUMBER + "\t" + REQUEST_TRANSMISSION_TIME + "\t" + RESPONSE_TRANSMISSION_TIME + "\t" + RESPONSE_CODE + "\t";
                strLogDescription += NOTE + "\t";

                System.IO.FileStream   fs             = new System.IO.FileStream(strLogPath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
                System.IO.StreamWriter m_streamWriter = new System.IO.StreamWriter(fs);
                m_streamWriter.BaseStream.Seek(0, System.IO.SeekOrigin.End);
                m_streamWriter.WriteLine(strLogDescription);
                m_streamWriter.Flush();
                m_streamWriter.Close();
            }

            #endregion

            #region log into DB

            if (strTransactionLogType == "2" || strTransactionLogType == "3")
            {
                App_Lib DbObj  = new App_Lib();
                string  strSql = "";
                strSql  = "insert into Transactions(";
                strSql += "  USERNAME, SESSION_ID, REQUEST_ID, MERCHANT_ID";
                strSql += ", IPADDRESS, STATUS, TRANS_ID, MESSAGE_TYPE_ID";
                strSql += ", MSISDN, TRANSACTION_AMOUNT, CLIENT_ID, SYSTEM_TRACE_AUDIT_NUMBER";
                strSql += ", REQUEST_TRANSMISSION_TIME, RESPONSE_TRANSMISSION_TIME, RESPONSE_CODE, NOTE";
                strSql += ", SERVICE_PROVIDER_CODE, CDR_STATUS";
                strSql += " ) ";
                //, Status, ActionDate)";
                strSql += "values(";
                strSql += "'" + USERNAME + "', '" + SESSION_ID + "', '" + REQUEST_ID + "', '" + MERCHANT_ID + "'";
                strSql += " ,'" + IPADDRESS + "', '" + STATUS + "', '" + TRANS_ID + "', '" + MESSAGE_TYPE_ID + "'";
                strSql += " ,'" + MSISDN + "', '" + TRANSACTION_AMOUNT + "', '" + CLIENT_ID + "', '" + SYSTEM_TRACE_AUDIT_NUMBER + "'";
                strSql += " ,TO_DATE('" + REQUEST_TRANSMISSION_TIME + "','mm/dd/yyyy hh:mi:ss PM'), TO_DATE('" + RESPONSE_TRANSMISSION_TIME + "','mm/dd/yyyy hh:mi:ss PM'), '" + RESPONSE_CODE + "', '" + NOTE + "'";
                strSql += " ,'" + SERVICE_PROVIDER_CODE + "', '0'";
                strSql += ")";

                try
                {
                    DbObj.ExecuteQuery(strSql, null, CommandType.Text);
                }
                catch (Exception ex)
                {
                    //throw ex;
                    //HttpContext.Current.Response.Write(strSql);
                    //HttpContext.Current.Response.End();
                    WriteLog("Insert DB failure, ex=" + ex.ToString());
                }
            }

            #endregion
        }
 public void Log(SimpleSystemDataProvider provider)
 {
     System.IO.StreamWriter writer = new System.IO.StreamWriter(this.filePath, true);
     writer.WriteLine(DateTime.Now + "-> CPU load: " + provider.CPULoad + " Available RAM: " + provider.AvailableRAM);
     writer.Close();
 }
Ejemplo n.º 51
0
        public static void WriteF(TextBox Mess, string strList, string DumpFile, string OutFile, string user, string password)
        {
            #region Tabella template agomento
            Dictionary <string, string> TemArg = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
            {
                { "[[Template:Album]]", "album discografici" },
                { "[[Template:Azienda]]", "aziende" },
                { "[[Template:Bio]]", "biografie" },
                { "[[Template:Brano musicale]]", "brani musicali" },
                { "[[Template:College]]", "università" },
                { "[[Template:Università]]", "università" },
                { "[[Template:Composto chimico]]", "sostanze chimiche" },
                { "[[Template:Corpo celeste]]", "astronomia" },
                { "[[Template:Asteroide]]", "astronomia" },
                { "[[Template:Discografia]]", "discografie" },
                { "[[Template:Divisione amministrativa]]", "geografia" },
                { "[[Template:Dramma]]", "teatro" },
                { "[[Template:Opera]]", "teatro" },
                { "[[Template:Spettacolo teatrale]]", "teatro" },
                { "[[Template:Teatro]]", "teatro" },
                { "[[Template:Edificio civile]]", "architettura" },
                { "[[Template:Edificio religioso]]", "architettura" },
                { "[[Template:Festival musicale]]", "festival musicali" },
                { "[[Template:Fiction TV]]", "fiction televisive" },
                { "[[Template:Film]]", "film" },
                { "[[Template:Formazione geologica]]", "geologia" },
                { "[[Template:Roccia]]", "geologia" },
                { "[[Template:Terremoto]]", "geologia" },
                { "[[Template:Episodio Anime]]", "anime e manga" },
                { "[[Template:Stagione anime]]", "anime e manga" },
                { "[[Template:Videogioco]]", "videogiochi" },
                { "[[Template:Infobox aeromobile]]", "aviazione" },
                { "[[Template:Infobox aeroporto]]", "aviazione" },
                { "[[Template:Auto]]", "automobili" },
                { "[[Template:Auto1]]", "automobili" },
                { "[[Template:Infobox linea ferroviaria]]", "ferrovie" },
                { "[[Template:Infobox stazione ferroviaria]]", "ferrovie" },
                { "[[Template:Infobox linea metropolitana]]", "metropolitane" },
                { "[[Template:Infobox stazione della metropolitana]]", "metropolitane" },
                { "[[Template:Infobox metropolitana]]", "metropolitane" },
                { "[[Template:Partito politico]]", "partiti politici" },
                { "[[Template:Infobox ponte]]", "ponti" },
                { "[[Template:Libro]]", "opere letterarie" },
                { "[[Template:Minerale]]", "mineralogia" },
                { "[[Template:Montagna]]", "montagna" },
                { "[[Template:Catena montuosa]]", "montagna" },
                { "[[Template:Valico]]", "montagna" },
                { "[[Template:Rifugio]]", "montagna" },
                { "[[Template:Museo]]", "musei" },
                { "[[Template:Opera d'arte]]", "arte" },
                { "[[Template:Prenome]]", "antroponimi" },
                { "[[Template:Sito archeologico]]", "siti archeologici" },
                { "[[Template:Software]]", "software" },
                { "[[Template:Tassobox]]", "biologia" },
                { "[[Template:Isola]]", "geografia" },
                { "[[Template:Infobox isola]]", "geografia" },
                { "[[Template:Competizione cestistica nazionale]]", "competizioni cestistiche" },
                { "[[Template:Edizione di competizione sportiva]]", "sport" }
            };

            #endregion

            #region Tabella categorie agomento
            Dictionary <string, string> CatArg = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
            {
                { "[[Categoria:Araldica]]", "araldica" },
                { "[[Categoria:Cucina]]", "cucina" },
                { "[[Categoria:Giappone]]", "Giappone" },
                { "[[Categoria:Mitologia]]", "mitologia" },
                { "[[Categoria:Scacchi]]", "scacchi" },
                { "[[Categoria:Vessillologia]]", "vessillologia" },
                { "[[Categoria:Prenome]]", "antroponimi" },
                { "[[Categoria:Personaggi cinematografici]]", "personaggi cinematografici" },
                { "[[Categoria:Ordini di grandezza]]", "metrologia" },
                { "[[Categoria:Ordini di grandezza \\(lunghezza\\)]]", "metrologia" },
                { "[[Categoria:Ordini di grandezza \\(temperatura\\)]]", "metrologia" }
            };
            #endregion

            #region Tabella portale agomento
            Dictionary <string, string> PorArg = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
            {
                { "Astronomia", "astronomia" },
                { "Vessillologia", "vessillologia" },
                { "Religioni", "religione" },
                { "Aviazione", "aviazione" },
                { "Chimica", "chimica" },
                { "Geografia", "geografia" },
                { "Tennis", "tennis" },
                { "Matematica", "matematica" },
                { "Astronautica", "astronautica" },
                { "Mitologia", "mitologia" },
                { "Letteratura", "letteratura" },
                { "Oggetti del profondo cielo", "astronomia" },
                { "Sistema solare", "astronomia" },
                { "Psicologia", "psicologia" },
                { "Finlandia", "Finlandia" },
                { "Danimarca", "Danimarca" },
                { "Cinema", "cinema" },
                { "Musica", "musica" },
                { "Metrologia", "metrologia" },
                { "Politica", "politica" },
                { "Calcio", "calcio" },
                { "Polonia", "Polonia" },
                { "Nuoto", "nuoto" },
                { "Tolkien", "Terra di Mezzo" },
                { "Australia", "Australia" },
                { "Islanda", "Islanda" },
                { "Atletica leggera", "atletica leggera" },
                { "Automobilismo", "automobilismo" },
                { "Trasporti", "trasporti" },
                { "Anime e manga", "anime e manga" },
                { "Fisica", "fisica" }
            };
            #endregion

            Mess.AppendText("Iniziato alle " + DateTime.Now.ToString() + Environment.NewLine);
            string[] lines   = strList.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            string   tmpList = "";
            int      cont    = 0;
            for (int idx = 0; idx < lines.Count(); idx++)
            {
                tmpList += lines[idx] + "|";
            }
            tmpList = tmpList.Remove(tmpList.LastIndexOf("|"));
            List <string> list    = Utility.SplitInChunk(tmpList, "|", 500);
            string        strJson = "";
            Site          WP      = new Site("https://it.wikipedia.org", user, password);

            System.IO.StreamWriter log = new System.IO.StreamWriter(@"C:\Users\ValterVB\Documents\Visual Studio 2015\Projects\VBot\File\F da sistemare" + ".txt", false, Encoding.UTF8);

            string res = "";
            foreach (string s in list)
            {
                Pages pages = new Pages();
                strJson = WP.LoadWP(s);
                pages   = JsonConvert.DeserializeObject <Pages>(strJson);
                foreach (Page p in pages.query.pages.Values)
                {
                    if (p.pageid != null)
                    {
                        string text = p.revisions[0].text;
                        text = System.Net.WebUtility.HtmlDecode(text); //wiki text
                                                                       // Esclusione pagine con certi template
                        if (Regex.Match(text, @"{{\s*F\s*}}", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                           //{{F}}
                        else if (Regex.Match(text, @"{{\s*F[\r\n]?[\r\n]?\|", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                           //{{F
                        else if (Regex.Match(text, @"{{\s*S\s*}}", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                //{{S}}
                        else if (Regex.Match(text, @"{{\s*S[\r\n]?[\r\n]?\|", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                           //{{S
                        else if (Regex.Match(text, @"{{\s*A\s*}}", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                //{{A}}
                        else if (Regex.Match(text, @"{{\s*A[\r\n]?[\r\n]?\|", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                           //{{A
                        else if (Regex.Match(text, @"{{\s*NN\s*}}", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                 //{{NN}}
                        else if (Regex.Match(text, @"{{\s*NN[\r\n]?[\r\n]?\|", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                            //{{NN
                        else if (Regex.Match(text, @"{{\s*Disambigua\s*}}", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                         //{{Disambigua}}
                        else if (Regex.Match(text, @"{{\s*Disambigua[\r\n]?[\r\n]?\|", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                                    //{{Disambigua
                        else if (Regex.Match(text, @"{{\s*Controllo di autorità\s*}}", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                                    //{{Controllo di autorità}}
                        else if (Regex.Match(text, @"{{\s*Torna a\s*[\r\n]?[\r\n]?\|", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                                    //{{Torna a
                        else if (Regex.Match(text, @"{{\s*Cita\s*}}", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                   //{{Cita}}
                        else if (Regex.Match(text, @"{{\s*Cita[\r\n]?[\r\n]?\|", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                              //{{Cita
                        else if (Regex.Match(text, @"{{\s*Cita.+[\r\n]?[\r\n]?\|", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                                //{{Cita

                        // Esclusione pagine sulle date
                        else if (Regex.Match(text, @"{{\s*Decennio\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                             //{{Decennio
                        else if (Regex.Match(text, @"{{\s*Anno\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                         //{{Anno
                        else if (Regex.Match(text, @"{{\s*Secolo\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                           //{{Secolo
                        else if (Regex.Match(text, @"{{\s*Millennio\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                              //{{Millennio
                        else if (Regex.Match(text, @"{{\s*Gennaio\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                            //{{mese
                        else if (Regex.Match(text, @"{{\s*Febbraio\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                             //{{mese
                        else if (Regex.Match(text, @"{{\s*Marzo\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                          //{{mese
                        else if (Regex.Match(text, @"{{\s*Aprile\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                           //{{mese
                        else if (Regex.Match(text, @"{{\s*Maggio\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                           //{{mese
                        else if (Regex.Match(text, @"{{\s*Giugno\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                           //{{mese
                        else if (Regex.Match(text, @"{{\s*Luglio\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                           //{{mese
                        else if (Regex.Match(text, @"{{\s*Agosto\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                           //{{mese
                        else if (Regex.Match(text, @"{{\s*Settembre\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                              //{{mese
                        else if (Regex.Match(text, @"{{\s*Ottobre\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                            //{{mese
                        else if (Regex.Match(text, @"{{\s*Novembre\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                             //{{mese
                        else if (Regex.Match(text, @"{{\s*Dicembre\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                             //{{mese

                        else if (Regex.Match(text, @"{{\s*Numero intero\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                                  //{{numeri
                        else if (Regex.Match(text, @"{{\s*MSC\s*}}", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                  //{{MSC}}

                        else if (Regex.Match(text, @"{{\s*Incipit lista cognomi\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                                          //{{Incipit lista cognomi
                        else if (Regex.Match(text, @"{{\s*Incipit lista nomi\s*[|\r\n]*", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                                       //{{Incipit lista nomi


                        else if (Regex.Match(text, @"===?=?\s*Note\s*===?=?", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                           //{{S}}
                        else if (Regex.Match(text, @"===?=?\s*Bibliografia\s*===?=?", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                                   //{{S}}
                        else if (Regex.Match(text, @"===?=?\s*Collegamenti esterni\s*===?=?", RegexOptions.IgnoreCase).Success)
                        {
                        }                                                                                                           //{{S}}

                        else if (text.IndexOf("<ref", StringComparison.CurrentCultureIgnoreCase) != -1)
                        {
                        }
                        else if (text.IndexOf("http://", StringComparison.CurrentCultureIgnoreCase) != -1)
                        {
                        }
                        else if (text.IndexOf("https://", StringComparison.CurrentCultureIgnoreCase) != -1)
                        {
                        }
                        else
                        {
                            // Controllo i template
                            string F = "{{F|";
                            foreach (KeyValuePair <string, string> templ in TemArg)
                            {
                                string t = templ.Key.Replace("[[Template:", "").Replace("]]", "");
                                if (Regex.Match(text, @"{{\s*" + t + @"[\r\n]?[\r\n]?\|", RegexOptions.IgnoreCase).Success)
                                {
                                    F += templ.Value + "|" + DateTime.Now.ToString("MMMM") + " " + DateTime.Now.Year + "}}";
                                    break;
                                }
                            }
                            //Controllo le categorie
                            if (F.IndexOf("}") == -1)
                            {
                                foreach (KeyValuePair <string, string> cat in CatArg)
                                {
                                    string c = cat.Key.Replace("[", "").Replace("]", "");
                                    if (Regex.Match(text, @"\[\[" + c + @"\]\]", RegexOptions.IgnoreCase).Success || Regex.Match(text, @"\[\[" + c + @"\s*\|", RegexOptions.IgnoreCase).Success)
                                    {
                                        F += cat.Value + "|" + DateTime.Now.ToString("MMMM") + " " + DateTime.Now.Year + "}}";
                                        break;
                                    }
                                }
                            }
                            //Controllo i portali
                            if (F.IndexOf("}") == -1)
                            {
                                Regex  regex      = new Regex("({{portale)(\\|.*)+(}})", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
                                Match  ms         = regex.Match(text);
                                string tempValues = ms.Groups[2].Value;
                                foreach (KeyValuePair <string, string> por in PorArg)
                                {
                                    if (tempValues.IndexOf(por.Key, StringComparison.CurrentCultureIgnoreCase) != -1)
                                    {
                                        F += por.Value + "|" + DateTime.Now.ToString("MMMM") + " " + DateTime.Now.Year + "}}";
                                        break;
                                    }
                                }
                            }

                            if (F.IndexOf("}") == -1) // no arg
                            {
                                F += "" + "|" + DateTime.Now.ToString("MMMM") + " " + DateTime.Now.Year + "}}";
                                log.WriteLine(p.title + '\t' + "No argomenti");
                            }
                            else
                            {
                                Regex regex   = new Regex("(\\{\\{(?:[nN]d[ |]|[nN]ota disambigua|[tT]orna a)[^}]*}}|__[^_]+__)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
                                bool  IsMatch = regex.IsMatch(text);

                                if (IsMatch)
                                {
                                    log.WriteLine(p.title + '\t' + "Template in testa");
                                    //res += "*[[" + p.title + "]] \t <nowiki>Template da sistemare</nowiki>" + Environment.NewLine;
                                }
                                else
                                {
                                    text = F + Environment.NewLine + p.revisions[0].text;
                                    WP.SavePage(p.title, text, "BOT: Add template " + F);
                                    res += "*[[" + p.title + "]] \t <nowiki>" + F + "</nowiki>" + Environment.NewLine;
                                    cont++;
                                }
                            }
                        }
                    }
                }
            }
            log.Close();
            Mess.AppendText(Environment.NewLine);
            Mess.AppendText(res);
            Mess.AppendText(Environment.NewLine);
            Mess.AppendText("Finito alle " + DateTime.Now.ToString() + Environment.NewLine);
        }
Ejemplo n.º 52
0
        // This program takes around 4 minutes to run
        static void Main(string[] args)
        {
            // Read the previous weeks file
            DataTable tbl_previous = new DataTable();
            DataRow   dr;
            DateTime  dt;

            tbl_previous.Columns.Add("uid");
            tbl_previous.Columns.Add("points");
            tbl_previous.PrimaryKey = new DataColumn[] { tbl_previous.Columns["uid"] };

            string fileroot = "C:\\Users\\jnicol\\Documents\\Personal\\eterna\\top200\\";
            string filename = fileroot + DateTime.Today.AddDays(-7).ToString("yyyyMMdd") + ".csv";

            System.IO.StreamReader sr = new System.IO.StreamReader(filename);
            string stUsers, stPuzzles, st;
            int    i1, i2, i3, uid, nid, solves, solves_10, solves_3, solves_switch;
            int    smalleasy_left, specials_left, spores_left, bugs_left, spugs_left;
            int    smallswitches_left, switched_left, minibits_left, mirrors_left, rsod_left;
            int    basicshapes_left, tricksters_left, puzzlets_left, chainletters_left;
            int    smallshape_left, funandeasy_left, boostme_left, structuralrepresentation_left;
            int    puzzles_created, puzzles_created_10, puzzles_created_3, puzzles_created_0;

            stUsers = sr.ReadLine(); // read header row

            while ((stUsers = sr.ReadLine()) != null)
            {
                dr           = tbl_previous.NewRow();
                i1           = stUsers.IndexOf("&uid=");
                i2           = stUsers.IndexOf("\"", i1);
                dr["uid"]    = int.Parse(stUsers.Substring(i1 + 5, i2 - i1 - 5));
                i1           = stUsers.IndexOf(",", i2 + 1);
                i1           = stUsers.IndexOf(",", i1 + 1);
                i2           = stUsers.IndexOf(",", i1 + 1);
                dr["points"] = int.Parse(stUsers.Substring(i1 + 1, i2 - i1 - 1));
                tbl_previous.Rows.Add(dr);
            }
            sr.Close();

            // Build list of Small and Easy puzzles
            int[] list_smalleasy = { 628737, 640504, 670886, 688515, 688808, 699722, 702500, 727172, 729351, 745238, 764359, 774860, 774863, 784583, 832357, 856771, 865997, 872070, 885411, 889665, 898373, 910810, 930923, 939688, 939735, 972680, 972682, 1006862, 1007132, 1007826, 1010502, 1228731, 1440832 };
            // Build list of Special Knowledge puzzles
            int[] list_special = { 5223102, 5223098, 885402, 885457, 888973, 888975, 888976, 899958, 899967, 899970, 901494, 963091, 963104, 1884715, 1897861 };
            // Build list of Spore puzzles
            int[] list_spore = { 460876, 461243, 461244, 461261, 465866, 465868, 466455, 466483, 466733, 466938, 467048, 467168, 467411, 467590, 467765, 778671, 876296, 876345, 876359 };
            // Build list of Bug puzzles
            int[] list_bug = { 5530420, 5525720, 5509425, 5505453, 5496863, 5486447, 5481670, 5481045, 5440694, 921867, 922555, 922563, 924832, 933750, 934778, 936999, 938388, 939793, 941255, 943678, 949886, 960437, 960440, 966416, 967786, 969286, 970812, 973763, 974760, 975528, 978079, 980508, 982159, 983653, 987506, 989689, 991842, 993722, 998516, 999201, 999856, 1000520, 1001273, 1001452, 1004465, 1005229, 1005956, 1006649, 1006697, 1007275, 1009216, 1009765, 1010399, 1027476, 1040119, 1059293, 1072878, 1088244, 1102242, 1132731, 1140523, 1271121, 1297872, 1333522, 1352620, 1372006, 1392204, 1419605, 1448148, 1464685, 1468791, 1504044, 1504102, 1543791, 1586778, 1594807, 1850224, 1852817, 1855316, 1857288, 1864825, 1868210, 1869954, 1872173, 1883111 };
            // Build list of Spug puzzles
            int[] list_spug = { 2439674, 2441085, 2449037, 2449362, 2453379, 2453413, 2463213, 2466841, 2468887, 2524875, 2524934, 2524972, 2541563, 2541569, 2541588, 2587536, 2587549 };
            // Build list of Small Switch Training puzzles
            int[] list_smallswitch = { 2533540, 2533544, 2533546, 2538013, 2538015, 2538017, 2542160, 2542162, 2545789, 2545791, 2545793, 2549593, 2549595, 2549597, 2553603, 2553605, 2553607, 2559356, 2559358, 2559360, 2563392, 2567228, 2567230, 2567234, 2571137, 2571139, 2571141, 2575665, 2575667, 2575669, 2580108 };
            // Build list of Switched puzzles
            int[] list_switched = { 3705313, 3705311, 3702514, 3702512, 3700303, 3700074, 3698049, 3698047, 3695997, 3695995, 3693541, 3693530, 3691506, 3691504, 3689550, 3689503, 3686825, 3686823, 3683760, 3683758, 3682384, 3682370, 3679656, 3679654, 3676781, 3676779, 3673650, 3673648, 3667963, 3667961, 3665533, 3665511, 3663088, 3663086, 3661424, 3661414, 3659819, 3659783, 3658499, 3658497, 3657188, 3657186, 3655482, 3655480, 3654255, 3654221, 3652459, 3652457, 3650370, 3650342, 3647918, 3647916, 3645882, 3645862, 3643790, 3643788, 3641700, 3641693, 3639394, 3639339, 3637494, 3637493, 3635588, 3635564, 3633640, 3633638, 3631248, 3631246, 3628339, 3628337, 3626230, 3625951, 3623546, 3623544, 3618698, 3618696, 3614581, 3614579, 3609678, 3609634, 3607565, 3607563, 3604910, 3604908, 3602898, 3602884, 3600202, 3600194, 3597844, 3597842, 3596083, 3596081, 3593915, 3593913, 3591908, 3591906, 3589496, 3589494, 3586262, 3586260 };
            // Build list of Minibit puzzles
            int[] list_minibit = { 3194553, 3194555, 3194557, 3196597, 3196599, 3196601, 3199302, 3199304, 3199306, 3201634, 3201638, 3201641, 3203863, 3203865, 3203867, 3205977, 3205979, 3205981, 3207952, 3207954, 3207956, 3209906, 3209908, 3209910, 3211446, 3211448, 3211450, 3214259, 3214261, 3214263, 3216473, 3216475, 3216477, 3221494, 3221496, 3221498, 3223907, 3223909, 3223911 };
            // Build list of Mirror puzzles
            int[] list_mirror = { 2335599, 2338875, 2339567, 2340979, 2341643, 2369997, 2370153, 2373022, 2373374, 2373407, 2376546, 2377064, 2377197, 2380827, 2382071, 2382120, 2384531, 2386304, 2386481, 2386913, 2388507, 2411141, 2423683, 2426603, 2429500, 2431208, 2431423, 2434137, 2434605, 2437476, 2443488, 2444502, 2445030, 2448260, 2448783, 2449592, 2450948, 2453341, 2454292, 2455815, 2455886, 2458323, 2460051, 2462604, 2476060, 2498108, 2502516, 2520278, 2520326, 2520940, 2545244, 2545409, 2553058, 2575235, 2579034, 2579990, 2580963, 2584160, 2585311, 2588855, 2627082, 2643182, 2648696, 2648914, 2648933, 2652503, 2659887, 2661246, 2668638, 2670271, 2674992, 2675488, 2675535, 2686833, 2701431, 2701511, 2702128, 2715708, 2749275, 2811274, 2820413, 2820486, 2820629, 2823117, 2824303, 2824342, 2824485, 2829857, 2831459, 2832205, 2838539, 2838547, 2838578, 2842197, 2842623, 2842834, 2846271, 2846307, 2846318, 2849613, 2849619, 2849632, 2853805, 2853819, 2853838, 3399967, 3401552, 3426467, 3480879 };
            // Build list of RSOD puzzles
            int[] list_rsod = { 3393925, 3394089, 3394117, 3396457, 3396533, 3399345, 3401274, 3403367, 3404848, 3406585, 3407488, 3409371, 3409377, 3412912, 3416592, 3416714, 3421857, 3421866, 3424676, 3426814, 3450032, 3450037, 3450046, 3454012, 3454014, 3457291, 3457293, 3462543, 3462558, 3462577, 3465664, 3465669, 3470194, 3470196, 3474134, 3474137, 3477169, 3477171, 3479768, 3479770, 3479772, 3482668, 3482671, 3488870, 3488872, 3488878, 3492812, 3492814, 3492816, 3495694 };
            // Build list of Basic Shapes puzzles
            int[] list_basicshapes = { 4186996, 4178237, 4172190, 4172108, 4156377, 4147399, 4147194, 4142431, 4138842, 4138782 };
            // Build list of Trickster puzzles
            int[] list_tricksters = { 3225468, 3225500, 3226151, 3229453, 3233285, 3233537, 3266478, 3237235, 3236996, 3237312, 3239434, 3239490, 3239528, 3241848, 3241890, 3242035, 3243833, 3245958, 3246013, 3246015, 3248262, 3248719, 3250817, 3252065, 3252980, 3257059, 3258384, 3260582, 3267592, 3273924, 3273936, 3276889, 3276988, 3284843, 3297637, 3307368, 3319288, 3327649 };
            // Build list of Puzzlet puzzles
            int[] list_puzzlets = { 5198481, 4930143, 4897017, 4886806, 4828344, 4783555, 4776227, 4756464, 4645515, 4634091, 4590639, 4494158, 4368285, 4360718, 4315075, 4263194, 4227188, 4225993, 4219585, 4182414, 4120729, 4105616, 4072226, 4043234, 3950819, 3923361, 3822755, 3756527, 3734129, 3722616, 3712599, 3709868, 3694841, 3686673, 3651180, 3637090, 3602614, 3581766, 3559860, 3538808, 3494415, 3488747, 3482930, 3471681, 3394672, 3365126, 3339877, 3282479, 3232217, 3060315, 2725418 };
            // Build list of Chain Letter puzzles
            int[] list_chainletters = { 4330993, 4326759, 4304242, 4298776, 4286424, 4277890, 4270923, 4270435, 4270026, 4260214, 4260089, 4243747, 4239119, 4231840, 4229935, 4218598, 4217256, 4215977, 4215035, 4180071, 4170805, 4170728, 4170704, 4170031, 4169065, 4162378, 4159873, 4159234, 4156764, 4147338, 4138661, 4137798, 4136281, 4135015, 4061187, 4033926, 3985684, 3981699, 3970582, 3967229, 3965981, 3965816, 3965181, 3921786, 3921662 };
            // Build list of Small Shape puzzles
            int[] list_smallshape = { 4772231, 4769685, 4244663, 4228114, 3932181, 3279461, 3279438, 3240251, 3236236, 3222762, 3063908, 2844270, 2628059, 1656115, 1651904, 1651802, 1651792, 1642982, 1636377, 1626167, 1611914, 1591298, 1480361, 1474060, 1441422, 1391383, 1381029, 1010333, 1002989, 999017, 996310, 992679 };
            // Build list of Fun and Easy puzzles
            int[] list_funandeasy = { 5281156, 5105539, 5026553, 5014799, 4979935, 4979895, 4883332, 4783904, 4729246, 4724109, 4694891, 4678864, 4674492, 4674384, 4668765, 4666355, 4664286, 4629746, 4478518, 4314613, 4314460, 4292190, 4285613, 4274825, 4267575, 4230426, 4226698, 4222487, 4217147, 4213427, 4213395, 4182418, 4180191, 4166011, 4157365, 4151044, 4147695 };
            // Build list of Boost Me puzzles
            int[] list_boostme = { 5613941, 5583207, 5529736, 5279262, 5121238, 4946971, 4856002, 4855990, 4847938, 4734631, 4729443, 4728241, 4728231, 4662025, 4660092, 4537091, 4314813, 4156764, 4147747, 4142946, 4124882, 4120153, 4120117, 4047253, 4044779, 4042666, 3993116, 3737063, 3737060, 3736687, 3679326, 3679036, 3679026, 3579951, 3507264, 3503132, 3453294, 3449552, 3435216, 3435181, 3296525, 3288665, 3277396, 3242065, 3195259, 3158139, 3134772, 3105234, 3086598, 3043459, 3043106, 3015187, 2942052, 2941941, 2899022, 2873700, 2873693, 2870396, 2870321, 2870306, 2648450, 2644112, 2570264, 2569947, 2564567, 2564440, 2564119, 2532266, 2504087, 2486427 };
            // Build list of Structural Representation puzzles
            int[] list_structuralrepresentation = { 5660043, 5657210, 5654891, 5654259, 5645689, 5635123, 5618938, 5618266, 5616125, 5613679, 5610873, 5608529, 5608370, 5605703, 5600472, 5591881, 5586320, 5581188, 5439579, 5385961, 5374293, 5322111, 5131139, 5124253, 5124201, 5101218, 5073097, 5059595, 5056041, 5053782, 5051829, 5048047, 5047877, 5047128, 5044902, 5041827, 5031725, 5028157, 5028048, 5026729, 5022815, 5022758, 5021911, 5016432, 5014369, 5011439, 5005929, 5005358, 5001488, 5000710, 5000520, 4997070, 4987260, 4980809, 4978220, 4976363, 4968741, 4964531, 4960368, 4955951, 4945820, 4937703, 4926788, 4923214, 4921006, 4919751, 4914184, 4908922, 4906780, 4902098, 4891834, 4885180, 4881673, 4878721, 4873229, 4869706, 4867445, 4858412, 4853858, 4841319, 4841197, 4833286, 4827975, 4809285, 4793787, 4782674, 4780635, 4780516, 4774127, 4773812, 4751705, 4751447, 4746999, 4743342, 4742777, 4738347, 4706909, 4705281, 4701173, 4698233, 4697123, 4696738, 4693666, 4692254, 4689362, 4684360, 4684273, 4654489, 4654014, 4647200, 4646468, 4643852, 4640099, 4639237, 4638101, 4634619, 4634331, 4632800, 4628539, 4625824, 4625345, 4622632, 4616282, 4611379, 4610972, 4609606, 4580740, 4546466, 4534090, 4526464, 4525234, 4522394, 4516551, 4516334, 4513428, 4506931, 4505449, 4498411, 4495188, 4490158, 4482931, 4482310, 4480623, 4467937, 4466852, 4458253, 4422345, 4420974, 4413623, 4342791, 4342361, 4341547, 4329159, 4327990, 4327576, 4323762, 4322254, 4322018, 4316121, 4315886 };

            // Get all puzzles that have 10 or less solvers
            DataTable tbl_puzzle = new DataTable();

            System.Net.WebRequest  req;
            System.IO.StreamReader rsp;
            tbl_puzzle.Columns.Add("nid");
            tbl_puzzle.Columns.Add("solves");
            tbl_puzzle.PrimaryKey = new DataColumn[] { tbl_puzzle.Columns["nid"] };
            i2 = 0; i3 = 5000; stPuzzles = ""; // skip the first 5000 puzzles since they have 16 or more solvers

            while (stPuzzles == "" || stPuzzles.IndexOf("\"id\"") > 0)
            {
                while ((i1 = stPuzzles.IndexOf("\"id\"", i2)) > 0)
                {
                    i2  = stPuzzles.IndexOf(",", i1);
                    nid = int.Parse(stPuzzles.Substring(i1 + 6, i2 - i1 - 7));
                    i1  = stPuzzles.IndexOf("\"created\"", i2);
                    i2  = stPuzzles.IndexOf(",", i1);
                    dt  = new DateTime(long.Parse(stPuzzles.Substring(i1 + 11, i2 - i1 - 12)) * 10000000 + DateTime.Parse("1-1-1970").Ticks);
                    i1  = stPuzzles.IndexOf("\"num-cleared\"", i2);
                    i2  = stPuzzles.IndexOf(",", i1);
                    st  = stPuzzles.Substring(i1 + 15, i2 - i1 - 16);
                    if (int.TryParse(st, out i1))
                    {
                        solves = int.Parse(st);
                    }
                    else
                    {
                        solves = 0;
                    }
                    if (solves <= 10 && dt.CompareTo(DateTime.Today.AddDays(-7)) == -1) // only get puzzles with 10 or less solves that are older than 1 week
                    {
                        dr           = tbl_puzzle.NewRow();
                        dr["nid"]    = nid;
                        dr["solves"] = solves;
                        tbl_puzzle.Rows.Add(dr);
                    }
                }
                req       = System.Net.WebRequest.Create("http://eterna.cmu.edu/get/?type=puzzles&sort=solved&puzzle_type=PlayerPuzzle&size=100&skip=" + i3.ToString());
                rsp       = new System.IO.StreamReader(req.GetResponse().GetResponseStream());
                stPuzzles = rsp.ReadToEnd();
                i3        = i3 + 100; i2 = 0;
            }

            // Get all switch puzzles
            DataTable tbl_switches = new DataTable();

            tbl_switches.Columns.Add("nid");
            tbl_switches.Columns.Add("solves");
            tbl_switches.PrimaryKey = new DataColumn[] { tbl_switches.Columns["nid"] };
            i2 = 0; i3 = 0; stPuzzles = "";

            while (stPuzzles == "" || stPuzzles.IndexOf("\"id\"") > 0)
            {
                while ((i1 = stPuzzles.IndexOf("\"id\"", i2)) > 0)
                {
                    i2  = stPuzzles.IndexOf(",", i1);
                    nid = int.Parse(stPuzzles.Substring(i1 + 6, i2 - i1 - 7));
                    i1  = stPuzzles.IndexOf("\"created\"", i2);
                    i2  = stPuzzles.IndexOf(",", i1);
                    dt  = new DateTime(long.Parse(stPuzzles.Substring(i1 + 11, i2 - i1 - 12)) * 10000000 + DateTime.Parse("1-1-1970").Ticks);
                    i1  = stPuzzles.IndexOf("\"num-cleared\"", i2);
                    i2  = stPuzzles.IndexOf(",", i1);
                    st  = stPuzzles.Substring(i1 + 15, i2 - i1 - 16);
                    if (int.TryParse(st, out i1))
                    {
                        solves = int.Parse(st);
                    }
                    else
                    {
                        solves = 0;
                    }
                    dr           = tbl_switches.NewRow();
                    dr["nid"]    = nid;
                    dr["solves"] = solves;
                    tbl_switches.Rows.Add(dr);
                }
                req       = System.Net.WebRequest.Create("http://eterna.cmu.edu/get/?type=puzzles&sort=solved&puzzle_type=PlayerPuzzle&switch=checked&size=100&skip=" + i3.ToString());
                rsp       = new System.IO.StreamReader(req.GetResponse().GetResponseStream());
                stPuzzles = rsp.ReadToEnd();
                i3        = i3 + 100; i2 = 0;
            }

            // Get the top 200 players
            DataTable tbl_current = new DataTable();

            tbl_current.Columns.Add("uid");
            tbl_current.Columns.Add("uname");
            tbl_current.Columns.Add("points");
            tbl_current.Columns.Add("started");
            tbl_current.Columns.Add("solves");
            tbl_current.Columns.Add("solves_switch");
            tbl_current.Columns.Add("solves_10");
            tbl_current.Columns.Add("solves_3");
            tbl_current.Columns.Add("puzzles_created");
            tbl_current.Columns.Add("puzzles_created_bns");
            tbl_current.Columns.Add("puzzles_created_10");
            tbl_current.Columns.Add("puzzles_created_3");
            tbl_current.Columns.Add("puzzles_created_0");
            tbl_current.Columns.Add("smalleasy_left");
            tbl_current.Columns.Add("specials_left");
            tbl_current.Columns.Add("spores_left");
            tbl_current.Columns.Add("bugs_left");
            tbl_current.Columns.Add("spugs_left");
            tbl_current.Columns.Add("smallswitches_left");
            tbl_current.Columns.Add("switched_left");
            tbl_current.Columns.Add("minibits_left");
            tbl_current.Columns.Add("mirrors_left");
            tbl_current.Columns.Add("rsod_left");
            tbl_current.Columns.Add("basicshapes_left");
            tbl_current.Columns.Add("tricksters_left");
            tbl_current.Columns.Add("puzzlets_left");
            tbl_current.Columns.Add("chainletters_left");
            tbl_current.Columns.Add("smallshape_left");
            tbl_current.Columns.Add("funandeasy_left");
            tbl_current.Columns.Add("boostme_left");
            tbl_current.Columns.Add("structuralrepresentation_left");

            DataTable tbl_created = new DataTable();

            tbl_created.Columns.Add("nid");
            tbl_created.PrimaryKey = new DataColumn[] { tbl_created.Columns["nid"] };

            req     = System.Net.WebRequest.Create("http://eterna.cmu.edu/get/?type=users&sort=point&size=200");
            rsp     = new System.IO.StreamReader(req.GetResponse().GetResponseStream());
            stUsers = rsp.ReadToEnd(); i2 = 0;
            while ((i1 = stUsers.IndexOf("\"uid\"", i2)) > 0)
            {
                i2  = stUsers.IndexOf(",", i1);
                uid = int.Parse(stUsers.Substring(i1 + 7, i2 - i1 - 8));

                // Get each players created puzzle list
                req             = System.Net.WebRequest.Create("http://eterna.cmu.edu//get/?type=user&tab_type=created&uid=" + uid.ToString());
                rsp             = new System.IO.StreamReader(req.GetResponse().GetResponseStream());
                stPuzzles       = rsp.ReadToEnd(); i3 = 0; tbl_created.Clear();
                puzzles_created = 0; puzzles_created_10 = 0; puzzles_created_3 = 0; puzzles_created_0 = 0;
                while ((i1 = stPuzzles.IndexOf("\"id\"", i3 + 1)) > 0)
                {
                    dr        = tbl_created.NewRow();
                    i3        = stPuzzles.IndexOf(",", i1);
                    nid       = int.Parse(stPuzzles.Substring(i1 + 6, i3 - i1 - 7));
                    dr["nid"] = nid;
                    tbl_created.Rows.Add(dr);
                    puzzles_created++;
                    dr = tbl_puzzle.Rows.Find(nid); // find 10 or less puzzles solved
                    if (dr != null)
                    {
                        puzzles_created_10++;
                        if (int.Parse(dr["solves"].ToString()) <= 3)
                        {
                            puzzles_created_3++;
                            if (int.Parse(dr["solves"].ToString()) == 0)
                            {
                                puzzles_created_0++;
                            }
                        }
                    }
                }

                // Get each players solved puzzle list
                req             = System.Net.WebRequest.Create("http://eterna.cmu.edu//get/?type=user&tab_type=cleared&uid=" + uid.ToString());
                rsp             = new System.IO.StreamReader(req.GetResponse().GetResponseStream());
                stPuzzles       = rsp.ReadToEnd(); i3 = 0;
                solves          = 0; solves_10 = 0; solves_3 = 0; solves_switch = 0;
                smalleasy_left  = list_smalleasy.Length; specials_left = list_special.Length; spores_left = list_spore.Length;
                bugs_left       = list_bug.Length; spugs_left = list_spug.Length; smallswitches_left = list_smallswitch.Length; switched_left = list_switched.Length;
                minibits_left   = list_minibit.Length; mirrors_left = list_mirror.Length; rsod_left = list_rsod.Length; basicshapes_left = list_basicshapes.Length;
                tricksters_left = list_tricksters.Length; puzzlets_left = list_puzzlets.Length; chainletters_left = list_chainletters.Length;
                smallshape_left = list_smallshape.Length; funandeasy_left = list_funandeasy.Length;
                boostme_left    = list_boostme.Length; structuralrepresentation_left = list_structuralrepresentation.Length;
                while ((i1 = stPuzzles.IndexOf("\"nid\"", i3 + 1)) > 0)
                {
                    solves++;
                    i3  = stPuzzles.IndexOf(",", i1);
                    nid = int.Parse(stPuzzles.Substring(i1 + 7, i3 - i1 - 8));
                    dr  = tbl_puzzle.Rows.Find(nid); // find 10 or less puzzles solved
                    if (dr != null)
                    {
                        solves_10++; if (int.Parse(dr["solves"].ToString()) <= 3)
                        {
                            solves_3++;
                        }
                    }
                    dr = tbl_created.Rows.Find(nid); // remove from puzzles created list if it has been solved
                    if (dr != null)
                    {
                        tbl_created.Rows.Remove(dr);
                    }
                    dr = tbl_switches.Rows.Find(nid); // find switches solved
                    if (dr != null)
                    {
                        solves_switch++;
                    }
                    if (Array.Find(list_smalleasy, id => id == nid) > 0)
                    {
                        smalleasy_left--;
                    }
                    else if (Array.Find(list_special, id => id == nid) > 0)
                    {
                        specials_left--;
                    }
                    else if (Array.Find(list_spore, id => id == nid) > 0)
                    {
                        spores_left--;
                    }
                    else if (Array.Find(list_bug, id => id == nid) > 0)
                    {
                        bugs_left--;
                    }
                    else if (Array.Find(list_spug, id => id == nid) > 0)
                    {
                        spugs_left--;
                    }
                    else if (Array.Find(list_smallswitch, id => id == nid) > 0)
                    {
                        smallswitches_left--;
                    }
                    else if (Array.Find(list_switched, id => id == nid) > 0)
                    {
                        switched_left--;
                    }
                    else if (Array.Find(list_minibit, id => id == nid) > 0)
                    {
                        minibits_left--;
                    }
                    else if (Array.Find(list_mirror, id => id == nid) > 0)
                    {
                        mirrors_left--;
                    }
                    else if (Array.Find(list_rsod, id => id == nid) > 0)
                    {
                        rsod_left--;
                    }
                    else if (Array.Find(list_basicshapes, id => id == nid) > 0)
                    {
                        basicshapes_left--;
                    }
                    else if (Array.Find(list_tricksters, id => id == nid) > 0)
                    {
                        tricksters_left--;
                    }
                    else if (Array.Find(list_puzzlets, id => id == nid) > 0)
                    {
                        puzzlets_left--;
                    }
                    else if (Array.Find(list_chainletters, id => id == nid) > 0)
                    {
                        chainletters_left--;
                    }
                    else if (Array.Find(list_smallshape, id => id == nid) > 0)
                    {
                        smallshape_left--;
                    }
                    else if (Array.Find(list_funandeasy, id => id == nid) > 0)
                    {
                        funandeasy_left--;
                    }
                    else if (Array.Find(list_boostme, id => id == nid) > 0)
                    {
                        boostme_left--;
                    }
                    else if (Array.Find(list_structuralrepresentation, id => id == nid) > 0)
                    {
                        structuralrepresentation_left--;
                    }
                }

                // Check each players created but not solved puzzle list for 10 or less puzzles solved and switches solved
                for (i1 = 0; i1 < tbl_created.Rows.Count; i1++)
                {
                    nid = int.Parse(tbl_created.Rows[i1]["nid"].ToString());
                    dr  = tbl_puzzle.Rows.Find(nid);
                    if (dr != null)
                    {
                        solves_10++; if (int.Parse(dr["solves"].ToString()) <= 3)
                        {
                            solves_3++;
                        }
                    }
                    dr = tbl_switches.Rows.Find(nid);
                    if (dr != null)
                    {
                        solves_switch++;
                    }
                }

                // Save each players solved stats
                dr                                  = tbl_current.NewRow();
                dr["uid"]                           = uid;
                i1                                  = i2 + 9;
                i2                                  = stUsers.IndexOf(",", i1);
                dr["uname"]                         = stUsers.Substring(i1, i2 - i1 - 1);
                i1                                  = stUsers.IndexOf("\"points\"", i2);
                i2                                  = stUsers.IndexOf(",", i1);
                dr["points"]                        = stUsers.Substring(i1 + 10, i2 - i1 - 11);
                i1                                  = stUsers.IndexOf("\"created\"", i2);
                i2                                  = stUsers.IndexOf(",", i1);
                dr["started"]                       = stUsers.Substring(i1 + 11, i2 - i1 - 12);
                dr["solves"]                        = solves;
                dr["solves_switch"]                 = solves_switch;
                dr["solves_10"]                     = solves_10;
                dr["solves_3"]                      = solves_3;
                dr["puzzles_created"]               = puzzles_created;
                dr["puzzles_created_bns"]           = tbl_created.Rows.Count;
                dr["puzzles_created_10"]            = puzzles_created_10;
                dr["puzzles_created_3"]             = puzzles_created_3;
                dr["puzzles_created_0"]             = puzzles_created_0;
                dr["smalleasy_left"]                = smalleasy_left;
                dr["specials_left"]                 = specials_left;
                dr["spores_left"]                   = spores_left;
                dr["bugs_left"]                     = bugs_left;
                dr["spugs_left"]                    = spugs_left;
                dr["smallswitches_left"]            = smallswitches_left;
                dr["switched_left"]                 = switched_left;
                dr["minibits_left"]                 = minibits_left;
                dr["mirrors_left"]                  = mirrors_left;
                dr["rsod_left"]                     = rsod_left;
                dr["basicshapes_left"]              = basicshapes_left;
                dr["tricksters_left"]               = tricksters_left;
                dr["puzzlets_left"]                 = puzzlets_left;
                dr["chainletters_left"]             = chainletters_left;
                dr["smallshape_left"]               = smallshape_left;
                dr["funandeasy_left"]               = funandeasy_left;
                dr["boostme_left"]                  = boostme_left;
                dr["structuralrepresentation_left"] = structuralrepresentation_left;
                tbl_current.Rows.Add(dr);
            }

            // Write the stats to a new file
            filename = fileroot + DateTime.Today.ToString("yyyyMMdd") + ".csv";
            System.IO.StreamWriter sw = new System.IO.StreamWriter(filename);
            sw.WriteLine("Rank,Player,Playing Since,Points as of,Points as of,Points / Day,Last Week,Puzzles Solved,Switches,Puzzles Solved 10 or less solvers,Puzzles Solved 3 or less solvers,Puzzles Created,Puzzles Created But Not Solved,Puzzles Created 10 or less solvers,Puzzles Created 3 or less solvers,Puzzles Created with 0 solvers,Small and Easy left,Special Knowledge left,Spores left,Bugs left,Spugs left,Basic Shapes left,Small Switches left,Switched left,Minibits left,Mirrors left,RSOD left,Tricksters left,Puzzlets left,Chain Letters left,Small Shape left,Fun and Easy left,Boost Me left,Structural Representation left");
            for (i1 = 0; i1 < tbl_current.Rows.Count; i1++)
            {
                stUsers  = (i1 + 1).ToString() + ",\"=hyperlink(\"\"http://eterna.cmu.edu/eterna_page.php?page=player&uid=";
                stUsers += tbl_current.Rows[i1]["uid"] + "\"\";\"\"" + tbl_current.Rows[i1]["uname"] + "\"\")\",";
                stUsers += tbl_current.Rows[i1]["started"] + ",";
                stUsers += tbl_current.Rows[i1]["points"] + ",";
                dr       = tbl_previous.Rows.Find(tbl_current.Rows[i1]["uid"]);
                if (dr == null)
                {
                    i2 = 0;
                }
                else
                {
                    i2 = int.Parse(dr["points"].ToString());
                }
                stUsers += i2.ToString() + ",";
                dt       = DateTime.Parse(tbl_current.Rows[i1]["started"].ToString());
                stUsers += (int.Parse(tbl_current.Rows[i1]["points"].ToString()) / DateTime.Today.Subtract(dt).Days).ToString() + ",";
                stUsers += (int.Parse(tbl_current.Rows[i1]["points"].ToString()) - i2).ToString() + ",";
                stUsers += tbl_current.Rows[i1]["solves"] + ",";
                stUsers += tbl_current.Rows[i1]["solves_switch"] + ",";
                stUsers += tbl_current.Rows[i1]["solves_10"] + ",";
                stUsers += tbl_current.Rows[i1]["solves_3"] + ",";
                stUsers += tbl_current.Rows[i1]["puzzles_created"] + ",";
                stUsers += tbl_current.Rows[i1]["puzzles_created_bns"] + ",";
                stUsers += tbl_current.Rows[i1]["puzzles_created_10"] + ",";
                stUsers += tbl_current.Rows[i1]["puzzles_created_3"] + ",";
                stUsers += tbl_current.Rows[i1]["puzzles_created_0"] + ",";
                stUsers += tbl_current.Rows[i1]["smalleasy_left"] + ",";
                stUsers += tbl_current.Rows[i1]["specials_left"] + ",";
                stUsers += tbl_current.Rows[i1]["spores_left"] + ",";
                stUsers += tbl_current.Rows[i1]["bugs_left"] + ",";
                stUsers += tbl_current.Rows[i1]["spugs_left"] + ",";
                stUsers += tbl_current.Rows[i1]["basicshapes_left"] + ",";
                stUsers += tbl_current.Rows[i1]["smallswitches_left"] + ",";
                stUsers += tbl_current.Rows[i1]["switched_left"] + ",";
                stUsers += tbl_current.Rows[i1]["minibits_left"] + ",";
                stUsers += tbl_current.Rows[i1]["mirrors_left"] + ",";
                stUsers += tbl_current.Rows[i1]["rsod_left"] + ",";
                stUsers += tbl_current.Rows[i1]["tricksters_left"] + ",";
                stUsers += tbl_current.Rows[i1]["puzzlets_left"] + ",";
                stUsers += tbl_current.Rows[i1]["chainletters_left"] + ",";
                stUsers += tbl_current.Rows[i1]["smallshape_left"] + ",";
                stUsers += tbl_current.Rows[i1]["funandeasy_left"] + ",";
                stUsers += tbl_current.Rows[i1]["boostme_left"] + ",";
                stUsers += tbl_current.Rows[i1]["structuralrepresentation_left"];
                sw.WriteLine(stUsers);
            }
            sw.Close();
        }
Ejemplo n.º 53
0
        internal static void WriteRecordingsToFile(TranscriptCmdletBase cmdlet, string fileName)
        {
//            System.IO.StreamWriter writer0001 =
//                new System.IO.StreamWriter(@"C:\1\__writer0001__.txt");
//            for (int i = 0; i < Recorder.recordingCollection.Count; i++) {
//                for (int j = 0; j < Recorder.recordingCollection[i].Items.Count; j++) {
//
//                    RecordedWebElement webE = Recorder.recordingCollection[i].Items[j] as RecordedWebElement;
//                    RecordedAction actE = Recorder.recordingCollection[i].Items[j] as RecordedAction;
//                    RecordedData dataE = Recorder.recordingCollection[i].Items[j] as RecordedData;
//
//                    if (null != webE) {
//                        foreach (string webKey in webE.UserData.Keys) {
//                            writer0001.WriteLine("\r\n" + webKey + "\t" + webE.UserData[webKey]);
//                        }
//                        writer0001.Flush();
//                    } else if (null != actE) {
//                        foreach (string actKey in actE.UserData.Keys) {
//                            writer0001.WriteLine("\r\n" + actKey + "\t" + actE.UserData[actKey]);
//                        }
//                        writer0001.Flush();
//                    } else if (null != dataE) {
//                        foreach (string dataKey in dataE.UserData.Keys) {
//                            writer0001.WriteLine("\r\n" + dataKey + "\t" + dataE.UserData[dataKey]);
//                        }
//                        writer0001.Flush();
//                    } else {
//                        writer0001.WriteLine("\r\nother");
//                        writer0001.Flush();
//                    }
//                }
//            }
//            writer0001.Flush();
//            writer0001.Close();

            cmdlet.WriteVerbose(cmdlet, "WriteRecordingsToFile");

            var commonData = string.Empty;

            //foreach (IRecordedCodeSequence codeSequence in recordingCollection) {
            foreach (var codeSequence in RecordingCollection)
            {
                commonData =
                    ConvertCodeSequenceToCode(codeSequence, (new PsLanguage()), commonData);
                Console.WriteLine("<<<<<<<<<<<<<<<<<<< written >>>>>>>>>>>>>>>>>>>>>");
            }

            if (string.Empty != commonData)
            {
                Console.WriteLine("<<<<<<<<<<<<<<<<<<< string.Empty != commonData >>>>>>>>>>>>>>>>>>>>>");
                try {
                    using (var writer = new System.IO.StreamWriter(fileName)) {
                        Console.WriteLine("<<<<<<<<<<<<<<<<<<< writing to the file >>>>>>>>>>>>>>>>>>>>>");
                        writer.WriteLine(commonData);
                        writer.Flush();
                        writer.Close();
                        Console.WriteLine("<<<<<<<<<<<<<<<<<<< written to the file >>>>>>>>>>>>>>>>>>>>>");
                    }
                }
                catch (Exception eOutputFileProblem) {
                    Console.WriteLine("<<<<<<<<<<<<<<<<<<< error >>>>>>>>>>>>>>>>>>>>>");
                    cmdlet.WriteError(
                        cmdlet,
                        "Couldn't save data to the file '" +
                        fileName +
                        "'. " +
                        eOutputFileProblem.Message,
                        "FailedToSaveData",
                        ErrorCategory.InvalidArgument,
                        true);
                }
            }
            else
            {
                Console.WriteLine("<<<<<<<<<<<<<<<<<<< error2 >>>>>>>>>>>>>>>>>>>>>");
                cmdlet.WriteError(
                    cmdlet,
                    "Nothing was recorded",
                    "NoRecords",
                    ErrorCategory.InvalidData,
                    false);
            }

            Console.WriteLine("FINISHED!!!!!!!!");
        }
Ejemplo n.º 54
0
 private void closeFile()
 {
     sw.Close();
     fileStream.Close();
 }
Ejemplo n.º 55
0
        public void Execute(ScriptContext context /*, System.Windows.Window window*/)
        {
            PlanSetup    plan = context.PlanSetup;
            StructureSet ss   = context.StructureSet;

            if (plan == null)
            {
                MessageBox.Show("Load a plan!");
                return;
            }
            if (plan.IsDoseValid == false)
            {
                MessageBox.Show("plan has no dose calculated!");
                return;
            }
            //User places point called "TopLeft" in top left corner where scan will start before running script
            Structure refMarker = (from s in ss.Structures
                                   where
                                   s.Id == "TopLeft"
                                   select s).FirstOrDefault();

            if (refMarker == null)
            {
                MessageBox.Show("No marker point called TopLeft found.");
                return;
            }
            VVector topLeft = refMarker.CenterPoint;

            //User places point called "BottomRight" in bottom right corner where scan will stop before running script
            Structure refMarker2 = (from s in ss.Structures
                                    where
                                    s.Id == "BottomRight"
                                    select s).FirstOrDefault();

            if (refMarker == null)
            {
                MessageBox.Show("No marker point called BottomRight found.");
                return;
            }
            VVector bottomRight = refMarker2.CenterPoint;
            VVector topRight    = new VVector(bottomRight.x, topLeft.y, topLeft.z);
            VVector bottomLeft  = new VVector(topLeft.x, topLeft.y, bottomRight.z);

            int column = 255; // arbitrarily make 255x255 (since that's what Excel can handle)
            int row    = 255;

            double[] buffer = new double[column];

            double xDist    = (VVector.Distance(topLeft, topRight)) / (double)column;
            string filename = string.Format(@"c:\temp\doseplane.csv");

            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(filename, false, Encoding.ASCII))
            {
                sw.Write("Y[cm]...X[cm],");
                for (int i = 0; i < column; i++)
                {
                    sw.Write("{0},", MMtoCM(Math.Round(topLeft.x + (xDist * i), 3)));
                }
                sw.WriteLine("");
                double zDist = (VVector.Distance(topLeft, bottomLeft)) / (double)row;
                for (int j = 0; j < row; j++)
                {
                    // figure out new start and stop points for the row we are scanning, then get the dose profile (scan it)
                    double  newZ        = topLeft.z - (zDist * j);
                    VVector newRowStart = topLeft;
                    VVector newRowEnd   = topRight;
                    newRowStart.z = newZ;
                    newRowEnd.z   = newZ;
                    // scan the row
                    DoseProfile dp = plan.Dose.GetDoseProfile(newRowStart, newRowEnd, buffer);

                    sw.Write("{0},", MMtoCM(Math.Round(newZ, 3)));
                    foreach (var profilePt in dp)
                    {
                        sw.Write("{0},", Math.Round(profilePt.Value, 6));
                    }
                    sw.WriteLine("");
                }

                sw.Flush();
                sw.Close();

                MessageBox.Show(string.Format(@"File written to '{0}'", filename), "Varian Developer");
            }
            // 'Start' generated CSV file to launch Excel window
            System.Diagnostics.Process.Start(filename);
            // Sleep for a few seconds to let Excel to start
            System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2));
        }
Ejemplo n.º 56
0
 private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
 {
     System.IO.StreamWriter objWriter = new System.IO.StreamWriter(saveFileDialog1.FileName);
     objWriter.WriteLine(textBox1.Text);
     objWriter.Close();
 }
Ejemplo n.º 57
0
        /// <summary>
        /// Refresh preview (if needed). Dependends on current environment and changed ETag.
        /// The preview is valid for remote and local view.
        /// First call will always lead to preview.
        ///
        /// /Files/LocalPreview/Server/Path-To-File/file.preview.ext
        /// /Files/LocalPreview/Server/Path-To-File/file.etag
        /// </summary>
        /// <param name="file"></param>
        public void RefreshPreview(File file)
        {
            _file = file;
            bool   createEtag = false;
            string path       = "Files/LocalPreview/" + _info.Hostname + "/" + _file.FilePath + ".etag";
            var    isf        = App.DataContext.Storage;

            {
                if (isf.FileExists(path))
                {
                    var reader = new System.IO.StreamReader(isf.OpenFile(path, System.IO.FileMode.Open));
                    if (reader.ReadToEnd() == _file.ETag)
                    {
                        reader.Close();
                        return;
                    }
                    reader.Close();
                }
                else
                {
                    createEtag = true;
                }
            }

            // create main type
            if (_enabled)
            {
                switch (_file.FileType.Split('/').First())
                {
                case "text":
                    TextPreview();
                    break;

                case "image":
                    ImagePreview();
                    break;

                case "application":
                    // try PDF content fetch
                    TextContentPreview();
                    break;

                default:
                    PreviewIcon(file.IsDirectory);
                    break;
                }
            }
            else
            {
                PreviewIcon();
                createEtag = false;
            }

            if (createEtag)
            {
                var storagePath = System.IO.Path.GetDirectoryName(path);
                if (!isf.DirectoryExists(storagePath))
                {
                    isf.CreateDirectory(storagePath);
                }
                var stream = isf.CreateFile(path);
                System.IO.StreamWriter writer = new System.IO.StreamWriter(stream);
                writer.Write(_file.ETag);
                writer.Close();
            }
        }
Ejemplo n.º 58
0
        public void myReader()
        {
            TcpClient client = new TcpClient();
            //     client.ExclusiveAdmyReaderdressUse = true;
            var result = client.BeginConnect(ip, port, null, null);
            var sucess = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));

            while (true)
            {
                if (!sucess)
                {
                    Console.WriteLine("Failed to connect");
                    Thread.Sleep(1000);
                }
                else
                {
                    try
                    {
                        byte[] bytesFrom = new byte[1000];

                        if (client.Connected)
                        {
                            var stream = client.GetStream();
                            stream.Read(bytesFrom, 0, 1000);
                            string readData = Encoding.ASCII.GetString(bytesFrom);



                            System.IO.StreamWriter file = new System.IO.StreamWriter(@"D:\\Barcode\BarcodeReader.txt", false);
                            //  Console.WriteLine("barcode" + barcode);

                            file.WriteLine(readData);
                            file.Close();
                        }

                        else
                        {
                            client = null;
                            client = new TcpClient();
                            client.ExclusiveAddressUse = true;
                            result = client.BeginConnect(ip, port, null, null);
                            sucess = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));

                            Thread.Sleep(1000);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        client = null;
                        client = new TcpClient();
                        client.ExclusiveAddressUse = true;
                        result = client.BeginConnect(ip, port, null, null);
                        sucess = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));

                        Thread.Sleep(1000);
                    }
                }
                sucess = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));
            }
        }
Ejemplo n.º 59
0
        private bool CreateEntity(string nameSpace, string tableName)
        {
            bool retval = false;

            try {
                string className = tableName.Replace(" ", string.Empty) + "Entity";
                System.Collections.ArrayList columns = new System.Collections.ArrayList();

                if (!System.IO.Directory.Exists(this.path + @"\Common\Entities"))
                {
                    System.IO.Directory.CreateDirectory(this.path + @"\Common\Entities");
                }
                System.IO.StreamWriter writer = new System.IO.StreamWriter(this.path + @"\Common\Entities\" + className + ".cs");
                StringBuilder          sb     = new StringBuilder();

                sb.AppendLine("using System;");
                sb.AppendLine("using System.Collections.Generic;");
                sb.AppendLine("using System.Text;");
                sb.AppendLine("");
                sb.Append("namespace ");
                sb.Append(nameSpace);
                sb.Append(".Common.Entities");
                sb.AppendLine(" {");
                sb.Append("public class ");
                sb.Append(className);
                sb.AppendLine(" {");

                //get columns
                using (SqlConnection cnn = new SqlConnection(this.connectionString)) {
                    cnn.Open();
                    SqlCommand cmd = new SqlCommand("select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@tableName", cnn);
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add(new SqlParameter("@tableName", tableName));
                    SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    while (reader.Read())
                    {
                        string columnName = reader["COLUMN_NAME"].ToString();
                        string dataType   = reader["DATA_TYPE"].ToString();
                        string type       = string.Empty;

                        Column col = new Column();
                        col.Name     = columnName;
                        col.DataType = dataType;
                        columns.Add(col);

                        switch (dataType)
                        {
                        case "uniqueidentifier":
                            type = "Guid";
                            break;

                        case "nvarchar":
                            type = "string";
                            break;

                        case "varchar":
                            type = "string";
                            break;

                        case "text":
                            type = "string";
                            break;

                        case "float":
                            type = "double";
                            break;

                        case "int":
                            type = "int";
                            break;

                        case "bigint":
                            type = "long";
                            break;

                        case "bit":
                            type = "bool";
                            break;

                        case "datetime":
                            type = "DateTime";
                            break;
                        }

                        //public properties
                        sb.Append("public ");
                        sb.Append(type);
                        sb.Append(" ");
                        sb.Append(columnName);
                        sb.AppendLine(" {");
                        sb.Append("get;");
                        sb.Append("set;");
                        sb.AppendLine("}");
                    }
                }

                //new entity method
                //public static ClassEntity NewClassEntity() {
                //    ClassEntity entity = new ClassEntity();
                //    entity.ClassKey = Guid.NewGuid();
                //    entity.Title = string.Empty;
                //    entity.Description = string.Empty;
                //    entity.CreatedDate = DateTime.Now;
                //    entity.UpdatedDate = DateTime.Now;
                //    return entity;
                //}
                sb.Append("public static ");
                sb.Append(className);
                sb.Append(" New");
                sb.Append(className);
                sb.AppendLine("() {");
                sb.Append(className);
                sb.Append(" entity = new ");
                sb.Append(className);
                sb.AppendLine("();");
                foreach (object ocol in columns)
                {
                    Column col = (Column)ocol;
                    switch (col.DataType)
                    {
                    case "uniqueidentifier":
                        sb.Append("entity.");
                        sb.Append(col.Name);
                        sb.Append(" = ");
                        sb.AppendLine("Guid.NewGuid();");
                        break;

                    case "nvarchar":
                        sb.Append("entity.");
                        sb.Append(col.Name);
                        sb.Append(" = ");
                        sb.AppendLine("string.Empty;");
                        break;

                    case "varchar":
                        sb.Append("entity.");
                        sb.Append(col.Name);
                        sb.Append(" = ");
                        sb.AppendLine("string.Empty;");
                        break;

                    case "text":
                        sb.Append("entity.");
                        sb.Append(col.Name);
                        sb.Append(" = ");
                        sb.AppendLine("string.Empty;");
                        break;

                    case "datetime":
                        sb.Append("entity.");
                        sb.Append(col.Name);
                        sb.Append(" = ");
                        sb.AppendLine("DateTime.Now;");
                        break;
                    }
                }
                sb.AppendLine("return entity;");
                sb.AppendLine("}");

                // merge method
                sb.Append("public void Merge(");
                sb.Append(className);
                sb.AppendLine(" obj) {");

                foreach (object ocol in columns)
                {
                    Column col = (Column)ocol;
                    switch (col.DataType)
                    {
                    case "uniqueidentifier":
                        sb.AppendLine("if (obj." + col.Name + " != Guid.Empty) { this." + col.Name + " = obj." + col.Name + "; }");
                        break;

                    case "nvarchar":
                    case "varchar":
                    case "text":
                        sb.AppendLine("if (!string.IsNullOrEmpty(obj." + col.Name + ")) { this." + col.Name + " = obj." + col.Name + "; }");
                        break;

                    case "datetime":
                        sb.AppendLine("if (obj." + col.Name + " > DateTime.MinValue) { this." + col.Name + " = obj." + col.Name + "; }");
                        break;

                    case "int":
                    case "bigint":
                    case "decimal":
                        sb.AppendLine("if (obj." + col.Name + " > 0) { this." + col.Name + " = obj." + col.Name + "; }");
                        break;
                    }
                }

/*
 *              public void Merge(InvoicesEntity obj) {
 *                  if (obj.InvoiceKey != Guid.Empty) { this.InvoiceKey = obj.InvoiceKey; }
 *              }
 */
                sb.AppendLine("}");

                sb.AppendLine("}");
                sb.AppendLine("}");

                writer.WriteLine(sb.ToString());
                writer.Close();
                retval = true;
            }
            catch (Exception ex) {
                throw ex;
            }
            return(retval);
        }
Ejemplo n.º 60
0
 public static void WriteToFile(string path, string Text)
 {
     System.IO.StreamWriter oStreamWriter = new System.IO.StreamWriter(path);
     oStreamWriter.Write(Text);
     oStreamWriter.Close();
 }