コード例 #1
0
ファイル: ISaveable.cs プロジェクト: NicTda/MAGTask
        /// @param savable
        ///     The savable to deserialize from file
        ///
        /// @return Whether the data was successfully loaded
        ///
        public static void Load(this ISavable savable)
        {
            var    jsonData = new Dictionary <string, object>();
            string filePath = string.Format(k_filePathFormat, savable.GetType().ToString());

            if (FileSystem.DoesFileExist(filePath, FileSystem.Location.Persistent))
            {
                jsonData = JsonWrapper.ParseJsonFile(filePath, FileSystem.Location.Persistent);
                if (jsonData == null)
                {
                    // Delete the corrupted file
                    FileSystem.DeleteFile(filePath, FileSystem.Location.Persistent);

                    // Load a backup
                    string backup = string.Format(k_filePathBackupFormat, savable.GetType().ToString());
                    jsonData = JsonWrapper.ParseJsonFile(backup, FileSystem.Location.Persistent);
                }
            }
            else if (FileSystem.DoesFileExist(filePath, FileSystem.Location.Cache))
            {
                // Legacy file in cache
                jsonData = JsonWrapper.ParseJsonFile(filePath, FileSystem.Location.Cache);
            }
            savable.Deserialize(jsonData);
        }
コード例 #2
0
ファイル: ConfigFile.cs プロジェクト: NickHola/Backupper
        //Friend Function DammiConfig(ByRef config As Configs.Base, distinguiUtente As Boolean, descErr As String, Optional tipoLogErr As Tipi = Tipi._Nothing) As Boolean
        internal bool GetConfig(ref ISavable config, bool markUser, Mess logMess)
        {
            IEnumerable <ConfigurazioneSuFile> configFiltrate;

            string name, parent;
            Type   type;

            name   = config.SavableName;
            parent = config.SavableParentName;
            type   = config.GetType();

            configFiltrate = from tmp in configurations where tmp.config.SavableName == name && tmp.config.SavableParentName == parent && tmp.type == type select tmp;

            if (markUser == true)
            {
                configFiltrate = from tmp in configFiltrate where tmp.userId == App.CurrentUserId select tmp;
            }

            if (configFiltrate.Count() == 0)
            {
                logMess.testoDaLoggare = "nel file di configurazione:<" + fullFilePath + ">, non ho trovato impostazioni con " + logMess.testoDaLoggare;
                Log.main.Add(logMess);
                return(false);
            }
            else if (configFiltrate.Count() > 1)
            {
                logMess.testoDaLoggare = "nel file di configurazione:<" + fullFilePath + ">, ho trovato più di una impostazione con " + logMess.testoDaLoggare + ", sarà preso il primo valore";
                Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, logMess.testoDaLoggare)); //In questo caso deve essere sempre errore per questo ho utilizzato un nuovo mess
            }

            config = configFiltrate.ElementAt(0).config;
            return(true);
        }
コード例 #3
0
ファイル: ConfigFile.cs プロジェクト: NickHola/Backupper
        internal bool SaveConfig(ISavable config, bool markUser, string descErr)
        {
            IEnumerable <ConfigurazioneSuFile> selectedConfig; UInt64 userId;

            //Check if config already exists
            selectedConfig = from tmp in configurations where tmp.config.SavableName == config.SavableName && tmp.config.SavableParentName == config.SavableParentName && tmp.type == config.GetType() select tmp;

            userId = markUser == true ? App.CurrentUserId : 0;

            selectedConfig = from tmp in selectedConfig where tmp.userId == userId select tmp;

            if (selectedConfig.Count() == 0)
            { //Creazione di una nuova
                ConfigurazioneSuFile configurazione = new ConfigurazioneSuFile();
                configurazione.type   = config.GetType();
                configurazione.userId = userId;
                configurazione.config = config;
                configurations.Add(configurazione);
            }
            else if (selectedConfig.Count() == 1)
            { //Aggiornamento della config esistente
                selectedConfig.ElementAt(0).config = config;
            }
            else
            {
                Log.main.Add(new Mess(LogType.Warn, Log.main.warnUserText, "nel file di configurazione:<" + fullFilePath + ">, ho trovato più di una impostazione con " + descErr + ", l'impostazione non sarà salvata"));
                return(false);
            }
            return(true);
        }
コード例 #4
0
ファイル: ISaveable.cs プロジェクト: NicTda/MAGTask
        /// @param savable
        ///     The savable to serialize to file
        ///
        public static void Save(this ISavable savable)
        {
            string filePath = string.Format(k_filePathFormat, savable.GetType().ToString());

            if (FileSystem.DoesFileExist(filePath, FileSystem.Location.Persistent))
            {
                // Create a backup automatically
                string backup = string.Format(k_filePathBackupFormat, savable.GetType().ToString());
                FileSystem.CopyFile(filePath, backup, FileSystem.Location.Persistent);
            }

            // Queue the save
            var saveData = (Dictionary <string, object>)savable.Serialize();

            GlobalDirector.Service <SaveService>().AddSaveJob(filePath, saveData);
        }
コード例 #5
0
    public static string SaveObj(ISavable obj)
    {
        Debug.Log(obj);
        FieldInfo[] prop = obj.GetType().GetFields();
        Array.Sort(prop, delegate(FieldInfo x, FieldInfo y) { return(x.Name.CompareTo(y.Name)); });

        List <string> comps = new List <string>();

        comps.Add(obj.getPrefab());
        string STransform = JsonUtility.ToJson(new STransform(((Component)obj).gameObject.transform));

        comps.Add(STransform);

        foreach (FieldInfo p in prop)
        {
            //Debug.Log(p);
            if (null != p && !p.IsNotSerialized)
            {
                Debug.Log(p);
                Type   pType = p.FieldType;
                object pVal  = p.GetValue(obj);
                pVal = Convert.ChangeType(pVal, pType);
                //Debug.Log(pVal);
                comps.Add(JsonUtility.ToJson(pVal));
            }
        }

        ListContainer <string> compsContainer = new ListContainer <string>();

        compsContainer.lis = comps;
        string retval = JsonUtility.ToJson(compsContainer);

        return(retval);
    }
コード例 #6
0
    public static void LoadObj(GameObject inst, string objStr)
    {
        ISavable      toLoad   = inst.GetComponent <ISavable>();
        List <string> Objcomps = JsonUtility.FromJson <ListContainer <string> >(objStr).lis;

        Objcomps.RemoveAt(0);

        STransform temp = JsonUtility.FromJson <STransform>((string)Objcomps[0]);

        inst.transform.position   = temp.position;
        inst.transform.rotation   = temp.rotation;
        inst.transform.localScale = temp.scale;
        Objcomps.RemoveAt(0);



        FieldInfo[] prop = toLoad.GetType().GetFields();
        Array.Sort(prop, delegate(FieldInfo x, FieldInfo y) { return(x.Name.CompareTo(y.Name)); });


        foreach (FieldInfo p in prop)
        {
            Debug.Log(p);
            if (null != p && !p.IsNotSerialized)
            {
                Type pType = p.FieldType;

                object pVal = Activator.CreateInstance(pType);
                pVal = Convert.ChangeType(pVal, pType);
                Debug.Log(Objcomps[0]);
                JsonUtility.FromJsonOverwrite(Objcomps[0], pVal);

                p.SetValue(toLoad, pVal);
                Objcomps.RemoveAt(0);
            }
        }
    }
コード例 #7
0
        public DbCommand[] GetUpdate2Commands(ISavable obj, UpdateCriteria criteria, bool doSelectBack)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }
            if (obj.GetType() != _dataObjectType)
            {
                throw new ArgumentException("Type of 'obj' does not match type from constructor.");
            }

            if (criteria == UpdateCriteria.AllFields)
            {
                throw new ArgumentException("UpdateCriteria.AllFields is not supported by Update2 methods.");
            }

            // set update criteria - default is changed fields
            if (criteria == UpdateCriteria.Default)
            {
                criteria = (_dataMap.DataItem.UpdateCriteria == UpdateCriteria.Default)
                                                           ? UpdateCriteria.ChangedFields : _dataMap.DataItem.UpdateCriteria;
            }
            if (criteria == UpdateCriteria.KeyAndVersion)
            {
                criteria = UpdateCriteria.ChangedFields;
            }

            // check for keys
            if (_dataMap.KeyFields.Count == 0)
            {
                throw new InvalidOperationException(String.Format("Class '{0}' does not contain any properties with DataFieldAttributes or none are marked with IsKeyField.", _dataObjectType.FullName));
            }

            // init commands
            DbCommand updateCommand = GetTextCommand("");
            DbCommand selectCommand = (doSelectBack) ? GetTextCommand("") : null;

            // create string builders and param lists
            var setString   = new StringBuilder();
            var setParmList = new List <DbParameter>();

            var whereString   = new StringBuilder();
            var whereParmList = new List <DbParameter>();

            foreach (KeyValuePair <string, object> changedField in obj.OriginalValues)
            {
                PropertyInfo pi = _dataObjectType.GetProperty(changedField.Key);
                if (pi == null)
                {
                    continue;
                }

                IDataMapField field = _dataMap.GetFieldForProperty(pi);
                if ((field == null) || (field.AccessType == AccessType.ReadOnly))
                {
                    continue;
                }
                if ((field.IsAutoIncrement) || (field.IsRowVersion))
                {
                    continue;
                }

                string sFieldDescr = _dialect.FormatFieldName(field.FieldName, (field.UseQuotedIdentifier ?? UseQuotedIdentifier));

                if (field.IsKeyField ||
                    (criteria >= UpdateCriteria.ChangedFields) ||
                    (field.IsRowVersion && (criteria == UpdateCriteria.KeyAndVersion))
                    )
                {
                    // A primary key or row version
                    if (whereString.Length > 0)
                    {
                        whereString.Append(" AND ");
                    }
                    object oParmValue = (changedField.Value ?? DBNull.Value);

                    // add to command
                    if (Convert.IsDBNull(oParmValue))
                    {
                        whereString.AppendFormat("{0} IS NULL", sFieldDescr);
                    }
                    else if (!field.IsComparable)
                    {
                        whereString.AppendFormat("{0} IS NOT NULL", sFieldDescr);
                    }
                    else
                    {
                        DbParameter whereParam = CreateWhereParam(updateCommand, field);
                        whereString.Append(sFieldDescr);
                        whereString.Append(" = ");
                        whereString.Append(whereParam.ParameterName);

                        whereParam.Value = oParmValue;
                        whereParmList.Add(whereParam);
                    }
                }

                if (setString.Length > 0)
                {
                    setString.Append(", ");
                }

                DbParameter setParm = CreateSetParam(updateCommand, field);
                setString.Append(sFieldDescr);
                setString.Append(" = ");
                setString.Append(setParm.ParameterName);

                if (pi.PropertyType == typeof(string))
                {
                    SetStringParamValue(field, setParm, pi.GetValue(obj, null), false);
                }
                else
                {
                    setParm.Value = (pi.GetValue(obj, null) ?? DBNull.Value);
                }

                setParmList.Add(setParm);
            }
            if (setParmList.Count == 0)
            {
                return(null);
            }

            var keyString   = new StringBuilder();
            var keyParmList = new List <DbParameter>();

            foreach (IDataMapField field in _dataMap.KeyFields)
            {
                PropertyInfo pi = field.Property;
                if (pi == null)
                {
                    continue;
                }

                string sFieldDescr = _dialect.FormatFieldName(field.FieldName, (field.UseQuotedIdentifier ?? UseQuotedIdentifier));

                if (doSelectBack)
                {
                    DbParameter keyParam = CreateWhereParam(selectCommand, field);
                    if (keyString.Length > 0)
                    {
                        keyString.Append(" AND ");
                    }
                    keyString.Append(sFieldDescr);
                    keyString.Append(" = ");
                    keyString.Append(keyParam.ParameterName);


                    keyParam.Value = pi.GetValue(obj, null);
                    keyParmList.Add(keyParam);
                }

                // A primary key or row version
                if (whereString.Length > 0)
                {
                    whereString.Append(" AND ");
                }

                // get value for parameter
                object oParmValue;
                if (obj.OriginalValues.ContainsKey(pi.Name))
                {
                    oParmValue = (obj.OriginalValues[pi.Name] ?? DBNull.Value);
                }
                else
                {
                    oParmValue = (pi.GetValue(obj, null) ?? DBNull.Value);
                }

                // add to command
                if (Convert.IsDBNull(oParmValue))
                {
                    whereString.AppendFormat("{0} IS NULL", sFieldDescr);
                }
                else
                {
                    DbParameter whereParam = CreateWhereParam(updateCommand, field);
                    whereString.Append(sFieldDescr);
                    whereString.Append(" = ");
                    whereString.Append(whereParam.ParameterName);

                    whereParam.Value = oParmValue;
                    whereParmList.Add(whereParam);
                }
            }

            // setup update command
            updateCommand.CommandText = String.Format("UPDATE {0} SET {1} WHERE {2};", SaveToTable, setString, whereString);
            updateCommand.Parameters.AddRange(setParmList.ToArray());
            updateCommand.Parameters.AddRange(whereParmList.ToArray());

            if (_dialect.SupportsChangeContext && ChangeTrackingContext != null)
            {
                _dialect.ApplyChangeTrackingContext(updateCommand, ChangeTrackingContext);
            }

            if (!doSelectBack)                  // if no select-back return now
            {
                return new[] { updateCommand, null }
            }
            ;

            // setup select command and return both
            selectCommand.CommandText = String.Format("SELECT {0} FROM {1} WHERE {2};", ColumnsString, TableName, keyString);
            selectCommand.Parameters.AddRange(keyParmList.ToArray());

            return(new[] { updateCommand, selectCommand });
        }
    }
コード例 #8
0
        public static bool Save(this ISavable obj, object destination, Mess logMess = null)
        {
            string testo, configType, errDesc;

            testo = "";

            configType = obj.GetType().Name.ParoleMinuMaiu(Str.MinMai.minu, true);

            errDesc = "name:<" + obj.SavableName + ">, parent:<" + obj.SavableParentName + ">, configType:<" + configType + ">";

            if (obj.SavableMarkUser == true)
            {
                if (App.CurrentUserId == 0)
                {
                    Log.main.Add(new Mess(LogType.Warn, Log.main.warnUserText, "for the config: " + errDesc + ", there is no logged in user"));
                    return(false);
                }

                errDesc += ", user id:<" + App.CurrentUserId + ">";
            }

            if (Serialize.SerializeInText(obj, ref testo) == false)
            {
                return(false);
            }



            //if (App.Db != null && (this.memorizzaIn == memorizzaIn.@default || this.memorizzaIn == memorizzaIn.dbPrincipaleApp)) {  //Salvo la config nella tabella impostApp del DB
            if (destination.GetType() == typeof(DBBase) || destination.GetType().IsSubclassOf(typeof(DBBase)))
            {
                DBBase           Db          = (DBBase)destination;
                SqlObj           sql         = new SqlObj(connStr: Db.ConnString);
                DBTabs.ImpostApp settingsTab = Db.ImpostApp;
                string where = settingsTab.nome.Nm + Sql.WhereFormat(obj.SavableName) + " AND " + settingsTab.padre.Nm + Sql.WhereFormat(obj.SavableParentName) + " AND " + settingsTab.tipo.Nm + Sql.WhereFormat(configType);

                if (obj.SavableMarkUser == true)
                {
                    where += " AND " + settingsTab.fk_utentiUte.Nm + Sql.WhereFormat(App.CurrentUserId);
                    settingsTab.fk_utentiUte.Value = App.CurrentUserId;
                }
                else
                {
                    settingsTab.fk_utentiUte.Value = 0;
                }

                if (obj.SavableMarkPcName == true)
                {
                    where += " AND " + settingsTab.nomePc.Nm + Sql.WhereFormat(Environment.MachineName);
                    settingsTab.nomePc.Value = Environment.MachineName;
                }
                else
                {
                    settingsTab.nomePc.Value = "";
                }

                if (sql.ExecQuery(Sql.sel + settingsTab.valore.Nm + " FROM " + settingsTab.Nm + " WHERE " + where) == false)
                {
                    return(false);
                }

                settingsTab.nome.Value    = obj.SavableName;
                settingsTab.padre.Value   = obj.SavableParentName;
                settingsTab.tipo.Value    = configType;
                settingsTab.valore.Value  = testo;
                settingsTab.ultData.Value = DateTime.Now;

                if (sql.ResDt.Rows.Count == 0)
                {
                    if (settingsTab.Insert(sql: ref sql) == false)
                    {
                        return(false);
                    }
                }
                else if (sql.ResDt.Rows.Count == 1)
                {
                    if (settingsTab.Update(where : where, sql: ref sql) == false)
                    {
                        return(false);
                    }
                }
                else
                {
                    Log.main.Add(new Mess(LogType.Warn, Log.main.warnUserText, "in the table:<" + settingsTab.Nm + ">, there are more than one setting with: " + errDesc + ", the setting will not be saved"));
                    return(false);
                }
            }
            else if (destination.GetType().IsSubclassOf(typeof(ConfigFile)))
            { //Salvo la config nel file di configurazione dell'applicazione
                ConfigFile configFile = (ConfigFile)destination;
                if (configFile.SaveConfig(obj, obj.SavableMarkUser, errDesc) == false)
                {
                    return(false);
                }
            }
            else
            {
                Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, "unexpected value for DestinationType:<" + destination.GetType().ToString() + ">"));
                return(false);
            }
            return(true);
        }
コード例 #9
0
        public static ISavable Load(this ISavable obj, object source, out bool inErr, Mess logMess = null)
        {
            inErr = true;
            if (logMess == null)
            {
                logMess = new Mess(LogType.Warn, Log.main.warnUserText);
            }

            if (String.IsNullOrEmpty(obj.SavableName))
            {
                logMess.testoDaLoggare = "received null or void SavableName";
                Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, logMess.testoDaLoggare));
                return(obj);
            }

            if (obj == null)
            {
                logMess.testoDaLoggare = "received null savable object";
                Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, logMess.testoDaLoggare));
                return(obj);
            }

            string text, configType, errDesc;

            configType = obj.GetType().Name;

            errDesc = "name:<" + obj.SavableName + ">, parent:<" + obj.SavableParentName + ">, configType:<" + configType + ">";

            if (obj.SavableMarkUser == true)
            {
                if (App.CurrentUserId == 0)
                {
                    logMess.testoDaLoggare = "for the config: " + errDesc + ", there is no logged in user";
                    Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, logMess.testoDaLoggare));
                    return(obj);
                }
                errDesc += ", id utente:<" + App.CurrentUserId + ">";
            }

            if (source.GetType() == typeof(DBBase) || source.GetType().IsSubclassOf(typeof(DBBase)))
            { //Carico la config dalla tabella impostApp del DB
                DBBase           Db          = (DBBase)source;
                DBTabs.ImpostApp settingsTab = Db.ImpostApp;

                SqlObj sql = new SqlObj(connStr: Db.ConnString); string where; List <string> queries = new List <string>();

                where = settingsTab.nome.Nm + Sql.WhereFormat(obj.SavableName) + " AND " + settingsTab.padre.Nm + Sql.WhereFormat(obj.SavableParentName) + " AND " + settingsTab.tipo.Nm + Sql.WhereFormat(configType);

                if (obj.SavableMarkUser == true)
                {
                    where += " AND " + settingsTab.fk_utentiUte.Nm + Sql.WhereFormat(App.CurrentUserId);
                }
                else
                {
                    where += " AND " + settingsTab.fk_utentiUte.Nm + Sql.WhereFormat(0);
                }


                //Se distinguiNomePc allora verifico se cè la config per nomePc se non c'è allora eseguo la ricerca senza così eventualmente prendo la confg.dell'utente se
                if (obj.SavableMarkPcName == true)
                {
                    queries.Add(Sql.sel + settingsTab.valore.Nm + " FROM " + settingsTab.Nm + " WHERE " + where + " AND " + settingsTab.nomePc.Nm + Sql.WhereFormat(Environment.MachineName));
                }

                queries.Add(Sql.sel + settingsTab.valore.Nm + " FROM " + settingsTab.Nm + " WHERE " + where);

                foreach (string query in queries)
                {
                    if (sql.ExecQuery(query) == false)
                    {
                        return(obj);
                    }
                    if (sql.ResDt.Rows.Count > 0)
                    {
                        break;
                    }
                }

                if (sql.ResDt.Rows.Count == 0)
                {
                    //If tipoLogErr <> Tipi._Nothing Then log.Acc(New Mess(tipoLogErr, log.testoUteGen(tipoLogErr), "nella tabella:<" & .nmTab & ">, non ho trovato impostazioni con " & descErr))
                    logMess.testoDaLoggare = "in the table:" + settingsTab.Nm + ">, there are no settings with: " + errDesc;
                    Log.main.Add(logMess);
                    return(obj);
                }
                else if (sql.ResDt.Rows.Count > 1)
                {
                    logMess.testoDaLoggare = "in the table:" + settingsTab.Nm + ">, there are more than one setting with: " + errDesc + ", sarà preso il primo valore";
                    Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, logMess.testoDaLoggare));
                }

                text = (string)sql.ResDt.Rows[0][settingsTab.valore.Nm];

                if (Serialize.DeserializeFromText(text, ref obj) == false)
                {
                    return(obj);
                }
            }
            else if (source.GetType().IsSubclassOf(typeof(ConfigFile)))  //Carico la config dal file di configurazione dell'applicazione
            {
                ConfigFile configFile = (ConfigFile)source;
                if (configFile.GetConfig(ref obj, obj.SavableMarkUser, logMess) == false)
                {
                    return(obj);
                }
            }
            else
            {
                Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, "unexpected value for source type:<" + source.GetType().ToString() + ">"));
            }
            inErr = false;
            return(obj);
        }