protected virtual int TightMarshalNestedObject1(
     OpenWireFormat wireFormat,
     DataStructure o,
     BooleanStream bs)
 {
     return wireFormat.TightMarshalNestedObject1(o, bs);
 }
        // 
        // Un-marshal an object instance from the data input stream
        // 
        public override void TightUnmarshal(OpenWireFormat wireFormat, Object o, BinaryReader dataIn, BooleanStream bs) 
        {
            base.TightUnmarshal(wireFormat, o, dataIn, bs);

            DataArrayResponse info = (DataArrayResponse)o;

            if (bs.ReadBoolean()) {
                short size = dataIn.ReadInt16();
                DataStructure[] value = new DataStructure[size];
                for( int i=0; i < size; i++ ) {
                    value[i] = (DataStructure) TightUnmarshalNestedObject(wireFormat,dataIn, bs);
                }
                info.Data = value;
            }
            else {
                info.Data = null;
            }
        }
Example #3
0
        public void LooseMarshalNestedObject(DataStructure o, BinaryWriter dataOut)
        {
            dataOut.Write(o != null);
            if(o != null)
            {
                byte type = o.GetDataStructureType();
                dataOut.Write(type);

                BaseDataStreamMarshaller dsm = GetDataStreamMarshallerForType(type);
                dsm.LooseMarshal(this, o, dataOut);
            }
        }
 protected virtual void TightMarshalNestedObject2(
     OpenWireFormat wireFormat,
     DataStructure o,
     BinaryWriter dataOut,
     BooleanStream bs)
 {
     wireFormat.TightMarshalNestedObject2(o, dataOut, bs);
 }
 public void TightMarshalNestedObject2(DataStructure o, BinaryWriter ds, BooleanStream bs)
 {
     if (!bs.ReadBoolean())
         return ;
     
     byte type = o.GetDataStructureType();
     ds.Write(type);
     
     if (o.IsMarshallAware() && bs.ReadBoolean())
     {
         MarshallAware ma = (MarshallAware) o;
         byte[] sequence = ma.GetMarshalledForm(this);
         ds.Write(sequence, 0, sequence.Length);
     }
     else
     {
         
         BaseDataStreamMarshaller dsm = (BaseDataStreamMarshaller) dataMarshallers[type & 0xFF];
         if (dsm == null)
             throw new IOException("Unknown data type: " + type);
         dsm.TightMarshal2(this, o, ds, bs);
     }
 }
 protected virtual void LooseMarshalNestedObject(
     OpenWireFormat wireFormat,
     DataStructure o,
     BinaryWriter dataOut)
 {
     wireFormat.LooseMarshalNestedObject(o, dataOut);
 }
 protected virtual void LooseMarshalObjectArray(
     OpenWireFormat wireFormat,
     DataStructure[] objects,
     BinaryWriter dataOut)
 {
     dataOut.Write(objects!=null);
     if (objects!=null)
     {
         dataOut.Write((short) objects.Length);
         for (int i = 0; i < objects.Length; i++)
         {
             LooseMarshalNestedObject(wireFormat, objects[i], dataOut);
         }
     }
 }
        public async Task<Document> Map(string filepath, string configFilepath, DataStructure dataStructure = null,
            Definition definitionParam = null)
        {
            var appConfig = await AppConfigMapper.Map(configFilepath);

            if (appConfig == null)
            {
                throw new ArgumentNullException(
                    "configFilepath",
                    string.Format("Could not load configuration file from: {0}", configFilepath));
            }

            var datastructure =
                appConfig.DataStructures.FirstOrDefault(
                    d =>
                        (d.Format == ConfigurationStaticData.ConllxFormat) ||
                        (d.Format == ConfigurationStaticData.ConllFormat));

            if (datastructure == null)
            {
                EventAggregator.GetEvent<StatusNotificationEvent>()
                    .Publish(
                        "Could not load CONLLX file because the structure is not defined in the configuration file.");
                return null;
            }
            definition = definitionParam ?? appConfig.Definitions.FirstOrDefault();

            if (definition == null)
            {
                EventAggregator.GetEvent<StatusNotificationEvent>()
                    .Publish(
                        "Could not load XML file because the tree definitionParam is not defined in the configuration file.");
                return null;
            }


            wordPrototype = datastructure.Elements.OfType<Word>().Single();
            sentencePrototype = datastructure.Elements.OfType<Sentence>().Single();
            documentPrototype = datastructure.Elements.OfType<Document>().Single();

            var document = await CreateDocument(filepath);

            document.FilePath = filepath;

            var filenameToPathMapping = AppConfig.GetConfigFileNameToFilePathMapping();

            document.Attributes.Add(
                new Attribute
                {
                    AllowedValuesSet = filenameToPathMapping.Values,
                    Value = appConfig.Name,
                    Name = "configuration",
                    DisplayName = "Configuration",
                    Entity = "attribute",
                    IsEditable = true,
                    IsOptional = false
                });

            document.Attributes.Add(
                new Attribute
                {
                    Value = appConfig.Filepath,
                    Name = "configurationFilePath",
                    DisplayName = "Configuration file path",
                    Entity = "attribute",
                    IsEditable = false,
                    IsOptional = false
                });

            return document;
        }
Example #9
0
    public static void Save()
    {
        GeneralExecution general = SceneGlobals.general;

        System.DateTime t0 = System.DateTime.Now;
        DataStructure   save_datastructure = new DataStructure();

        DataStructure general_information = new DataStructure("GeneralInformation", save_datastructure);

        general_information.Set("original_path", general.battle_path);
        general_information.Set("in level progress", (int)general.mission_core.in_level_progress);
        general_information.Set("in stage progress", (int)general.mission_core.in_stage_progress);

        ReferenceSystem ref_sys = SceneGlobals.ReferenceSystem;

        if (ref_sys.HasParent)
        {
            general_information.Set("RS offset", ref_sys.Offset);
            general_information.Set("RS parent", ref_sys.ref_obj.ID);
        }
        else
        {
            general_information.Set("RS position", ref_sys.Position);
        }

        SceneObject[]       scene_array     = new SceneObject[SceneObject.TotObjectList.Count];
        Explosion[]         explosion_array = new Explosion[SceneGlobals.explosion_collection.Count];
        Bullet[]            bullet_array    = new Bullet[SceneGlobals.bullet_collection.Count];
        DestroyableTarget[] target_array    = new DestroyableTarget[SceneGlobals.destroyables.Count];

        SceneObject.TotObjectList.Values.CopyTo(scene_array, 0);
        SceneGlobals.bullet_collection.CopyTo(bullet_array);
        SceneGlobals.destroyables.CopyTo(target_array);

        scene_array = System.Array.FindAll(scene_array,
                                           x =>
                                           !(x is Missile && !(x as Missile).Released) &&
                                           !(x is Network && (x as Network).Name == "\"friendly rogue\"-Network" | (x as Network).Name == "\"hostile rogue\"-Network") &&
                                           !(x is Target)
                                           );

        ISavable[] savable_objects = new ISavable[scene_array.Length +
                                                  explosion_array.Length +
                                                  bullet_array.Length +
                                                  target_array.Length];

        int indx = 0;

        System.Array.ConvertAll(scene_array, x => x as ISavable).CopyTo(savable_objects, indx);
        indx += scene_array.Length;
        System.Array.ConvertAll(explosion_array, x => x as ISavable).CopyTo(savable_objects, indx);
        indx += explosion_array.Length;
        System.Array.ConvertAll(bullet_array, x => x as ISavable).CopyTo(savable_objects, indx);
        indx += bullet_array.Length;
        System.Array.ConvertAll(target_array, x => x as ISavable).CopyTo(savable_objects, indx);

        DataStructure object_states = new DataStructure("ObjectStates", save_datastructure);

        foreach (ISavable obj in savable_objects)
        {
            if (obj != null)
            {
                DataStructure ds = new DataStructure(obj.Name, object_states);
                obj.Save(ds);
            }
        }

        //save_datastructure.Save("saved/Saves/" + System.DateTime.Now.ToString("dd_MM_yyyy_hh_mm_ss"));
        save_datastructure.Save("saved/Saves/def_save");
        DeveloppmentTools.LogFormat("Saved: {0} ms", (System.DateTime.Now - t0).Milliseconds.ToString());
    }
Example #10
0
    /// <summary>
    ///		Saves a battle.
    ///		Should be called, when the save button is pressed
    /// </summary>
    public void SaveBattle()
    {
        string path = DataStructure.GeneralPath + path_field.text + ".cfgt";

        DataStructure res     = new DataStructure();
        DataStructure general = new DataStructure("general", res);

        general.Set("planet", "mars");
        bool   is_player_squad = false;
        ushort player_num      = 0;

        //	Story
        // -------------
        StoryStage first = StoryStage.FirstStage;

        if (first != null)
        {
            first.GetTotalDS(res);
        }


        //	Implications
        // --------------
        for (int i = 0; i < EditorGeneral.squadron_list.Count; i++)
        {
            Squadron squad = EditorGeneral.squadron_list[i];
            if (squad.name == "default")
            {
                continue;
            }

            is_player_squad = squad.ships.Exists(x => x.IsPlayer) | (squad.leader != null && squad.leader.IsPlayer);
            DataStructure squad_data = new DataStructure(is_player_squad ? "player squadron" : "squadron", res);
            squad_data.Set("name", squad.name);
            squad_data.Set("friendly", squad.friendly);
            if (squad.leader == null)
            {
                squad_data.Set("leader", "NULL");
            }
            else
            {
                squad_data.Set("leader pos", squad.leader.Position);
                squad_data.Set("leader rot", Quaternion.Euler(squad.leader.Rotation));
                squad_data.Set("leader vel", squad.leader.Velocity);
                squad_data.Set("leader angvel", squad.leader.AngularVelocity);
                squad_data.Set("leader", squad.leader.name);
            }
            int          ship_num           = squad.ships.Count;
            string[]     names              = new string[ship_num];
            Vector3[]    positions          = new Vector3[ship_num];
            Quaternion[] rotations          = new Quaternion[ship_num];
            Vector3[]    velocities         = new Vector3[ship_num];
            Vector3[]    angular_velocities = new Vector3[ship_num];
            for (int j = 0; j < ship_num; j++)
            {
                EDShip ship = squad.ships[j];
                names [j]              = ship.name;
                positions [j]          = ship.Position;
                rotations [j]          = Quaternion.Euler(ship.Rotation);
                velocities [j]         = ship.Velocity;
                angular_velocities [j] = ship.AngularVelocity;
                if (ship.IsPlayer)
                {
                    player_num = (ushort)(j + 1);
                }
            }
            if (is_player_squad)
            {
                squad_data.Set("player ship", player_num);
            }
            squad_data.Set("ships", names);
            squad_data.Set("positions", positions);
            squad_data.Set("orientations", rotations);
            squad_data.Set("velocities", velocities);
            squad_data.Set("angular velocities", angular_velocities);
        }

        for (int i = 0; i < EditorGeneral.target_list.Count; i++)
        {
            EDTarget      tgt      = EditorGeneral.target_list[i];
            DataStructure tgt_data = new DataStructure("target", res);
            tgt_data.Set("hp", tgt.hp);
            tgt_data.Set("mass", tgt.mass);
            tgt_data.Set("name", tgt.name);
            tgt_data.Set("friendly", tgt.friendly);
            tgt_data.Set("position", tgt.Position);
            tgt_data.Set("rotation", Quaternion.Euler(tgt.Rotation));
            tgt_data.Set("velocity", tgt.Velocity);
            tgt_data.Set("angular velocity", tgt.AngularVelocity);
            tgt_data.Set("object", tgt.pref);
        }

        // Debug.Log(string.Join("\n", res.ToText()));
        res.Save(path, true);

        FileReader.FileLog(string.Format("Saved to {0} sucessfully", path), FileLogType.editor);
    }
Example #11
0
    /// <summary>
    ///		Loads a battle.
    ///		Should be called, when the load button is pressed
    /// </summary>
    public void LoadBattle()
    {
        EditorGeneral.active.Clear();
        string path = DataStructure.GeneralPath + path_field.text + ".cfgt";

        if (!File.Exists(path))
        {
            FileReader.FileLog(string.Format("File \"{0}\" does not exist!", path), FileLogType.error);
        }
        DataStructure battle_data = DataStructure.Load(path, "battledata", is_general: true);

        FileReader.FileLog(string.Format("Loaded {0} into editor", path), FileLogType.editor);

        foreach (DataStructure child in battle_data.AllChildren)
        {
            switch (child.Name)
            {
            // Story
            case "story":
                var        stages = child.AllChildren;
                StoryStage last   = null;
                for (int i = 0; i < stages.Length; i++)
                {
                    DataStructure stage         = stages[i];
                    StoryStage    current_stage = StoryManager.active.SpawnStoryStage();
                    if (i == 0)
                    {
                        current_stage.IsFirst = true;
                    }
                    else
                    {
                        current_stage.SetParent(last);
                    }
                    foreach (DataStructure command in stage.AllChildren)
                    {
                        switch (command.Name)
                        {
                        case "spawn":
                            current_stage.Spawn_SpawnNode(command.Get <string []>("types"), command.Get <string []>("names"));
                            break;

                        case "get conversation":
                            current_stage.Spawn_ConversationNode(command.Get <ushort>("ID"));
                            break;

                        case "objective":
                            current_stage.Spawn_ObjectiveNode(command.Get <string>("objective type"), command.Get <string>("target name"));
                            break;
                        }
                    }
                    last = current_stage;
                }
                break;

            // Implications
            case "player squadron":
            case "squadron":
                Squadron squad = new Squadron(child.Get <string>("name"), child.Get <bool>("friendly"));

                // Leader
                string leader_ship_name = child.Get <string>("leader", quiet: true);
                if (leader_ship_name != "NULL" & child.Contains <string>("leader"))
                {
                    GameObject leader_prefab = Globals.premade_ships.GetChild(leader_ship_name).Get <GameObject>("chassis");
                    GameObject leader        = Instantiate(leader_prefab);
                    EDShip     leader_ship   = new EDShip(leader_ship_name, child.Get <Vector3>("leader pos"), child.Get <Quaternion>("leader rot").eulerAngles)
                    {
                        Velocity        = child.Get("leader vel", Vector3.zero, quiet: true),
                        AngularVelocity = child.Get("leader angvel", Vector3.zero, quiet: true)
                    };
                    leader.AddComponent <Movable>().correspondence = leader_ship;
                    squad.leader = leader_ship;
                }
                else
                {
                    squad.leader = null;
                }

                // Squad
                string[]     names     = child.Get <string[]>("ships");
                GameObject[] ship_objs = System.Array.ConvertAll(names,
                                                                 x => Globals.premade_ships.GetChild(x).Get <GameObject>("chassis")
                                                                 );

                Quaternion[] def_rot            = child.Get <Quaternion []>("orientations");
                Vector3[]    positions          = child.Get <Vector3 []>("positions");
                Vector3[]    velocities         = child.Get <Vector3 []>("velocities", quiet: true);
                Vector3[]    angular_velocities = child.Get <Vector3 []>("angular velocities", quiet: true);

                bool has_velocities     = velocities != default(Vector3[]);
                bool has_ang_velocities = angular_velocities != default(Vector3[]);

                List <EDShip> ship_collection = new List <EDShip>();
                for (ushort i = 0; i < positions.Length; i++)
                {
                    GameObject ship_obj = Instantiate(ship_objs[i]);
                    EDShip     ship     = new EDShip(names[i], positions [i], def_rot [i].eulerAngles);
                    if (has_velocities)
                    {
                        ship.Velocity = velocities [i];
                    }
                    if (has_ang_velocities)
                    {
                        ship.AngularVelocity = angular_velocities [i];
                    }
                    ship_obj.AddComponent <Movable>().correspondence = ship;
                    ship_collection.Add(ship);
                }
                EditorGeneral.squadron_list.Add(squad);

                // Asssgn to squad
                if (squad.leader != null)
                {
                    squad.leader.AssignSilent(squad);
                }
                ship_collection.ForEach(x => x.Squad = squad);

                break;

            case "target":
                DSPrefab   ds_pref = child.Get <DSPrefab>("object");
                GameObject tgt_obj = Instantiate(ds_pref.obj);
                EDTarget   tgt     = new EDTarget(child.Get <string>("name"), child.Get <bool>("friendly"), ds_pref)
                {
                    Position = child.Get <Vector3>("position"),
                    Rotation = child.Get <Quaternion>("rotation").eulerAngles
                };
                tgt_obj.AddComponent <Movable>().correspondence = tgt;
                EditorGeneral.target_list.Add(tgt);
                break;

            default: break;
            }
        }

        EditorGeneral.active.Reload();
    }
        public new void CheckSemantics(IDslModel existingConcepts)
        {
            base.CheckSemantics(existingConcepts);

            if (!DslUtility.IsQueryable(DataStructure))
            {
                throw new DslSyntaxException(this, this.GetKeywordOrTypeName() + " can only be used on a queryable data structure, such as Entity. " + DataStructure.GetKeywordOrTypeName() + " is not queryable.");
            }

            if (!DslUtility.IsQueryable(ReferenceProperty.DataStructure))
            {
                throw new DslSyntaxException(this, this.GetKeywordOrTypeName() + " must reference a queryable data structure, such as Entity. " + ReferenceProperty.DataStructure.GetKeywordOrTypeName() + " is not queryable.");
            }

            if (ReferenceProperty.Referenced != DataStructure)
            {
                throw new DslSyntaxException(this, string.Format(
                                                 "{0} references '{1}' which is a reference to '{2}'. Expected is a reference back to '{3}'.",
                                                 this.GetKeywordOrTypeName(),
                                                 ReferenceProperty.GetUserDescription(),
                                                 ReferenceProperty.Referenced.GetUserDescription(),
                                                 DataStructure.GetUserDescription()));
            }
        }
        public void Marshal(Object o, BinaryWriter ds)
        {
            int size = 1;

            if (o != null)
            {
                DataStructure            c    = (DataStructure)o;
                byte                     type = c.GetDataStructureType();
                BaseDataStreamMarshaller dsm;
                bool                     _tightEncodingEnabled;
                bool                     _sizePrefixDisabled;

                lock (this.marshalLock)
                {
                    dsm = GetDataStreamMarshallerForType(type);
                    _tightEncodingEnabled = this.tightEncodingEnabled;
                    _sizePrefixDisabled   = this.sizePrefixDisabled;
                }

                if (_tightEncodingEnabled)
                {
                    BooleanStream bs = new BooleanStream();
                    size += dsm.TightMarshal1(this, c, bs);
                    size += bs.MarshalledSize();

                    if (!_sizePrefixDisabled)
                    {
                        ds.Write(size);
                    }

                    ds.Write(type);
                    bs.Marshal(ds);
                    dsm.TightMarshal2(this, c, ds, bs);
                }
                else
                {
                    BinaryWriter looseOut = ds;
                    MemoryStream ms       = null;

                    // If we are prefixing then we need to first write it to memory,
                    // otherwise we can write direct to the stream.
                    if (!_sizePrefixDisabled)
                    {
                        ms       = new MemoryStream();
                        looseOut = new EndianBinaryWriter(ms);
                        looseOut.Write(size);
                    }

                    looseOut.Write(type);
                    dsm.LooseMarshal(this, c, looseOut);

                    if (!_sizePrefixDisabled)
                    {
                        ms.Position = 0;
                        looseOut.Write((int)ms.Length - 4);
                        ds.Write(ms.GetBuffer(), 0, (int)ms.Length);
                    }
                }
            }
            else
            {
                ds.Write(size);
                ds.Write(NULL_TYPE);
            }
        }
Example #14
0
        public static ShowPrimaryDataModel Convert(long datasetId, int versionId, string title, DataStructure dataStructure, List <ContentDescriptor> dataFileList, bool downloadAccess, Dictionary <string, string> asciiFileDownloadSupport, bool latestVersion, bool hasEditRights)
        {
            ShowPrimaryDataModel model = new ShowPrimaryDataModel();

            model.FileList                 = ConvertContentDiscriptorsToFileInfos(dataFileList);
            model.DatasetId                = datasetId;
            model.VersionId                = versionId;
            model.DataStructure            = dataStructure;
            model.DataStructureType        = DataStructureType.Unstructured;
            model.DatasetTitle             = title;
            model.CompareValuesOfDataTypes = CompareValues(dataStructure as StructuredDataStructure);
            model.DownloadAccess           = downloadAccess;
            model.AsciiFileDownloadSupport = asciiFileDownloadSupport;
            model.LatestVersion            = latestVersion;
            model.HasEditRight             = hasEditRights;


            return(model);
        }
Example #15
0
        public static ShowPrimaryDataModel Convert(long datasetId, int versionId, string title, DataStructure dataStructure, DataTable data, bool downloadAccess, Dictionary <string, string> supportedAsciiFileTypes, bool latestVersion, bool hasEditRights)
        {
            ShowPrimaryDataModel model = new ShowPrimaryDataModel();

            model.Data                     = data;
            model.DatasetId                = datasetId;
            model.VersionId                = versionId;
            model.DataStructure            = dataStructure;
            model.DataStructureType        = DataStructureType.Structured;
            model.DatasetTitle             = title;
            model.CompareValuesOfDataTypes = CompareValues(dataStructure as StructuredDataStructure);
            model.DownloadAccess           = downloadAccess;
            model.DisplayFormats           = getDisplayFormatObjects(dataStructure as StructuredDataStructure);
            model.AsciiFileDownloadSupport = supportedAsciiFileTypes;
            model.LatestVersion            = latestVersion;
            model.HasEditRight             = hasEditRights;

            return(model);
        }
Example #16
0
    public static void Load(string path)
    {
        DataStructure saved = DataStructure.Load(path);
        DataStructure general_information = saved.GetChild("GeneralInformation");
        DataStructure original_file       = DataStructure.Load(general_information.Get <string>("original_path"), is_general: true);

        FileReader.FileLog("Begin Loading", FileLogType.loader);
        GameObject       placeholder = GameObject.Find("Placeholder");
        GeneralExecution general     = placeholder.GetComponent <GeneralExecution>();

        general.battle_path = path;

        // Initiate Operating system
        general.os = new NMS.OS.OperatingSystem(Object.FindObjectOfType <ConsoleBehaviour>(), null);

        // Initiate mission core
        Loader partial_loader = new Loader(original_file);

        general.mission_core = new MissionCore(general.console, partial_loader);

        general.mission_core.in_level_progress = (short)general_information.Get <int>("in level progress");
        general.mission_core.in_stage_progress = (short)general_information.Get <int>("in stage progress");
        DeveloppmentTools.Log("start loading");
        partial_loader.LoadEssentials();

        DataStructure objects = saved.GetChild("ObjectStates");

        Debug.Log(objects);
        foreach (DataStructure child in objects.AllChildren)
        {
            int id = child.Get <ushort>("type", 1000, quiet: true);
            switch (id)
            {
            case 0:
                // Ship
                Dictionary <string, Turret[]> weapon_arrays = new Dictionary <string, Turret[]>();

                string     config_path  = child.Get <string>("config path");
                bool       is_friendly  = child.Get <bool>("friendly");
                bool       is_player    = child.Get <bool>("player");
                int        given_id     = child.Get <int>("id");
                GameObject ship_chassis = Loader.SpawnShip(config_path, is_friendly, is_player, false, pre_id: given_id);

                //LowLevelAI ai = Loader.EnsureComponent<LowLevelAI>(ship_chassis);
                //ai.HasHigherAI = !is_player;

                ShipControl ship_control = ship_chassis.GetComponent <ShipControl>();
                Ship        ship         = ship_control.myship;
                //ship.control_script.ai_low = ai;
                //ship.low_ai = ai;

                int netID = child.Get("parent network", is_friendly ? 1 : 2);
                if (SceneObject.TotObjectList.ContainsKey(netID) && SceneObject.TotObjectList [netID] is Network)
                {
                    ship.high_ai.Net = SceneObject.TotObjectList [netID] as Network;
                }

                ship.Position        = child.Get <Vector3>("position");
                ship.Orientation     = child.Get <Quaternion>("orientation");
                ship.Velocity        = child.Get <Vector3>("velocity");
                ship.AngularVelocity = child.Get <Vector3>("angular velocity");

                foreach (DataStructure child01 in child.AllChildren)
                {
                    switch (child01.Get <ushort>("type", 9, quiet:true))
                    {
                    case 1:                     // weapon
                        Weapon.GetFromDS(child01.GetChild("description"), child01, ship.Transform);
                        break;

                    case 3:                     // fuel tank
                        FuelTank.GetFromDS(child01.GetChild("description"), child01, ship.Transform);
                        break;

                    case 4:                     // engine
                        Engine.GetFromDS(child01.GetChild("description"), child01, ship.Transform);
                        break;

                    case 10:                     // ammo box
                        AmmoBox.GetFromDS(child01.GetChild("description"), child01, ship.Transform);
                        break;

                    case 11:                     // missile launcher
                        MissileLauncher.GetFromDS(child01.GetChild("description"), child01, ship.Transform);
                        break;

                    case 12:                     // armor
                        Armor.GetFromDS(child01, ship);
                        break;

                    default:
                        if (child01.Name.StartsWith("turr-"))
                        {
                            var tg = TurretGroup.Load(child01, ship);
                            weapon_arrays [child01.Name.Substring(5)] = tg.TurretArray;
                            ship_control.turretgroup_list.Add(new TurretGroup(Target.None, tg.TurretArray, tg.name)
                            {
                                own_ship = ship
                            });
                        }
                        break;
                    }
                }


                // Initializes parts
                foreach (BulletCollisionDetection part in ship_chassis.GetComponentsInChildren <BulletCollisionDetection>())
                {
                    part.Initialize();
                }
                ship_control.turrets = weapon_arrays;

                ship.os.cpu.Execute(child.Get <ulong []>("code"));

                if (is_player)
                {
                    SceneGlobals.Player = ship;
                    SceneGlobals.ui_script.Start_();
                }

                break;

            case 1:             // Missile
                Missile.SpawnFlying(child);
                break;

            case 2:             // Bullet
                Bullet.Spawn(
                    Globals.ammunition_insts [child.Get <string>("ammunition")],
                    child.Get <Vector3>("position"),
                    Quaternion.FromToRotation(Vector3.forward, child.Get <Vector3>("velocity")),
                    child.Get <Vector3>("velocity"),
                    child.Get <bool>("is_friend")
                    );
                break;

            case 3:             // Destroyable target
                DestroyableTarget.Load(child);
                break;

            case 4:             // Explosion

                break;
            }
        }

        general.os.Attached = SceneGlobals.Player;

        ReferenceSystem ref_sys;

        if (general_information.Contains <Vector3>("RS position"))
        {
            ref_sys = new ReferenceSystem(general_information.Get <Vector3>("RS position"));
        }
        else
        {
            int parent_id = general_information.Get <int>("RS parent");
            if (SceneObject.TotObjectList.ContainsKey(parent_id))
            {
                ref_sys = new ReferenceSystem(SceneObject.TotObjectList [parent_id]);
            }
            else
            {
                ref_sys = new ReferenceSystem(Vector3.zero);
            }
            ref_sys.Offset = general_information.Get <Vector3>("RS offset");
        }
        SceneGlobals.ReferenceSystem = ref_sys;
    }
Example #17
0
        public void TightMarshalNestedObject2(DataStructure o, BinaryWriter ds, BooleanStream bs)
        {
            if(!bs.ReadBoolean())
            {
                return;
            }

            byte type = o.GetDataStructureType();
            ds.Write(type);

            if(o.IsMarshallAware() && bs.ReadBoolean())
            {
                MarshallAware ma = (MarshallAware) o;
                byte[] sequence = ma.GetMarshalledForm(this);
                ds.Write(sequence, 0, sequence.Length);
            }
            else
            {
                BaseDataStreamMarshaller dsm = GetDataStreamMarshallerForType(type);
                dsm.TightMarshal2(this, o, ds, bs);
            }
        }
        public DataStructureDataTable(long id) : this()
        {
            DataStructureManager dataStructureManager = null;

            try
            {
                dataStructureManager = new DataStructureManager();
                DataStructure dataStructure = dataStructureManager.AllTypesDataStructureRepo.Get(id);
                if (dataStructure != null)
                {
                    this.Id          = dataStructure.Id;
                    this.Title       = dataStructure.Name;
                    this.Description = dataStructure.Description;

                    if (dataStructure.Datasets.Count > 0)
                    {
                        this.inUse = true;
                    }
                    else
                    {
                        this.inUse = false;
                    }

                    this.Structured = false;


                    if (dataStructureManager.StructuredDataStructureRepo.Get(id) != null)
                    {
                        this.Variables = new DataTable("Variables");

                        this.Variables.Columns.Add("Id", typeof(Int64));
                        this.Variables.Columns.Add("Label");
                        this.Variables.Columns.Add("Description");
                        this.Variables.Columns.Add("isOptional", typeof(Boolean));
                        this.Variables.Columns.Add("Unit");
                        this.Variables.Columns.Add("DataType");
                        this.Variables.Columns.Add("SystemType");
                        this.Variables.Columns.Add("AttributeName");
                        this.Variables.Columns.Add("AttributeDescription");

                        StructuredDataStructure structuredDataStructure = dataStructureManager.StructuredDataStructureRepo.Get(id);
                        this.Structured = true;
                        DataRow dataRow;
                        foreach (Variable vs in structuredDataStructure.Variables)
                        {
                            dataRow                         = this.Variables.NewRow();
                            dataRow["Id"]                   = vs.Id;
                            dataRow["Label"]                = vs.Label;
                            dataRow["Description"]          = vs.Description;
                            dataRow["isOptional"]           = vs.IsValueOptional;
                            dataRow["Unit"]                 = vs.Unit.Name;
                            dataRow["DataType"]             = vs.DataAttribute.DataType.Name;
                            dataRow["SystemType"]           = vs.DataAttribute.DataType.SystemType;
                            dataRow["AttributeName"]        = vs.DataAttribute.Name;
                            dataRow["AttributeDescription"] = vs.DataAttribute.Description;
                            this.Variables.Rows.Add(dataRow);
                        }
                    }
                }
            }
            finally
            {
                dataStructureManager.Dispose();
            }
        }
Example #19
0
        public static ShowPrimaryDataModel Convert(long datasetId, string title, DataStructure dataStructure, DataTable data, bool downloadAccess)
        {
            ShowPrimaryDataModel model = new ShowPrimaryDataModel();
            model.Data = data;
            model.DatasetId = datasetId;
            model.DataStructure = dataStructure;
            model.DataStructureType = DataStructureType.Structured;
            model.DatasetTitle = title;
            model.CompareValuesOfDataTypes = CompareValues();
            model.DownloadAccess = downloadAccess;
            model.DisplayFormats = getDisplayFormatObjects(dataStructure as StructuredDataStructure);

            return model;
        }
 protected virtual int TightMarshalObjectArray1(
     OpenWireFormat wireFormat,
     DataStructure[] objects,
     BooleanStream bs)
 {
     if (objects != null)
     {
         int rc = 0;
         bs.WriteBoolean(true);
         rc += 2;
         for (int i = 0; i < objects.Length; i++)
         {
             rc += TightMarshalNestedObject1(wireFormat, objects[i], bs);
         }
         return rc;
     }
     else
     {
         bs.WriteBoolean(false);
         return 0;
     }
 }
Example #21
0
 public abstract string Build(DataStructure data);
Example #22
0
 public OpEngineerManager(SessionConfig PrivateSessionConfig) : base(PrivateSessionConfig)
 {
     this.DataStructrure = new DataStructure();
 }
        private async Task<StorageFolder> getModuleBaseFolderAsync(DataStructure.Module selectedModule)
        {
            // check if token exists
            Windows.Storage.ApplicationDataContainer folderTokens = Windows.Storage.ApplicationData.Current.LocalSettings;
            string listToken = (string)folderTokens.Values[selectedModule.moduleId];

            StorageFolder moduleBaseFolder;

            // if token exists
            // get folder access
            // otherwise create folder under Downloads library
            if (listToken != null)
            {
                try
                {
                    moduleBaseFolder = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFolderAsync(listToken);
                }
                catch
                {
                    moduleBaseFolder = null;
                }

                if (moduleBaseFolder == null)
                {
                    String moduleFolderName = selectedModule.moduleCode.Replace("/", "_");

                    moduleBaseFolder = await Windows.Storage.DownloadsFolder.CreateFolderAsync(moduleFolderName, CreationCollisionOption.GenerateUniqueName);
                    listToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(moduleBaseFolder, moduleBaseFolder.Name);

                    folderTokens.Values[selectedModule.moduleId] = listToken;
                }
            }
            else
            {
                String moduleFolderName = selectedModule.moduleCode.Replace("/", "_");

                moduleBaseFolder = await Windows.Storage.DownloadsFolder.CreateFolderAsync(moduleFolderName, CreationCollisionOption.GenerateUniqueName);
                listToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(moduleBaseFolder, moduleBaseFolder.Name);

                folderTokens.Values[selectedModule.moduleId] = listToken;
            }

            return moduleBaseFolder;
        }
Example #24
0
 public abstract string GetFilename(DataStructure dataStructure);
 protected virtual void TightMarshalObjectArray2(
     OpenWireFormat wireFormat,
     DataStructure[] objects,
     BinaryWriter dataOut,
     BooleanStream bs)
 {
     if (bs.ReadBoolean())
     {
         dataOut.Write((short) objects.Length);
         for (int i = 0; i < objects.Length; i++)
         {
             TightMarshalNestedObject2(wireFormat, objects[i], dataOut, bs);
         }
     }
 }
Example #26
0
        protected override async Task ImportData()
        {
            FLogger.Log(LogType.Message, "ChunkImporter: Importing Data");
            IOMessages.CurrentState = "Importing Data";

            try
            {
                if (format != PLY_FORMAT_ASCII)
                {
                    throw new FormatException("PLY files in binary format are not supported.");
                }

                using (var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, DefaultFileOptions))
                    using (var reader = new StreamReader(stream))
                    {
                        string line;
                        bool   header    = true;
                        Char   delimiter = ' ';

                        while ((line = await reader.ReadLineAsync()) != null)
                        {
                            String[] lineStrings = line.Split(delimiter);

                            if (header)
                            {
                                if (lineStrings[0] == "end_header")
                                {
                                    header = false;
                                }
                            }
                            else
                            {
                                ParticleData           particleData = new ParticleData();
                                Triple <int, int, int> chunkId      = new Triple <int, int, int>();
                                chunkId.x = 0; chunkId.y = 0; chunkId.z = 0;

                                if (DataStructure.ContainsKey("x"))
                                {
                                    Single x = Single.Parse(lineStrings[DataStructure["x"]], CultureInfo.InvariantCulture);
                                    x += (Single)Offsets.x;
                                    x *= (Single)ScaleValue;
                                    particleData.x = x;
                                    chunkId.x      = Convert.ToInt32(Math.Floor((x - BoundsMin.x) / ChunkSize.x));
                                    if (chunkId.x < 0)
                                    {
                                        chunkId.x = 0;
                                    }
                                    if (chunkId.x >= ChunkCount.x)
                                    {
                                        chunkId.x = ChunkCount.x - 1;
                                    }
                                }

                                if (DataStructure.ContainsKey("y"))
                                {
                                    Single y = Single.Parse(lineStrings[DataStructure["y"]], CultureInfo.InvariantCulture);
                                    y += (Single)Offsets.y;
                                    y *= (Single)ScaleValue;
                                    particleData.y = y;
                                    chunkId.y      = Convert.ToInt32(Math.Floor((y - BoundsMin.y) / ChunkSize.y));
                                    if (chunkId.y < 0)
                                    {
                                        chunkId.y = 0;
                                    }
                                    if (chunkId.y >= ChunkCount.y)
                                    {
                                        chunkId.y = ChunkCount.y - 1;
                                    }
                                }

                                if (DataStructure.ContainsKey("z"))
                                {
                                    Single z = Single.Parse(lineStrings[DataStructure["z"]], CultureInfo.InvariantCulture);
                                    z += (Single)Offsets.z;
                                    z *= (Single)ScaleValue;
                                    particleData.z = z;
                                    chunkId.z      = Convert.ToInt32(Math.Floor((z - BoundsMin.z) / ChunkSize.z));
                                    if (chunkId.z < 0)
                                    {
                                        chunkId.z = 0;
                                    }
                                    if (chunkId.z >= ChunkCount.z)
                                    {
                                        chunkId.z = ChunkCount.z - 1;
                                    }
                                }

                                if (DataStructure.ContainsKey("r"))
                                {
                                    Single r = Single.Parse(lineStrings[DataStructure["r"]], CultureInfo.InvariantCulture) / 255;
                                    particleData.r = r;
                                }

                                if (DataStructure.ContainsKey("g"))
                                {
                                    Single g = Single.Parse(lineStrings[DataStructure["g"]], CultureInfo.InvariantCulture) / 255;
                                    particleData.g = g;
                                }

                                if (DataStructure.ContainsKey("b"))
                                {
                                    Single b = Single.Parse(lineStrings[DataStructure["b"]], CultureInfo.InvariantCulture) / 255;
                                    particleData.b = b;
                                }

                                if (DataStructure.ContainsKey("a"))
                                {
                                    Single a = Single.Parse(lineStrings[DataStructure["a"]], CultureInfo.InvariantCulture) / 255;
                                    particleData.a = a;
                                }

                                int chunkIndex = chunkId.x +
                                                 chunkId.y * ChunkCount.x +
                                                 chunkId.z * ChunkCount.x * ChunkCount.y;


                                if (chunkIndex >= 0 && chunkIndex < _chunkManager.ChunkList.Count)
                                {
                                    Chunk chunk = _chunkManager.ChunkList[chunkIndex];
                                    chunk.BinaryWriter.Write(particleData.GetByteArray());
                                    chunk.UpdateElementCount();
                                }

                                LinesProcessed++; // update count of processed lines -> needed to calculate progress
                                if (LinesProcessed == Lines)
                                {
                                    break;                      // all vertices are parsed now -> break
                                }
                            }
                        }

                        _chunkManager.UpdateElementCount();
                        IOMessages.CurrentState = "Finished";
                    }
            }
            catch (Exception e)
            {
                FLogger.Log(LogType.Error, e.ToString());
                IOMessages.CurrentState = e.ToString();
            }
        }
 protected virtual void LooseMarshalCachedObject(
     OpenWireFormat wireFormat,
     DataStructure o,
     BinaryWriter dataOut)
 {
     /*
      if (wireFormat.isCacheEnabled()) {
      Short index = wireFormat.getMarshallCacheIndex(o);
      if (bs.ReadBoolean()) {
      dataOut.Write(index.shortValue(), dataOut);
      wireFormat.Marshal2NestedObject(o, dataOut, bs);
      } else {
      dataOut.Write(index.shortValue(), dataOut);
      }
      } else {
      wireFormat.Marshal2NestedObject(o, dataOut, bs);
      }
      */
     wireFormat.LooseMarshalNestedObject(o, dataOut);
 }
Example #28
0
 public abstract string Build(DataStructure data);
Example #29
0
 public abstract string GetFilename(DataStructure dataStructure);
Example #30
0
        public static MessageModel validateDataStructureDelete(long Id , DataStructure dataStructure)
        {
            if (dataStructure != null && dataStructure.Id != 0)
            {

                if (dataStructure.Datasets.Count == 0)
                {
                    return new MessageModel()
                    {
                        hasMessage = false,
                        Message = "Are you sure you want to delete the Datastructure " + dataStructure.Name + " (" + dataStructure.Id + ").",
                        CssId = dataStructure.Id.ToString()
                    };
                }
                else
                {
                    try
                    {
                        return new MessageModel()
                        {
                            hasMessage = true,
                            Message = "Can't delete the Datastructure " + dataStructure.Name + " (" + dataStructure.Id + ").",
                            CssId = dataStructure.Id.ToString()
                        };
                    }
                    catch
                    {
                        return new MessageModel()
                        {
                            hasMessage = true,
                            Message = "Something is wrong with Datastructure " + Id,
                            CssId = "0"
                        };
                    }
                }
            }
            else
            {
                return new MessageModel()
                {
                    hasMessage = true,
                    Message = "Something is wrong with Datastructure " + Id,
                    CssId = "0"
                };
            }
        }
 public int TightMarshalNestedObject1(DataStructure o, BooleanStream bs)
 {
     bs.WriteBoolean(o != null);
     if (o == null)
         return 0;
     
     if (o.IsMarshallAware())
     {
         MarshallAware ma = (MarshallAware) o;
         byte[] sequence = ma.GetMarshalledForm(this);
         bs.WriteBoolean(sequence != null);
         if (sequence != null)
         {
             return 1 + sequence.Length;
         }
     }
     
     byte type = o.GetDataStructureType();
     if (type == 0) {
         throw new IOException("No valid data structure type for: " + o + " of type: " + o.GetType());
     }
     BaseDataStreamMarshaller dsm = (BaseDataStreamMarshaller) dataMarshallers[type & 0xFF];
     if (dsm == null)
         throw new IOException("Unknown data type: " + type);
     //Console.WriteLine("Marshalling type: " + type + " with structure: " + o);
     return 1 + dsm.TightMarshal1(this, o, bs);
 }
Example #32
0
 public static MessageModel validateDataStructureInUse(long Id, DataStructure dataStructure)
 {
     if (dataStructure != null && dataStructure.Id != 0)
     {
         if (dataStructure.Datasets.Count > 0)
         {
             try
             {
                 return new MessageModel()
                 {
                     hasMessage = true,
                     Message = "Can't save Datastructure " + dataStructure.Name + " (" + Id + "), it's uesed by a Dataset.",
                     CssId = "inUse"
                 };
             }
             catch
             {
                 return new MessageModel()
                 {
                     hasMessage = true,
                     Message = "Something is wrong with Datastructure " + Id,
                     CssId = "0"
                 };
             }
         }
         else
         {
             return new MessageModel();
         }
     }
     else
     {
         if (Id == 0)
         {
             return new MessageModel();
         }
         else
         {
             return new MessageModel()
             {
                 hasMessage = true,
                 Message = "Can't store Variable for the Datastructure " + Id + ", it's uesed by a Dataset.",
                 CssId = "0"
             };
         }
     }
 }
        public void LooseMarshalNestedObject(DataStructure o, BinaryWriter dataOut)
        {
			dataOut.Write(o!=null);
			if( o!=null ) {
				byte type = o.GetDataStructureType();
				dataOut.Write(type);
                BaseDataStreamMarshaller dsm = (BaseDataStreamMarshaller) dataMarshallers[type & 0xFF];
				if( dsm == null )
					throw new IOException("Unknown data type: "+type);
				dsm.LooseMarshal(this, o, dataOut);
			}
        }
Example #34
0
 public static void HomdoUpdateSlot(OleDbConnection conn, int _slot, DataStructure.HomdoInfo _homdo)
 {
     string cmdText = string.Concat(new string[]
     {
         "UPDATE Homdo SET Id = ",
         Conversions.ToString(_homdo._ID),
         " , [Count] = ",
         Conversions.ToString(_homdo._Count),
         " , Lv = ",
         Conversions.ToString(_homdo._Lv),
         " , Doben = ",
         Conversions.ToString(_homdo._Doben),
         " , Int1 = ",
         Conversions.ToString(_homdo._Int1),
         " , Atk1 = ",
         Conversions.ToString(_homdo._Atk1),
         " , Def1 = ",
         Conversions.ToString(_homdo._Def1),
         " , Hpx1 = ",
         Conversions.ToString(_homdo._Hpx1),
         " , Spx1 = ",
         Conversions.ToString(_homdo._Spx1),
         " , Agi1 = ",
         Conversions.ToString(_homdo._Agi1),
         " , Fai1 = ",
         Conversions.ToString(_homdo._Fai1),
         " , Int2 = ",
         Conversions.ToString(_homdo._Int2),
         " , Atk2 = ",
         Conversions.ToString(_homdo._Atk2),
         " , Def2 = ",
         Conversions.ToString(_homdo._Def2),
         " , Hpx2 = ",
         Conversions.ToString(_homdo._Hpx2),
         " , Spx2 = ",
         Conversions.ToString(_homdo._Spx2),
         " , Agi2 = ",
         Conversions.ToString(_homdo._Agi2),
         " , Fai2 = ",
         Conversions.ToString(_homdo._Fai2),
         " , Hp = ",
         Conversions.ToString(_homdo._Hp),
         " , Sp = ",
         Conversions.ToString(_homdo._Sp),
         " , [Long] = ",
         Conversions.ToString(_homdo._Long),
         " , GiatriLong = ",
         Conversions.ToString(_homdo._GiatriLong),
         " , Khang = ",
         Conversions.ToString(_homdo._Khang),
         " , Thuoctinh = ",
         Conversions.ToString(_homdo._Thuoctinh),
         " , GiatriThuoctinh = ",
         Conversions.ToString(_homdo._GiatriThuoctinh),
         " , Loai = ",
         Conversions.ToString(_homdo._Loai),
         " , Texp = ",
         Conversions.ToString(_homdo._TExp),
         " WHERE Slot = ",
         Conversions.ToString(_slot)
     });
     OleDbCommand oleDbCommand = new OleDbCommand(cmdText, conn);
     oleDbCommand.ExecuteNonQuery();
 }
Example #35
0
        public int TightMarshalNestedObject1(DataStructure o, BooleanStream bs)
        {
            bs.WriteBoolean(o != null);
            if(null == o)
            {
                return 0;
            }

            if(o.IsMarshallAware())
            {
                MarshallAware ma = (MarshallAware) o;
                byte[] sequence = ma.GetMarshalledForm(this);
                bs.WriteBoolean(sequence != null);
                if(sequence != null)
                {
                    return 1 + sequence.Length;
                }
            }

            byte type = o.GetDataStructureType();
            if(type == 0)
            {
                throw new IOException("No valid data structure type for: " + o + " of type: " + o.GetType());
            }

            BaseDataStreamMarshaller dsm = GetDataStreamMarshallerForType(type);

            Tracer.Debug("Marshalling type: " + type + " with structure: " + o);
            return 1 + dsm.TightMarshal1(this, o, bs);
        }
Example #36
0
 public static int GetDataBattleGate(DataStructure.BattleGates_key _key, string type)
 {
     int result = 0;
     DataStructure.BattleGates battleGates = Data.Data_BattleGates[_key];
     if (Operators.CompareString(type, "MapId", false) == 0)
     {
         result = battleGates._MapId;
     }
     else
     {
         if (Operators.CompareString(type, "WarpId", false) == 0)
         {
             result = battleGates._WarpId;
         }
         else
         {
             if (Operators.CompareString(type, "Diahinh", false) == 0)
             {
                 result = battleGates._Diahinh;
             }
             else
             {
                 if (Operators.CompareString(type, "1", false) == 0)
                 {
                     result = battleGates._1;
                 }
                 else
                 {
                     if (Operators.CompareString(type, "2", false) == 0)
                     {
                         result = battleGates._2;
                     }
                     else
                     {
                         if (Operators.CompareString(type, "3", false) == 0)
                         {
                             result = battleGates._3;
                         }
                         else
                         {
                             if (Operators.CompareString(type, "4", false) == 0)
                             {
                                 result = battleGates._4;
                             }
                             else
                             {
                                 if (Operators.CompareString(type, "5", false) == 0)
                                 {
                                     result = battleGates._5;
                                 }
                                 else
                                 {
                                     if (Operators.CompareString(type, "6", false) == 0)
                                     {
                                         result = battleGates._6;
                                     }
                                     else
                                     {
                                         if (Operators.CompareString(type, "7", false) == 0)
                                         {
                                             result = battleGates._7;
                                         }
                                         else
                                         {
                                             if (Operators.CompareString(type, "8", false) == 0)
                                             {
                                                 result = battleGates._8;
                                             }
                                             else
                                             {
                                                 if (Operators.CompareString(type, "9", false) == 0)
                                                 {
                                                     result = battleGates._9;
                                                 }
                                                 else
                                                 {
                                                     if (Operators.CompareString(type, "10", false) == 0)
                                                     {
                                                         result = battleGates._10;
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return result;
 }
Example #37
0
        public long createDataset(string dataSetID, XmlDocument metadataXml, long metadataStructureId, DataStructure dataStructure, string researchPlanName)
        {
            Dataset dataset = new Dataset();

            DatasetManager datasetManager = new DatasetManager();
            DataStructureManager dataStructureManager = new DataStructureManager();
            ResearchPlanManager researchPlanManager = new ResearchPlanManager();
            MetadataStructureManager metadataStructureManager = new MetadataStructureManager();
            PermissionManager permissionManager = new PermissionManager();
            SubjectManager subjectManager = new SubjectManager();

            // get existing researchPlan
            ResearchPlan researchPlan = researchPlanManager.Repo.Get(r => researchPlanName.Equals(r.Title)).FirstOrDefault();

            // get existing metadataStructure (created manualy by using edited Bexis1_XSD)
            MetadataStructure metadataStructure = metadataStructureManager.Repo.Get(metadataStructureId);

            // update verwendet, da bei unstructured structures im dataset constructor dataset(dataStructure) nullexception
            dataset = datasetManager.CreateEmptyDataset(dataStructure, researchPlan, metadataStructure);
            long datasetId = dataset.Id;

            // dataPermission
            List<string> usersWithDataPerm = new List<string>();

            // create dataPermission for originalDatasetManager
            string originalDatasetManager = metadataXml.SelectSingleNode("Metadata/general/general/originalDatasetManager/originalDatasetManager").InnerText;
            User userODM = subjectManager.UsersRepo.Get(u => originalDatasetManager.Equals(u.FullName)).FirstOrDefault();
            permissionManager.CreateDataPermission(userODM.Id, 1, dataset.Id, RightType.Create);
            permissionManager.CreateDataPermission(userODM.Id, 1, dataset.Id, RightType.View);
            permissionManager.CreateDataPermission(userODM.Id, 1, dataset.Id, RightType.Update);
            permissionManager.CreateDataPermission(userODM.Id, 1, dataset.Id, RightType.Download);
            usersWithDataPerm.Add(originalDatasetManager);

            // create dataPermissions for metadataAuthor
            string metadataAuthor = metadataXml.SelectSingleNode("Metadata/general/general/metadataCreator/metadataCreator").InnerText;
            if (!usersWithDataPerm.Contains(metadataAuthor))
            {
                User userMA = subjectManager.UsersRepo.Get(u => metadataAuthor.Equals(u.FullName)).FirstOrDefault();
                permissionManager.CreateDataPermission(userMA.Id, 1, dataset.Id, RightType.Create);
                permissionManager.CreateDataPermission(userMA.Id, 1, dataset.Id, RightType.View);
                permissionManager.CreateDataPermission(userMA.Id, 1, dataset.Id, RightType.Update);
                permissionManager.CreateDataPermission(userMA.Id, 1, dataset.Id, RightType.Download);
                usersWithDataPerm.Add(metadataAuthor);
            }

            // create dataPermissions for designatedDatasetManager
            string designatedDatasetManager = metadataXml.SelectSingleNode("Metadata/general/general/designatedDatasetManager/contactType/designatedDatasetManagerName/designatedDatasetManagerName").InnerText;
            if (!usersWithDataPerm.Contains(designatedDatasetManager))
            {
                User userDDM = subjectManager.UsersRepo.Get(u => designatedDatasetManager.Equals(u.FullName)).FirstOrDefault();
                permissionManager.CreateDataPermission(userDDM.Id, 1, dataset.Id, RightType.Create);
                permissionManager.CreateDataPermission(userDDM.Id, 1, dataset.Id, RightType.View);
                permissionManager.CreateDataPermission(userDDM.Id, 1, dataset.Id, RightType.Update);
                permissionManager.CreateDataPermission(userDDM.Id, 1, dataset.Id, RightType.Download);
                usersWithDataPerm.Add(designatedDatasetManager);
            }

            // create dataPermissions for owners
            XmlNodeList ownerNodes = metadataXml.SelectNodes("Metadata/general/general/owners/ownerType/owner/owner");
            foreach (XmlNode ownerNode in ownerNodes)
            {
                string owner = ownerNode.InnerText;
                if (!usersWithDataPerm.Contains(owner))
                {
                    User userO = subjectManager.UsersRepo.Get(u => owner.Equals(u.FullName)).FirstOrDefault();
                    if (userO != null)
                    {
                        permissionManager.CreateDataPermission(userO.Id, 1, dataset.Id, RightType.Create);
                        permissionManager.CreateDataPermission(userO.Id, 1, dataset.Id, RightType.View);
                        permissionManager.CreateDataPermission(userO.Id, 1, dataset.Id, RightType.Update);
                        permissionManager.CreateDataPermission(userO.Id, 1, dataset.Id, RightType.Download);
                        usersWithDataPerm.Add(owner);
                    }
                }
            }

            // integrate metadataXml to dataset
            // checkOut
            if (datasetManager.IsDatasetCheckedOutFor(datasetId, userODM.Name) || datasetManager.CheckOutDataset(datasetId, userODM.Name))
            {
                DatasetVersion workingCopy = datasetManager.GetDatasetWorkingCopy(datasetId); // get dataset
                workingCopy.Metadata = metadataXml; // set metadata to dataset
                datasetManager.EditDatasetVersion(workingCopy, null, null, null); // edit dataset
                datasetManager.CheckInDataset(datasetId, "Metadata was submited.", userODM.Name); // check in
            }

            return dataset.Id;
        }
Example #38
0
 public void DisposeOf(DataStructure objectId)
 {
     RemoveInfo command = new RemoveInfo();
     command.ObjectId = objectId;
     transport.Oneway(command);
 }
Example #39
0
        public static ShowPrimaryDataModel Convert(long datasetId, string title, DataStructure dataStructure, List<ContentDescriptor> dataFileList, bool downloadAccess)
        {
            ShowPrimaryDataModel model = new ShowPrimaryDataModel();
            model.FileList = ConvertContentDiscriptorsToFileInfos(dataFileList);
            model.DatasetId = datasetId;
            model.DataStructure = dataStructure;
            model.DataStructureType = DataStructureType.Unstructured;
            model.DatasetTitle = title;
            model.CompareValuesOfDataTypes = CompareValues();
            model.DownloadAccess = downloadAccess;

            return model;
        }
Example #40
0
        private List<Variable> SortVariablesOnDatastructure(List<Variable> variables, DataStructure datastructure)
        {
            List<Variable> sortedVariables = new List<Variable>();

            XmlDocument extra = new XmlDocument();
            extra.LoadXml(datastructure.Extra.OuterXml);
            IEnumerable<XElement> elements = XmlUtility.GetXElementByNodeName("variable", XmlUtility.ToXDocument(extra));

            foreach (XElement element in elements)
            {
                long id = Convert.ToInt64(element.Value);
                Variable var =variables.Where(v => v.Id.Equals(id)).FirstOrDefault();
                if(var !=null)
                    sortedVariables.Add(var);
            }

            return sortedVariables;
        }
        public async Task<Sentence> LoadSentence(string sentenceId, string filepath, string configFilepath,
            DataStructure dataStructure = null,
            Definition definitionParam = null)
        {
            var appConfig = await AppConfigMapper.Map(configFilepath);

            if (appConfig == null)
            {
                throw new ArgumentNullException(
                    "configFilepath",
                    string.Format("Could not load configuration file from: {0}", configFilepath));
            }

            var datastructure =
                appConfig.DataStructures.FirstOrDefault(
                    d =>
                        (d.Format == ConfigurationStaticData.ConllxFormat) ||
                        (d.Format == ConfigurationStaticData.ConllFormat));

            if (datastructure == null)
            {
                EventAggregator.GetEvent<StatusNotificationEvent>()
                    .Publish(
                        "Could not load CONLLX file because the structure is not defined in the configuration file.");
                return null;
            }
            definition = definitionParam ?? appConfig.Definitions.FirstOrDefault();

            if (definition == null)
            {
                EventAggregator.GetEvent<StatusNotificationEvent>()
                    .Publish(
                        "Could not load XML file because the tree definitionParam is not defined in the configuration file.");
                return null;
            }


            wordPrototype = datastructure.Elements.OfType<Word>().Single();
            sentencePrototype = datastructure.Elements.OfType<Sentence>().Single();

            var sentence = await Task.FromResult(CreateSentence(filepath, sentenceId));

            return sentence;
        }
        private async Task GetTimetableForOneModuleAsync(DataStructure.Module module)
        {
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("CourseId", module.moduleId);

            string timetableResponse = await Utils.RequestSender.GetResponseStringAsync("Timetable_Student_Module", parameters);

            if (timetableResponse != null)
            {
                DataStructure.ClassWrapper classWrapper = JsonConvert.DeserializeObject<DataStructure.ClassWrapper>(timetableResponse);

                if (classWrapper.comments.Equals("Valid login!"))
                {
                    foreach (DataStructure.Class mClass in classWrapper.classes)
                    {
                        mClass.classModuleColor = module.modulePrimaryColor;
                        Utils.DataManager.AddClass(mClass);
                    }
                }
            }
        }
Example #43
0
 private void DisposeOf(DataStructure objectId)
 {
     try
     {
         RemoveInfo command = new RemoveInfo();
         command.ObjectId = objectId;
         if(asyncClose)
         {
             Tracer.Info("Asynchronously disposing of Connection.");
             if(connected.Value)
             {
                 transport.Oneway(command);
             }
             Tracer.Info("Oneway command sent to broker.");
         }
         else
         {
             // Ensure that the object is disposed to avoid potential race-conditions
             // of trying to re-create the same object in the broker faster than
             // the broker can dispose of the object.  Allow up to 5 seconds to process.
             Tracer.Info("Synchronously disposing of Connection.");
             SyncRequest(command, TimeSpan.FromSeconds(5));
             Tracer.Info("Synchronously closed Connection.");
         }
     }
     catch // (BrokerException)
     {
         // Ignore exceptions while shutting down.
     }
 }
Example #44
0
 public DataStructureExtractor()
 {
     DataStructure = new DataStructure();
 }