public ConnectionInfoEditor(ref ConnectionInfo con)
 {
     InitializeComponent();
     connection = con;
     if (con != null && con.address != null) {
         // get values from con and fill form
         serverTextBox.Text = con.address.Host;
         serverPort.Text = con.address.Port.ToString ();
         if (con.useProxy) {
             proxyCheckBox.Checked = true;
             proxyServerTextBox.Text = con.proxy.Host;
             proxyPortTextBox.Text = con.proxy.Port.ToString ();
         }
     } else {
         this.connection = con = new ConnectionInfo ();
         //fill with default values
         server = @"photo.weebox.keep.pt/";
         serverTextBox.Text = server;
         serverPort.Text = (80).ToString ();
         proxyCheckBox.Checked = false;
     }
 }
        public static void setup()
        {
            ConnectionInfo con = new ConnectionInfo(
                new Utilizador("g10_demo", "demo"),
                "http://photo.weebox.keep.pt/", "http://proxy.uminho.pt/");

            CoreAbstraction core = CoreAbstraction.getCore();

            WeeboxSync wee = new WeeboxSync();
            FicheiroSystemAbstraction abs = new FicheiroSystemAbstraction();
            DataBaseAbstraction ab = new DataBaseAbstraction();
            ab.deleteALl();
            if (Directory.Exists(@"c:\users\fabiim\my documents\my weebox")){
                abs.DeleteRecursiveFolder(@"c:\users\fabiim\my documents\my weebox");
            }
            wee.connection_info = con;
            wee.setDefaultRootFolder();
            Watcher w= new Watcher(ref wee, wee.getRootFolder() + "\\Bundles");
            wee.SetWatcher(ref w);
               w.Disable();
               while (true){
               try{
                   wee.setup();
                   while (true){
                       wee.SynchronizeAll();
                   }
               }
               catch (Exception e){
                   Console.Out.Write("Exception");
                   Console.Out.Write(e);
               }
               }
            try{
                wee.setup();

                while (true){
                    wee.SynchronizeAll();
                }
            }catch (Exception e){
                Console.Out.Write("Exception");
                Console.Out.Write(e);
                Console.Read();

            }
            /*            //wee.getBundleInfo("2BF883C16A5D8C2E827CD47A6EA19028");
            Ficheiro file = new Ficheiro(@"c:\asd.png", true);
            List<Ficheiro> files = new List<Ficheiro>(){ new Ficheiro(@"c:\asd.png", true), new Ficheiro(@"c:\drf.png", true) };
            wee.PutFicheiros("689421950C2542A0A7E09C76E40536C4", files);
            */
            //wee.RemoveFicheiros(
            //            wee.RemoveFicheiros("E37ADFC66E0ECB631998DFB13B34BB63",
            //                                new List<string>()
            //                                    {
                                    //    "1F8FEC6875461D0B5BA6EA7972486F8B",
            //                                        "66BF8E7E5DCAF1D96FEE3EA78D8549CD"
              //                                  });

            Console.ReadLine();
            //            wee.PutFicheiro("", new Ficheiro());

            //con.user
            //con.proxy.ToString();

            //            WeeboxSync weebox = new WeeboxSync();
            //          weebox.connection_info = con;
            //        weebox.setup();
            //            CoreAbstraction core = CoreAbstraction.getCore();
            //            core.SetConnection(con);

            //            core.PutFicheiro("", new Ficheiro());
        }
 /// <summary>
 /// Sets the connection information to contact the server. 
 /// </summary>
 /// <param name="con"> The connection information</param>
 public void SetConnection(ConnectionInfo con)
 {
     _conInfo = con;
     if (con.address != null) {
         _client = new HttpClient(con.address.ToString());
     }
     if (con.user != null) {
         _client.TransportSettings.Credentials = new NetworkCredential(con.user.user, con.user.pass);
     }
     if (con.useProxy && con.proxy != null) {
         _client.TransportSettings.Proxy = new WebProxy(con.proxy);
     }
     _client.TransportSettings.PreAuthenticate = true;
 }
        private static bool DoSetup()
        {
            ConnectionInfo ci = null;
            Weebox = new WeeboxSync();
            int state = 1;
            bool cont = true;
            FicheiroSystemAbstraction fsa = new FicheiroSystemAbstraction();
            WelcomeScreen ws = new WelcomeScreen ();
            ws.ShowDialog ();
            do {
                /**
                * if dialog results are DialogResult.Retry,
                * show the last form (back button was pressed)
                * if the result is Cancel, setup is to be canceled entirely
                * if the result is OK, follow to the next form, up until download.
                */

                DialogResult result;
                switch (state) {
                    case 1:
                        ci = new ConnectionInfo();
                        ConnectionInfoEditor cie = new ConnectionInfoEditor (ref ci);
                        result = cie.ShowDialog ();
                        if (result == DialogResult.Cancel)
                            return false;
                        if(result == DialogResult.Retry)
                            state = 0; // exit
                        else
                            state++;
                        break;
                    case 2:
                        if(ci == null) {
                            state = 0;
                            break;
                        }
                        Weebox.connection_info = ci;
                        LoginWindow lw = new LoginWindow ( ref Weebox);
                        result = lw.ShowDialog ();
                        if (result == DialogResult.Cancel)
                            return false;
                        if(result == DialogResult.Retry)
                            state--; // back to previous dialog
                        else
                            state++; // next dialog
                        break;
                    case 3:
                        FolderChooser fc = new FolderChooser (ref Weebox);
                        result = fc.ShowDialog ();
                        if (result == DialogResult.Cancel)
                            return false;
                        if (result == DialogResult.Retry)
                            state--; // back to previous dialog
                        else
                            state++; // next dialog
                        break;
                    case 4:
                        //setup successful, go to download
                        SaveRegistryKeys ();
                        DataBaseAbstraction dba = new DataBaseAbstraction ();
                        try
                        {
                            dba.SaveConnectionInfo(Weebox.connection_info);
                        }
                        catch (Exception e) {
                            //eliminar chaves de registo
                            DeleteRegistryKeys();
                            //eliminar pasta root
                            fsa.DeleteRecursiveFolder(Weebox.getRootFolder());
                            MessageBox.Show(
                                "Setup falhou. Por favor inicie novamente a aplicação, verifique os dados inseridos e tente novamente",
                                "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return false;
                        }
                        DownloadWait dw = new DownloadWait (ref Weebox);
                        var res = dw.ShowDialog ();
                        if(res == DialogResult.Cancel) {
                            //eliminar chaves de registo
                            DeleteRegistryKeys();
                            //eliminar pasta root
                            fsa.DeleteRecursiveFolder(Weebox.getRootFolder());
                            MessageBox.Show(
                                "Setup falhou. Por favor inicie novamente a aplicação, verifique os dados inseridos e tente novamente",
                                "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return false;
                        }
                        else if (res == DialogResult.OK) {
                            MessageBox.Show ("O setup foi concluído com sucesso.\nBem-vindo ao mundo Weebox.", "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        cont = false;
                        break;

                    case 5:
                        // all tasks done, exit

                        return true;
                    case 0:
                        //Cancel setup and exit application
                        Application.Exit ();
                        return false;
                    default:
                        MessageBox.Show (
                            "Houve um erro no processo de instalação.\n" +
                            "Por favor volte a iniciar a aplicação para concluir o processo,",
                            "Erro",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                        //eliminar chaves de registo
                        DeleteRegistryKeys();
                        //eliminar pasta root
                        fsa.DeleteRecursiveFolder(Weebox.getRootFolder());
                        Application.Exit();
                        break;
                }
            } while (cont);
            //MessageBox.Show ("Setup done!, Now we rock!");
            return true;
        }
 private void SetConnectionInfo(object sender, EventArgs eventArgs)
 {
     ConnectionInfo ci = new ConnectionInfo();
     ConnectionInfoEditor cie = new ConnectionInfoEditor(ref ci);
     var dialogRes = cie.ShowDialog();
     if (dialogRes == DialogResult.OK) { //not canceled
         var res = weebox.setConnectionInfo (ci.address, ci.proxy, ci.useProxy);
         if (!res)
         {
             MessageBox.Show("Sincronização em curso, por favor aguarde alguns minutos e tente novamente.",
                              "Erro",
                              MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
 }
        /**
            * stores the connection information associated with this weebox instance
         * ::Checked::
            */
        public void SaveConnectionInfo(ConnectionInfo conI)
        {
            if (conI == null || conI.user == null || conI.address == null)
                return;

            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            //check if data is set
            bool set;
            SqlCommand query = new SqlCommand(string.Format("select * from utilizador where username = '******'", conI.user.user), con);
            SqlDataReader reader = query.ExecuteReader();
            set = reader.Read();
            reader.Close();
            //insert or update values
            string proxy;
            proxy = conI.proxy != null ? conI.proxy.ToString() : string.Empty;

            string[] par = { conI.user.user, conI.user.pass, conI.address.ToString (), proxy,
                             conI.useProxy.ToString (), conI.serial_generator.ToString()};
            if (set) {
                //operation : update
                query = new SqlCommand(string.Format(
                    "update utilizador set " +
                    "username='******',password='******', server='{2}', proxy='{3}', useProxy='{4}', serial_generator ='{5}'", par), con);
            }
            else {
                //operation : insert
                query = new SqlCommand(string.Format(
                    "insert into utilizador (username, password, server, proxy, useProxy, serial_generator) " +
                    "values ( '{0}', '{1}', '{2}', '{3}', '{4}', '{5}')", par), con);
            }
            query.ExecuteNonQuery();
            con.Close();
        }
        /**
            * retrieves the connection information associated with this weebox instance
         * ::Checked::
            */
        public ConnectionInfo GetConnectionInfo(String username)
        {
            if (string.IsNullOrEmpty(username))
                return null;
            ConnectionInfo conInfo = null;

            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            SqlCommand query = new SqlCommand(string.Format(
                "SELECT username, password, server, proxy, serial_generator FROM utilizador WHERE username = '******'", username), con);
            SqlDataReader reader = query.ExecuteReader();
            if (reader.Read()) { //only the first occurrence
                Utilizador user = new Utilizador(reader.GetString(0), reader.GetString(1));
                string server = reader.GetString(2);
                string proxy = reader.GetString(3);
                if (!(string.IsNullOrEmpty(proxy) || proxy.Equals("null"))) {
                    //there is a proxy to save
                    conInfo = new ConnectionInfo(user, server, proxy);
                }
                else {
                    //no proxy
                    conInfo = new ConnectionInfo(user, server);
                }
                int defaultInt = reader.GetInt32 (4);
                conInfo.serial_generator = defaultInt;
            }
            reader.Close();
            con.Close();
            return conInfo;
        }