public ConfigChecker(Project p)
        {
            Logger.Log("Inizializzazione dello strumento di verifica...");
            channelMap = new Dictionary<string, Canale>();
            fluxes = new List<Foglia>();
            variables = new Dictionary<string, Variable>();
            List<Variable> ls = new List<Variable>();
            p.VarTree.getVariables(ls, true);
            foreach (Variable v in ls)
                variables.Add(v.Path, v);
            p.VarTree.getLeaves(fluxes, true);
            List<Foglia> lst = new List<Foglia>();
            p.ComTree.getLeaves(lst, true);
            foreach (Foglia f in lst)
            {
                try {
                    if (f.Enabled)
                        channelMap.Add(f.Name, (Canale)f);
                }
                catch (Exception e)
                {
                    Logger.Log("Errore: sono presenti due canali con lo stesso nome: " + f.Name,"Red");
                }
            }         
            //if (p.Properties["Ridondanza Enabled"].ToLower()=="true")
            //{
            //    mergeDirectory(p.Properties["MasterSharedFolder"], p.Properties["BackupSharedFolder"], "");
            //}

        }
 private static void writeStationFile(string dir, Project p, int stNumber)
 {
     string fileName = Path.Combine(dir, ProjectDefinitions.Map["a"].DefaultValue);
     string content = "[Main]\nStationNumber=";
     StreamWriter sw = null;
     try
     {
         sw = new StreamWriter(Path.Combine(dir, "Station.cfg"));
         sw.Write(content + stNumber);
         sw.Close();
     }
     catch (Exception e) {
         throw new FileManagerException("Error writing file " + fileName, e);
     }
     finally { if (sw != null) sw.Close(); }
 }
        public static void save(string file, Project progetto)
        {
            XmlSerializer xSer;
            StreamWriter sw = null;
            string zipfilename = Path.GetFileNameWithoutExtension(file) + ".zip";
            string xmlfilename= Path.GetFileNameWithoutExtension(file) + DateTime.Now.ToString("yyyyMMddHHmmssfff")+".xml";
            try
            {
                if (File.Exists(xmlfilename))
                    deleteFile(xmlfilename);
                if (File.Exists(file))
                    deleteFile(file);
                List<Type> tlist = new List<Type>();
                tlist.Add(typeof(Nodo));
                tlist.Add(typeof(VarNodo));
                tlist.Add(typeof(ComNodo));
                tlist.Add(typeof(Report61850Nodo));
                tlist.Add(typeof(Report61850));
                tlist.Add(typeof(Foglia));
                tlist.Add(typeof(Canale));
                tlist.Add(typeof(Variable));
                tlist.Add(typeof(Flusso));
                tlist.Add(typeof(PropertyItem));
                xSer = new XmlSerializer(typeof(Project));
                sw = new StreamWriter(xmlfilename);
                xSer.Serialize(sw, progetto);
                sw.Close();
                sw = null;
                zipFile(new string[] { xmlfilename },zipfilename);
                File.Move(zipfilename, file);
                deleteFile(xmlfilename);                
            }
            catch (Exception e)
            {
                throw new FileManagerException("Error saving file " + file + ":" + e.Message, e);
            }
            finally
            {
                if (sw != null) sw.Close();
            }

        }
 public static void writeScript(Project p, string dir=".\\Config")
 {
     string fileName = Path.Combine(dir, "user_logics.php");
     StreamWriter sw = null;            
     try
     {
         sw = new StreamWriter(fileName);
         string script = p.Properties["Script"];
         byte[] ansiscriptbytes = Encoding.Convert(Encoding.UTF8, Encoding.Default, Encoding.UTF8.GetBytes(script));
         string ansiscript = Encoding.Default.GetString(ansiscriptbytes);
         sw.Write(ansiscript);
     }
     catch (Exception e)
     {
         throw new FileManagerException("Error writing file " + fileName, e);
     }
     finally
     {
         if (sw != null) sw.Close();
     }
 }
        private static void writeProjectConfFile(Project p,string dir=".\\Config")
        {
            string fileName = Path.Combine(dir, ProjectDefinitions.Map["a"].DefaultValue);
            StreamWriter sw = null;
            Logger.Log("Scrittura file "+ ProjectDefinitions.Map["a"].DefaultValue+"...");
            try
            {
                sw = new StreamWriter(fileName);
                foreach (var group in ProjectDefinitions.Groups)
                {
                    sw.WriteLine("[" + group.Key + "]");
                    foreach (var pr in p.propertylist)
                    {
                        if (String.IsNullOrWhiteSpace(pr.Value)) continue;
                        proprietaType pt = group.Value.FirstOrDefault(x => x.NomeVisualizzato == pr.Name);
                        if (pt==null)
                            continue;
                        //proprietaType pdef = ProjectDefinitions.Map[pr.Name];
                        if (pt.NomeEsportazioneGPM.ToLower() == "false") continue;
                        sw.WriteLine(pt.NomeEsportazioneGPM + "=" + pr.Value);
                    }
                }
                sw.WriteLine("[Scheduler]");
                sw.WriteLine("LogLevel=1");
                sw.WriteLine("Enabled=true");
                sw.WriteLine("RequiredVesion=1.0.0.0");

            }
            catch (Exception e)
            {
                throw new FileManagerException("Error writing file " + fileName, e);
            }
            finally
            {
                if (sw != null) sw.Close();
            }
        }
        private static void writeReports61850File(Project p, string dir)
        {
            if (p.Rep61850Tree.Children.Count == 0) return;
            Protocol definitions = VarDefinitions.Map["Reports61850"];
            string fileName = Path.Combine(dir, definitions["a"].DefaultValue);
            StreamWriter sw = null;
            List<Foglia> nodidascrivere = new List<Foglia>();
            string valueString;
            p.Rep61850Tree.getLeaves(nodidascrivere, true);
            Logger.Log("Scrittura file " + definitions["a"].DefaultValue + "...");
            try
            {
                sw = new StreamWriter(fileName);
                foreach (Report61850 f in nodidascrivere)
                {
                    sw.WriteLine("[" + f.Path + "]");
                    sw.WriteLine("Description=" + f.Name);
                    sw.WriteLine("GM.Address=NULL");
                    foreach (proprietaType defProp in definitions.Values)
                    {
                        if (defProp.NomeEsportazioneGPM == "false") continue;
                        if (defProp.name.ToLower() == "namenodo")
                            valueString = f.Name;
                        else if (defProp.name.ToLower() == "mastername")
                            valueString = f.Father.Name;
                        else
                            valueString = f[defProp.NomeVisualizzato];
                        if (String.IsNullOrWhiteSpace(valueString)) continue;
                        sw.WriteLine(defProp.NomeEsportazioneGPM + "=" + valueString);
                    }
                    sw.WriteLine("");
                }
            }
            catch (Exception e)
            {
                throw new FileManagerException("Error writing file " + fileName, e);
            }
            finally
            {
                if (sw != null) sw.Close();
            }

        }
 public static void generateConf(Project p,string dir=".\\Config")     //si può farne la versione multithreaded 
 {
     Logger.Log("Inizio esportazione...");
     string[] filestodelete = Directory.GetFiles(dir);
     foreach (string file in filestodelete) {
         if (Path.GetFileName(file).ToLower() == "user_logics.php") continue;
         deleteFile(file);                    
     }
     Logger.Log("Scrittura file user_logics.php...");
     writeScript(p, dir);
     writeProjectConfFile(p,dir);
     VarDefinitions vardefs = VarDefinitions.Map;
     List<Foglia> flussi = new List<Foglia>();
     p.VarTree.getLeaves(flussi,true);
     foreach (var vp in vardefs)
     {
         List<Foglia> nodidascrivere = flussi.FindAll(x => x.ProtocolName == vp.Key);
         if (nodidascrivere.Count != 0)
         {
             writeVarConfFile(dir, nodidascrivere, vp);
             if (vp.Key== "IEC 61850")
             {
                 writeReports61850File(p, dir);
             }
         }
     }
     flussi.Clear();
     List<Foglia> canali = new List<Foglia>();
     p.ComTree.getLeaves(canali,true);
     ComDefinitions comdefs = ComDefinitions.getDefinitions();
     foreach (var cd in comdefs)
     {
         List<Foglia> candascrivere = canali.FindAll(x => x.ProtocolName == cd.Key);
         if (candascrivere.Count != 0)
         {
             writeComConfFile(dir, candascrivere, cd);
         }
     }
     writeStationFile(dir, p, 1);
     if (p.Properties.ContainsKey("Ridondanza Enabled") && bool.Parse(p.Properties["Ridondanza Enabled"])){
         string destfolder = p.Properties["BackupSharedFolder"]+"\\Config";
         copyDir(dir,destfolder,true);
         writeStationFile(destfolder, p, 2);
     }
 }
 private static void loadOldScriptFile(Project p, string scriptFile)
 {
     StreamReader sr = null;
     try
     {
         sr = new StreamReader(scriptFile);
         p.Properties["Script"] = sr.ReadToEnd();
     }
     catch (Exception e)
     {
         throw new FileManagerException("Error reading old script file: " + e.Message + " "+e.StackTrace);
     }
     finally
     {
         sr.Close();
     }
 }
        private static Project loadOldProjectFile(string file)
        {
            Project p = new Project(false);
            Logger.Log("Unzipping file " + file + "...");
            unzipFile(file);
            string projectFile;// = Path.GetDirectoryName(file) + "\\Temp\\" + Path.GetFileName(file);
            string directory = Path.GetDirectoryName(file);
            string[] files = Directory.GetFiles(Path.Combine (directory,"Temp"),"*.gprj");
            string scriptFile = Path.Combine(directory, "Temp\\user_logics.php");            
            projectFile = files[0];     
            StreamReader sr = null;
            int lineCounter = 0;
            try
            {
                sr = new StreamReader(projectFile);
                string line, section1, propValue, propName, path, prevPath = "";
                bool first = true;
                bool firstcom = true;
                bool firstOth = true;
                string[] lineFields, pathFields;
                Dictionary<string, string> nodeProps = new Dictionary<string, string>();
                int pathLength;
                while (!sr.EndOfStream)
                {
                    line = sr.ReadLine();
                    if (line.Length < 1) continue;
                    lineFields = line.Split(new string[] { "###" }, StringSplitOptions.None);
                    section1 = lineFields[0];
                    path = getPathString(section1);
                    propValue = lineFields[1];
                    pathFields = section1.Split(';');
                    pathLength = pathFields.Length;
                    propName = pathFields[pathLength - 1];
                    switch (pathFields[0])
                    {
                        case "Progetto":
                            if (propName.ToLower() == "false") continue;
                            if (!nodeProps.ContainsKey(propName))
                                nodeProps.Add(propName, propValue);
                            else
                                Logger.Log("Attenzione! Chiave " + propName + "ripetuta per il nodo " + path);
                            break;
                        case "Memoria Globale":
                            if (first)
                            {
                                p.addPropertiesGPRJ(nodeProps);
                                nodeProps.Clear();
                                prevPath = path;
                                first = false;
                            }
                            if (path == prevPath)
                            {
                                if (!nodeProps.ContainsKey(propName) && !Regex.IsMatch(propName, "false|true", RegexOptions.IgnoreCase) && !String.IsNullOrWhiteSpace(propValue))
                                    nodeProps.Add(propName, propValue);
                            }
                            else
                            {
                                p.VarTree.addVarNodeGPRJ(prevPath, nodeProps);
                                nodeProps.Clear();
                                nodeProps.Add(propName, propValue);
                            }
                            prevPath = path;
                            break;
                        case "Comunicazione":

                            if (firstcom)
                            {
                                p.VarTree.addVarNodeGPRJ(prevPath, nodeProps);
                                prevPath = path;
                                nodeProps.Clear();
                                firstcom = false;
                            }
                            if (path == prevPath)
                            {
                                if (!nodeProps.ContainsKey(propName) && !Regex.IsMatch(propName, "false|true", RegexOptions.IgnoreCase) && !String.IsNullOrWhiteSpace(propValue))
                                    nodeProps.Add(propName, propValue);
                            }
                            else
                            {
                                p.ComTree.addComNodeGPRJ(prevPath, nodeProps);
                                nodeProps.Clear();
                                nodeProps.Add(propName, propValue);
                            }
                            prevPath = path;
                            break;
                        case "Altro":
                            if (firstOth)
                            {
                                if (pathFields[1] == "User") continue;
                                p.ComTree.addComNodeGPRJ(prevPath, nodeProps);                               
                                prevPath = path;
                                nodeProps.Clear();
                                firstOth = false;
                            }
                            
                            if (path == prevPath)
                            {
                                if (!nodeProps.ContainsKey(propName) && !Regex.IsMatch(propName, "false|true", RegexOptions.IgnoreCase) && !String.IsNullOrWhiteSpace(propValue))
                                    nodeProps.Add(propName, propValue);
                            }
                            else
                            {
                                p.OtherTree.addReport61850NodeGPRJ(prevPath, nodeProps);
                                nodeProps.Clear();
                                nodeProps.Add(propName, propValue);
                            }
                            prevPath = path;
                            break;                            
                    }
                    lineCounter++;
                }
                sr.Close();
                loadOldScriptFile(p, scriptFile);

                FileManager.deleteDir(Path.GetDirectoryName(file) + "\\Temp");
            }
            catch (Exception e)
            {
                Logger.Log("Errore durante il caricamento del file " + file + " sulla linea: " + lineCounter + "-" + e.Message + " -" + e.StackTrace);
            }
            finally
            {
                if (sr != null) sr.Close();
            }
            return p;
        }
 private void mbar_nuovoprogetto_click(object sender, RoutedEventArgs e)
 {
     closeActualProject();
     albero.ItemsSource = "";
     progetti[0] = new Project(true);
     progetti[0].setDefaultPropertyList();
     albero.ItemsSource = progetti;
     albero.Resources["varProtocols"] = progetti[0].EnabledVarProtocols;
     albero.Resources["comProtocols"] = progetti[0].EnabledComProtocols;
 }