Exemplo n.º 1
0
        public async Task StoreAsync_WithStorageFile_ThrowsException_IfFileIsNull()
        {
            StorageManager storageManager = new StorageManager();

            TestData data = new TestData() { Text = "Test Text", Number = 42 };
            await AssertEx.ThrowsExceptionAsync<ArgumentNullException>(() => storageManager.StoreAsync(null, data));
        }
Exemplo n.º 2
0
        public async Task RetrieveAsync_WithStorageFolder_ThrowsException_IfFolderIsNull()
        {
            StorageManager storageManager = new StorageManager();

            StorageFolder folder = null;
            string name = GetTestFilename();
            await AssertEx.ThrowsExceptionAsync<ArgumentNullException>(() => storageManager.RetrieveAsync<TestData>(folder, name));
        }
Exemplo n.º 3
0
        public async Task StoreAsync_WithStorageFolder_ThrowsException_IfNameIsEmpty()
        {
            StorageManager storageManager = new StorageManager();

            StorageFolder folder = ApplicationData.Current.TemporaryFolder;
            TestData data = new TestData() { Text = "Test Text", Number = 42 };
            await AssertEx.ThrowsExceptionAsync<ArgumentException>(() => storageManager.StoreAsync(folder, "", data));
        }
Exemplo n.º 4
0
        public async Task StoreAsync_WithStorageFolder_ThrowsException_IfFolderIsNull()
        {
            StorageManager storageManager = new StorageManager();

            StorageFolder folder = null;
            string name = GetTestFilename();
            TestData data = new TestData() { Text = "Test Text", Number = 42 };
            await AssertEx.ThrowsExceptionAsync<ArgumentNullException>(() => storageManager.StoreAsync(folder, name, data));
        }
        public async Task StoreAsync_WithStorageFile_ThrowsException_IfFileIsNull()
        {
            StorageManager storageManager = new StorageManager();

            TestData data = new TestData() { Text = "Test Text", Number = 42 };
            var e = await Assert.ThrowsAsync<ArgumentNullException>(() => storageManager.StoreAsync(null, data));

            Assert.Equal("Value cannot be null.\r\nParameter name: file", e.Message);
            Assert.Equal("file", e.ParamName);
        }
        public async Task StoreAsync_WithStorageFolder_ThrowsException_IfNameIsEmpty()
        {
            StorageManager storageManager = new StorageManager();

            StorageFolder folder = ApplicationData.Current.TemporaryFolder;
            TestData data = new TestData() { Text = "Test Text", Number = 42 };
            var e = await Assert.ThrowsAsync<ArgumentException>(() => storageManager.StoreAsync(folder, "", data));

            Assert.Equal("The argument cannot be null or an empty string.\r\nParameter name: name", e.Message);
            Assert.Equal("name", e.ParamName);
        }
        public async Task RetrieveAsync_WithStorageFolder_ReturnsNullIfFileDoesNotExist()
        {
            StorageManager storageManager = new StorageManager();

            StorageFolder folder = ApplicationData.Current.TemporaryFolder;
            string name = GetTestFilename();

            TestData retrievedData = await storageManager.RetrieveAsync<TestData>(folder, name);

            Assert.Null(retrievedData);
        }
        public async Task StoreAsync_WithStorageFolder_ThrowsException_IfFolderIsNull()
        {
            StorageManager storageManager = new StorageManager();

            StorageFolder folder = null;
            string name = GetTestFilename();
            TestData data = new TestData() { Text = "Test Text", Number = 42 };
            var e = await Assert.ThrowsAsync<ArgumentNullException>(() => storageManager.StoreAsync(folder, name, data));

            Assert.Equal("Value cannot be null.\r\nParameter name: folder", e.Message);
            Assert.Equal("folder", e.ParamName);
        }
Exemplo n.º 9
0
        public HGScene(RegionInfo regInfo, AgentCircuitManager authen,
                       CommunicationsManager commsMan, SceneCommunicationService sceneGridService,
                       StorageManager storeManager,
                       ModuleLoader moduleLoader, bool dumpAssetsToFile, bool physicalPrim,
                       bool SeeIntoRegionFromNeighbor, IConfigSource config, string simulatorVersion)
            : base(regInfo, authen, commsMan, sceneGridService, storeManager, moduleLoader,
                   dumpAssetsToFile, physicalPrim, SeeIntoRegionFromNeighbor, config, simulatorVersion)
        {
            m_log.Info("[HGScene]: Starting HGScene.");
            m_assMapper = new HGAssetMapper(this);

            EventManager.OnNewInventoryItemUploadComplete += UploadInventoryItem;
        }
Exemplo n.º 10
0
    //Constructor
    private Managers()
    {
        if (m_managers == null)
        {
            m_managers = GameObject.Instantiate(Resources.Load("Prefabs/Manager") as GameObject);

            if (m_managers != null)
            {
                m_SpawnerMgr = m_managers.GetComponent<Spawner>();
                m_GameMgr = m_managers.GetComponent<GameController>();
                m_MenuMgr = m_managers.GetComponent<MenusController>();
                m_StorageMgr = m_managers.GetComponent<StorageManager>();
            }
        }
    }
Exemplo n.º 11
0
		public XmppServer()
		{
			StorageManager = new StorageManager();
			userManager = new UserManager(StorageManager);
			AuthManager = new AuthManager();

			streamManager = new XmppStreamManager();
			SessionManager = new XmppSessionManager();

			gateway = new XmppGateway();
			sender = new XmppSender(gateway);

			serviceManager = new XmppServiceManager(this);
			handlerManager = new XmppHandlerManager(streamManager, gateway, sender, this);
		}
        public void StorageManagerStoreSmallErrorTextDirectlyInTable()
        {
            var tableMock = new Mock<ITableClient>();

            var blobMock = new Mock<IBlobClient>();

            var mgr = new StorageManager(tableMock.Object, blobMock.Object);

            var record = new ExceptionRecord
            {
                SerializedError = "Small Error"
            };

            mgr.StoreError(record);

            tableMock.Verify(x => x.Save(It.Is<ExceptionRecord>(r => r == record)));
        }
Exemplo n.º 13
0
        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App()
        {
            // Global handler for uncaught exceptions.
            UnhandledException += Application_UnhandledException;

            // Standard XAML initialization
            InitializeComponent();

            // Phone-specific initialization
            InitializePhoneApplication();

            // Language display initialization
            InitializeLanguage();

            ViewModelLocator = Resources["Locator"] as ViewModelLocator;
            if (ViewModelLocator == null)
            {
                Debug.WriteLine("ViewModelLocator is null, exiting.");
                Terminate();
            }

            StorageManager = new StorageManager();

            // Show graphics profiling information while debugging.
            if (Debugger.IsAttached)
            {
                // Display the current frame rate counters.
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // Enable non-production analysis visualization mode,
                // which shows areas of a page that are handed off to GPU with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;

                // Prevent the screen from turning off while under the debugger by disabling
                // the application's idle detection.
                // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
                // and consume battery power when the user is not using the phone.
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }
        }
Exemplo n.º 14
0
 /// <summary>
 /// constructor with stored Sessions load 
 /// </summary>
 SessionDataManager()
 {
     StorageManager = new StorageManager<SessionsContainer>(this.handleSave, this.handleError);
     Data_Lock.EnterWriteLock();
     try
     {
         var sessions = StorageManager.Get<Session[]>((dbx) =>
         {
             return dbx.Session.Include(s => s.User.Role).ToArray();
         });
         foreach (var sess in sessions)
         {
             Data.Add(sess.SessionGuid, sess);
         }
     }
     finally
     {
         Data_Lock.ExitWriteLock();
     }
 }
Exemplo n.º 15
0
        public Scene(RegionInfo regInfo, AgentCircuitManager authen,
                     CommunicationsManager commsMan, SceneCommunicationService sceneGridService,
                     StorageManager storeManager,
                     ModuleLoader moduleLoader, bool dumpAssetsToFile, bool physicalPrim,
                     bool SeeIntoRegionFromNeighbor, IConfigSource config, string simulatorVersion)
        {
            m_config = config;

            Random random = new Random();
            
            BordersLocked = true;

            Border northBorder = new Border();
            northBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, (int)Constants.RegionSize);  //<---
            northBorder.CrossDirection = Cardinals.N;
            NorthBorders.Add(northBorder);

            Border southBorder = new Border();
            southBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, 0);    //--->
            southBorder.CrossDirection = Cardinals.S;
            SouthBorders.Add(southBorder);

            Border eastBorder = new Border();
            eastBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, (int)Constants.RegionSize);   //<---
            eastBorder.CrossDirection = Cardinals.E;
            EastBorders.Add(eastBorder);

            Border westBorder = new Border();
            westBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, 0);     //--->
            westBorder.CrossDirection = Cardinals.W;
            WestBorders.Add(westBorder);

            BordersLocked = false;

            m_lastAllocatedLocalId = (uint)(random.NextDouble() * (double)(uint.MaxValue/2))+(uint)(uint.MaxValue/4);
            m_moduleLoader = moduleLoader;
            m_authenticateHandler = authen;
            CommsManager = commsMan;
            m_sceneGridService = sceneGridService;
            m_storageManager = storeManager;
            m_regInfo = regInfo;
            m_regionHandle = m_regInfo.RegionHandle;
            m_regionName = m_regInfo.RegionName;
            m_datastore = m_regInfo.DataStore;
            m_lastUpdate = Util.EnvironmentTickCount();

            m_physicalPrim = physicalPrim;
            m_seeIntoRegionFromNeighbor = SeeIntoRegionFromNeighbor;

            m_eventManager = new EventManager();
            m_permissions = new ScenePermissions(this);

            m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this);
            m_asyncSceneObjectDeleter.Enabled = true;

            // Load region settings
            m_regInfo.RegionSettings = m_storageManager.DataStore.LoadRegionSettings(m_regInfo.RegionID);
            if (m_storageManager.EstateDataStore != null)
            {
                m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(m_regInfo.RegionID);
            }

            //Bind Storage Manager functions to some land manager functions for this scene
            EventManager.OnLandObjectAdded +=
                new EventManager.LandObjectAdded(m_storageManager.DataStore.StoreLandObject);
            EventManager.OnLandObjectRemoved +=
                new EventManager.LandObjectRemoved(m_storageManager.DataStore.RemoveLandObject);

            m_sceneGraph = new SceneGraph(this, m_regInfo);

            // If the scene graph has an Unrecoverable error, restart this sim.
            // Currently the only thing that causes it to happen is two kinds of specific
            // Physics based crashes.
            //
            // Out of memory
            // Operating system has killed the plugin
            m_sceneGraph.UnRecoverableError += RestartNow;

            RegisterDefaultSceneEvents();

            DumpAssetsToFile = dumpAssetsToFile;

            m_scripts_enabled = !RegionInfo.RegionSettings.DisableScripts;

            m_physics_enabled = !RegionInfo.RegionSettings.DisablePhysics;

            StatsReporter = new SimStatsReporter(this);
            StatsReporter.OnSendStatsResult += SendSimStatsPackets;
            StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats;

            StatsReporter.SetObjectCapacity(objectCapacity);

            // Old
            /*
            m_simulatorVersion = simulatorVersion
                + " (OS " + Util.GetOperatingSystemInformation() + ")"
                + " ChilTasks:" + m_seeIntoRegionFromNeighbor.ToString()
                + " PhysPrim:" + m_physicalPrim.ToString();
            */

            m_simulatorVersion = simulatorVersion + " (" + Util.GetRuntimeInformation() + ")";

            try
            {
                // Region config overrides global config
                //
                IConfig startupConfig = m_config.Configs["Startup"];

                // Should we try to run loops synchronously or asynchronously?
                m_useAsyncWhenPossible = startupConfig.GetBoolean("use_async_when_possible", false);

                //Animation states
                m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
                // TODO: Change default to true once the feature is supported
                m_usePreJump = startupConfig.GetBoolean("enableprejump", false);

                m_maxNonphys = startupConfig.GetFloat("NonPhysicalPrimMax", m_maxNonphys);
                if (RegionInfo.NonphysPrimMax > 0)
                {
                    m_maxNonphys = RegionInfo.NonphysPrimMax;
                }

                m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys);

                if (RegionInfo.PhysPrimMax > 0)
                {
                    m_maxPhys = RegionInfo.PhysPrimMax;
                }

                // Here, if clamping is requested in either global or
                // local config, it will be used
                //
                m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", m_clampPrimSize);
                if (RegionInfo.ClampPrimSize)
                {
                    m_clampPrimSize = true;
                }

                m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries);
                m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings);
                m_dontPersistBefore =
                  startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
                m_dontPersistBefore *= 10000000;
                m_persistAfter =
                  startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
                m_persistAfter *= 10000000;

                m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "XEngine");

                IConfig packetConfig = m_config.Configs["PacketPool"];
                if (packetConfig != null)
                {
                    PacketPool.Instance.RecyclePackets = packetConfig.GetBoolean("RecyclePackets", true);
                    PacketPool.Instance.RecycleDataBlocks = packetConfig.GetBoolean("RecycleDataBlocks", true);
                }

                m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl);

                IConfig interest_management_config = m_config.Configs["InterestManagement"];
                if (interest_management_config != null)
                {
                    string update_prioritization_scheme = interest_management_config.GetString("UpdatePrioritizationScheme", "Time").Trim().ToLower();
                    switch (update_prioritization_scheme)
                    {
                        case "time":
                            m_update_prioritization_scheme = UpdatePrioritizationSchemes.Time;
                            break;
                        case "distance":
                            m_update_prioritization_scheme = UpdatePrioritizationSchemes.Distance;
                            break;
                        case "simpleangulardistance":
                            m_update_prioritization_scheme = UpdatePrioritizationSchemes.SimpleAngularDistance;
                            break;
                        case "frontback":
                            m_update_prioritization_scheme = UpdatePrioritizationSchemes.FrontBack;
                            break;
                        default:
                            m_log.Warn("[SCENE]: UpdatePrioritizationScheme was not recognized, setting to default settomg of Time");
                            m_update_prioritization_scheme = UpdatePrioritizationSchemes.Time;
                            break;
                    }

                    m_reprioritization_enabled = interest_management_config.GetBoolean("ReprioritizationEnabled", true);
                    m_reprioritization_interval = interest_management_config.GetDouble("ReprioritizationInterval", 5000.0);
                    m_root_reprioritization_distance = interest_management_config.GetDouble("RootReprioritizationDistance", 10.0);
                    m_child_reprioritization_distance = interest_management_config.GetDouble("ChildReprioritizationDistance", 20.0);
                }

                m_log.Info("[SCENE]: Using the " + m_update_prioritization_scheme + " prioritization scheme");

                #region BinaryStats

                try
                {
                    IConfig statConfig = m_config.Configs["Statistics.Binary"];
                    if (statConfig.Contains("enabled") && statConfig.GetBoolean("enabled"))
                    {
                        if (statConfig.Contains("collect_region_stats"))
                        {
                            if (statConfig.GetBoolean("collect_region_stats"))
                            {
                                // if enabled, add us to the event. If not enabled, I won't get called
                                StatsReporter.OnSendStatsResult += LogSimStats;
                            }
                        }
                        if (statConfig.Contains("region_stats_period_seconds"))
                        {
                            m_statLogPeriod = TimeSpan.FromSeconds(statConfig.GetInt("region_stats_period_seconds"));
                        }
                        if (statConfig.Contains("stats_dir"))
                        {
                            m_statsDir = statConfig.GetString("stats_dir");
                        }
                    }
                }
                catch
                {
                    // if it doesn't work, we don't collect anything
                }

                #endregion BinaryStats
            }
            catch
            {
                m_log.Warn("[SCENE]: Failed to load StartupConfig");
            }
        }
Exemplo n.º 16
0
        private static void WriteResources(Transaction context, StorageManager storage, Resource[] data, bool abort)
        {
            bool createTransaction = (null == context);
            if (createTransaction)
            {
                context = new Transaction();
            }

            // write the data
            foreach (var item in data)
            {
                storage.Write(context, item.Id, item);
            }

            // read the data in the same transaction
            ReadResources(context, storage, data);

            if (createTransaction
                && !abort)
            {
                storage.Prepare(context);
                storage.Commit(context);
            }
            else if (createTransaction
                && abort)
            {
                storage.Abort(context);
            }
        }
Exemplo n.º 17
0
 public void save()
 {
     StorageManager.storeOnDisk(StorageManager.SKIN, this.skin);
     StorageManager.storeOnDisk(StorageManager.ID, this.id);
 }
Exemplo n.º 18
0
    public XnaGame()
    {
        Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;

        Instance              = this;
        _graphics             = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";

        IsFixedTimeStep = true;
        IsMouseVisible  = false;

        #if WINDOWS
        _graphics.PreferredBackBufferWidth  = 960;
        _graphics.PreferredBackBufferHeight = 640;

        _mousepointer = true;
        #elif XBOX360
        _graphics.PreferredBackBufferWidth  = 1280;
        _graphics.PreferredBackBufferHeight = 720;

        _mousepointer = true;
        #elif WINDOWS_PHONE
        _graphics.PreferredBackBufferFormat = SurfaceFormat.Color;
        _mousepointer = false;
        #endif

        //Make 30 FPS or put a key limiter on KeyDown!
        TargetElapsedTime = TimeSpan.FromSeconds(1 / 60.0f);

        StorageManager = new StorageManager("EndingXNA");
        StorageManager.ShowStorageGuide();
        StorageManager.StorageDeviceAction += (sender, e) => {
            if (e.DialogAction == DialogAction.Select)
            {
                Game.LoadFromUserStorage(e.StorageContainer);
            }
        };


        FlashRenderer = new FlashRenderer();

        //Post processing effects for bloom, fisheye and scanlines...
        PostProcess = new PostProcess(this, null);
        #if WINDOWS || XBOX360
        PostProcess.AddProcessor(new BloomProcessor(this)
        {
            Active = true, Settings = BloomProcessor.BloomSettings.PresetSettings[7]
        });
        PostProcess.AddProcessor(new BarrelDistortionProcessor(this)
        {
            Active = false
        });
        PostProcess.AddProcessor(new ScanlinesProcessor(this)
        {
            Active = false, ScanlinesValue = 0.25f
        });

        Components.Add(new GamerServicesComponent(this));
        Components.Add(ThreadPoolComponent = new ThreadPoolComponent(this));
        #endif
    }
Exemplo n.º 19
0
        private static void SearchChunk(IEnumerable <string> chunk, ReadMemoryResults res, bool readChatMessages = true, bool readLogMessages = true)
        {
            List <int> stamps = TimestampManager.getLatestStamps(3, ignoreStamp);

            foreach (string it in chunk)
            {
                string logMessage = it;
                string t          = logMessage.Substring(0, 5);
                int    hour       = int.Parse(logMessage.Substring(0, 2));
                int    minute     = int.Parse(logMessage.Substring(3, 2));
                if (!stamps.Contains(TimestampManager.getStamp(hour, minute)))
                {
                    continue;                                                            // the log message is not recent, so we skip parsing it
                }
                if (FlashClient)
                {
                    // there is some inconsistency with log messages, certain log messages use "12:00: Message.", others use "12:00 Message"
                    // if there is a : after the timestamp we remove it
                    if (logMessage[5] == ':')
                    {
                        logMessage = logMessage.Remove(5, 1);
                    }
                }

                logMessage = logMessage.Replace(" (active prey bonus)", "");

                string message = logMessage.Substring(6); // message without timestamp
                if (readLogMessages)
                {
                    if (logMessage.Length > 14 && logMessage.Substring(5, 9) == " You see " && logMessage[logMessage.Length - 1] == '.')
                    {
                        // the message contains "you see", so it's a look message
                        if (!res.lookMessages.ContainsKey(t))
                        {
                            res.lookMessages.Add(t, new List <string>());
                        }
                        if (!skipDuplicateCommands || !res.lookMessages[t].Contains(logMessage))
                        {
                            res.lookMessages[t].Add(logMessage);
                        }
                        continue;
                    }
                    else if (message.Contains(':'))
                    {
                        if (logMessage.Length > 14 && logMessage.Substring(5, 9) == " Loot of ")   // loot drop message
                        {
                            if (!res.itemDrops.ContainsKey(t))
                            {
                                res.itemDrops.Add(t, new List <string>());
                            }
                            res.itemDrops[t].Add(logMessage);
                            continue;
                        }
                    }
                    else if (logMessage.Length > 17 && logMessage.Substring(5, 12) == " You gained " && logMessage.EndsWith("experience points."))
                    {
                        // the message is an experience string, "You gained x experience."
                        try {
                            int experience = int.Parse(logMessage.Substring(17).Split(' ')[0]);
                            if (!res.exp.ContainsKey(t))
                            {
                                res.exp.Add(t, experience);
                            }
                            else
                            {
                                res.exp[t] = res.exp[t] + experience;
                            }
                        } catch {
                        }
                        continue;
                    }
                    else if (logMessage.Length == 19 && logMessage.Substring(5, 14) == " You are dead.")
                    {
                        if (!res.deaths.ContainsKey(t))
                        {
                            res.deaths.Add(t, true);
                        }
                    }
                    else if (logMessage.Length > 18)
                    {
                        string[] split = message.Split(' ');
                        int      index = split.IndexOf("hitpoints");
                        if (index > 0)
                        {
                            int ind;
                            // damage log message (X loses Y hitpoints due to an attack by Z.)
                            int damage = 0;
                            if (!int.TryParse(split[index - 1], out damage))
                            {
                                continue;
                            }
                            string player;
                            if ((logMessage.Substring(logMessage.Length - 12) == "your attack.") || (logMessage.Substring(logMessage.Length - 21) == "your critical attack."))
                            {
                                // X lost Y hitpoints because of your attack.
                                // attacker is the player himself
                                player = "You";
                            }
                            else if (split.Contains("by"))
                            {
                                // X lost Y hitpoints because of an attack by Z.
                                // Z is the attacker => after the word "by"
                                player = "";
                                ind    = split.IndexOf("by") + 1;
                                for (int i = ind; i < split.Length; i++)
                                {
                                    player = (player == "" ? player : player + " ") + split[i];
                                }
                            }
                            else
                            {
                                continue;
                            }
                            string splitTerm;
                            if (split.Contains("loses"))
                            {
                                splitTerm = "loses";
                            }
                            else if (split.Contains("lose"))
                            {
                                splitTerm = "lose";
                            }
                            else
                            {
                                continue;
                            }
                            ind = split.IndexOf(splitTerm);
                            string target = "";
                            for (int i = 0; i < ind; i++)
                            {
                                target = (target == "" ? target : target + " ") + split[i];
                            }
                            if (!res.damageDealt.ContainsKey(player))
                            {
                                res.damageDealt.Add(player, new Dictionary <string, DamageEntry>());
                            }
                            DamageEntry damageEntry;
                            if (!res.damageDealt[player].ContainsKey(t))
                            {
                                damageEntry        = new DamageEntry();
                                damageEntry.damage = damage;
                                damageEntry.targetDamage.Add(target, damage);
                                res.damageDealt[player].Add(t, damageEntry);
                            }
                            else
                            {
                                damageEntry         = res.damageDealt[player][t];
                                damageEntry.damage += damage;
                                if (damageEntry.targetDamage.ContainsKey(target))
                                {
                                    damageEntry.targetDamage[target] += damage;
                                }
                                else
                                {
                                    damageEntry.targetDamage.Add(target, damage);
                                }
                            }
                            continue;
                        }
                        else
                        {
                            index = split.IndexOf("hitpoints.");
                            if (index > 0)
                            {
                                // heal log message (X healed Y for Z hitpoints.)
                                int healing = 0;
                                if (!int.TryParse(split[index - 1], out healing))
                                {
                                    continue;
                                }

                                int forIndex = split.IndexOf("for");
                                if (forIndex <= 0)
                                {
                                    continue;
                                }


                                string splitTerm;
                                if (split.Contains("heal"))
                                {
                                    splitTerm = "heal";
                                }
                                else if (split.Contains("healed"))
                                {
                                    splitTerm = "healed";
                                }
                                else
                                {
                                    continue;
                                }
                                int healIndex = split.IndexOf(splitTerm);
                                if (healIndex >= forIndex)
                                {
                                    continue;
                                }

                                string source = "";
                                for (int i = 0; i < healIndex; i++)
                                {
                                    if (split[i] == "was" || split[i] == "were")
                                    {
                                        break;
                                    }
                                    if (split[i] == "by")
                                    {
                                        continue;
                                    }
                                    source = (source == "" ? source : source + " ") + split[i];
                                }
                                string target = "";
                                for (int i = healIndex + 1; i < forIndex; i++)
                                {
                                    if (split[i] == "was" || split[i] == "were")
                                    {
                                        break;
                                    }
                                    if (split[i] == "by")
                                    {
                                        continue;
                                    }
                                    target = (target == "" ? target : target + " ") + split[i];
                                }
                                if (target == "yourself" || target == "itself" || target == "himself" || target == "herself")
                                {
                                    target = source;
                                }

                                if (target.Length == 0 || source.Length == 0)
                                {
                                    continue;
                                }

                                if (split.Contains("by"))
                                {
                                    // X healed Y for Z. => X is the source and Y is the target (default)
                                    // X was healed by Y for Z. => X is the target and Y is the source, so swap source and target
                                    string temp = source;
                                    source = target;
                                    target = temp;
                                }

                                if (!res.healingDone.ContainsKey(source))
                                {
                                    res.healingDone.Add(source, new Dictionary <string, DamageEntry>());
                                }
                                DamageEntry healingEntry;
                                if (!res.healingDone[source].ContainsKey(t))
                                {
                                    healingEntry        = new DamageEntry();
                                    healingEntry.damage = healing;
                                    healingEntry.targetDamage.Add(target, healing);
                                    res.healingDone[source].Add(t, healingEntry);
                                }
                                else
                                {
                                    healingEntry         = res.healingDone[source][t];
                                    healingEntry.damage += healing;
                                    if (healingEntry.targetDamage.ContainsKey(target))
                                    {
                                        healingEntry.targetDamage[target] += healing;
                                    }
                                    else
                                    {
                                        healingEntry.targetDamage.Add(target, healing);
                                    }
                                }
                            }
                            else if (logMessage.Substring(5, 14) == " You advanced " && logMessage.Contains("level", StringComparison.OrdinalIgnoreCase))
                            {
                                // advancement log message (You advanced from level x to level x + 1.)
                                if (logMessage[logMessage.Length - 1] == '.')
                                {
                                    if (GlobalDataManager.AddLevelAdvance(logMessage))
                                    {
                                        res.newAdvances.Add(logMessage);
                                    }
                                    continue;
                                }
                            }
                            else if (logMessage.Substring(5, 7) == " Using " && logMessage.Substring(logMessage.Length - 3, 3) == "...")
                            {
                                // using log message (Using one of X items...)
                                var values = Parser.ParseUsingMessage(logMessage);
                                if (!res.usingMessages.ContainsKey(values.Item1))
                                {
                                    res.usingMessages.Add(values.Item1, new Dictionary <string, HashSet <int> >());
                                }
                                if (!res.usingMessages[values.Item1].ContainsKey(t))
                                {
                                    res.usingMessages[values.Item1].Add(t, new HashSet <int>());
                                }
                                res.usingMessages[values.Item1][t].Add(values.Item2);
                                continue;
                            }
                            else if (logMessage.Length > 50 && logMessage.Substring(5, 45) == " Congratulations! You earned the achievement ")
                            {
                                Achievement achievement = StorageManager.getAchievement(Parser.GetAchievement(logMessage));
                                if (achievement != null)
                                {
                                    res.achievements.Add(new Tuple <Achievement, string>(achievement, logMessage));
                                }
                                else
                                {
                                    Console.WriteLine("Unrecognized achievement {0}.", Parser.GetAchievement(logMessage));
                                }
                            }
                            else
                            {
                                foreach (Event ev in StorageManager.eventIdMap.Values)
                                {
                                    foreach (string evMessage in ev.eventMessages)
                                    {
                                        if (logMessage.Length == evMessage.Length + 6 && logMessage.Contains(evMessage.Trim(), StringComparison.OrdinalIgnoreCase))
                                        {
                                            res.eventMessages.Add(new Tuple <Event, string>(ev, logMessage));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (readChatMessages)
                {
                    if (message.Contains(':'))
                    {
                        if (logMessage.Length > 14 && logMessage.Substring(5, 9) == " Loot of ")   // loot drop message
                        {
                            continue;
                        }
                        else     // if the message contains the ':' symbol but is not a loot drop message, it is a chat message, i.e. a command or url
                                 // we only split at most once, because the chat message can contain the ':' symbol as well and we don't want to discard that
                        {
                            string[] split   = message.Split(new char[] { ':' }, 2);
                            string   command = split[1];
                            // now get the player name, we have to discard the level that is between brackets
                            // players can also have spaces in their name, so we take that into account
                            string[] playersplit = split[0].Split(' ');
                            string   player      = "";
                            foreach (string str in playersplit)
                            {
                                if (str.Contains('['))
                                {
                                    break;
                                }
                                player = (player == "" ? player : player + " ") + str;
                            }
                            if (player == "http" || player == "https")
                            {
                                continue;                                        // I don't remember why we do this, possible http link in a log message? not sure
                            }
                            if (command.Contains('@'))
                            {
                                // @ symbol symbolizes a command, so if there is an @ symbol, we treat the string as a command
                                if (!res.commands.ContainsKey(t))
                                {
                                    res.commands.Add(t, new List <Tuple <string, string> >());
                                }
                                var tpl = new Tuple <string, string>(player, command);
                                if (!skipDuplicateCommands || !res.commands[t].Contains(tpl))
                                {
                                    res.commands[t].Add(tpl);
                                }
                            }
                            else if (command.Contains("www") || command.Contains("http") || command.Contains(".com") || command.Contains(".net") || command.Contains(".tv") || command.Contains(".br"))
                            {
                                // check if the command is an url, we aren't really smart about this, just check for a couple of common url-like things
                                if (!res.urls.ContainsKey(t))
                                {
                                    res.urls.Add(t, new List <Tuple <string, string> >());
                                }
                                res.urls[t].Add(new Tuple <string, string>(player, command));
                            }
                        }
                    }
                }
            }
        }
        public MailAttachment AttachFile(int tenant, string user, int messageId,
                                         string name, Stream inputStream, string contentType = null)
        {
            if (messageId < 1)
            {
                throw new AttachmentsException(AttachmentsException.Types.BadParams, "Field 'id_message' must have non-negative value.");
            }

            if (tenant < 0)
            {
                throw new AttachmentsException(AttachmentsException.Types.BadParams, "Field 'id_tenant' must have non-negative value.");
            }

            if (String.IsNullOrEmpty(user))
            {
                throw new AttachmentsException(AttachmentsException.Types.BadParams, "Field 'id_user' is empty.");
            }

            if (inputStream.Length == 0)
            {
                throw new AttachmentsException(AttachmentsException.Types.EmptyFile, "Empty files not supported.");
            }

            var message = GetMailInfo(tenant, user, messageId, new MailMessage.Options());

            if (message == null)
            {
                throw new AttachmentsException(AttachmentsException.Types.MessageNotFound, "Message not found.");
            }

            if (message.Folder != MailFolder.Ids.drafts && message.Folder != MailFolder.Ids.temp)
            {
                throw new AttachmentsException(AttachmentsException.Types.BadParams, "Message is not a draft.");
            }

            if (string.IsNullOrEmpty(message.StreamId))
            {
                throw new AttachmentsException(AttachmentsException.Types.MessageNotFound, "StreamId is empty.");
            }

            var totalSize = GetAttachmentsTotalSize(messageId) + inputStream.Length;

            if (totalSize > ATTACHMENTS_TOTAL_SIZE_LIMIT)
            {
                throw new AttachmentsException(AttachmentsException.Types.TotalSizeExceeded, "Total size of all files exceeds limit!");
            }

            var fileNumber = GetMaxAttachmentNumber(messageId, tenant);

            var attachment = new MailAttachment
            {
                fileName    = name,
                contentType = string.IsNullOrEmpty(contentType) ? MimeMapping.GetMimeMapping(name) : contentType,
                fileNumber  = fileNumber,
                size        = inputStream.Length,
                data        = inputStream.ReadToEnd(),
                streamId    = message.StreamId,
                tenant      = tenant,
                user        = user,
                mailboxId   = message.MailboxId
            };

            QuotaUsedAdd(tenant, inputStream.Length);
            try
            {
                var storage = new StorageManager(tenant, user);
                storage.StoreAttachmentWithoutQuota(attachment);
            }
            catch
            {
                QuotaUsedDelete(tenant, inputStream.Length);
                throw;
            }

            using (var db = GetDb())
            {
                using (var tx = db.BeginTransaction())
                {
                    attachment.fileId = SaveAttachment(db, tenant, messageId, attachment);
                    UpdateMessageChainAttachmentsFlag(db, tenant, user, messageId);

                    tx.Commit();
                }
            }

            return(attachment);
        }
Exemplo n.º 21
0
        public override void LoadForm()
        {
            if (quest == null)
            {
                return;
            }
            this.SuspendLayout();
            NotificationInitialize();

            wikiButton.Click -= c_Click;

            this.questTitle.Text  = quest.name;
            this.premiumBox.Image = quest.premium ? StyleManager.GetImage("checkmark-yes.png") : StyleManager.GetImage("checkmark-no.png");
            this.cityLabel.Text   = quest.city == null ? "Unknown" : quest.city.ToTitle();
            this.levelLabel.Text  = quest.minlevel.ToString();
            this.legendLabel.Text = quest.legend;

            List <TibiaObject> rewards = new List <TibiaObject>();

            foreach (int reward in quest.rewardItems)
            {
                Item item = StorageManager.getItem(reward);
                rewards.Add(item);
            }
            rewards = rewards.OrderByDescending(o => (o as Item).GetMaxValue()).ToList <TibiaObject>();
            int x = 5;
            int y = 77;

            foreach (string missionName in quest.questInstructions.Keys)
            {
                if (quest.questInstructions[missionName].Count == 0)
                {
                    continue;
                }
                if (x + 150 >= this.Size.Width)
                {
                    x  = 5;
                    y += 25;
                }
                Label missionButton = new Label();
                missionButton.BackColor   = System.Drawing.Color.Transparent;
                missionButton.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
                missionButton.Font        = wikiButton.Font;
                missionButton.ForeColor   = StyleManager.NotificationTextColor;
                missionButton.Location    = new System.Drawing.Point(x, y);
                missionButton.Name        = quest.questInstructions[missionName][0].specialCommand != null ? quest.questInstructions[missionName][0].specialCommand : "guide" + Constants.CommandSymbol + quest.name.ToLower() + Constants.CommandSymbol + "1" + Constants.CommandSymbol + missionName;
                missionButton.Padding     = new System.Windows.Forms.Padding(2);
                missionButton.Text        = missionName;
                missionButton.TextAlign   = System.Drawing.ContentAlignment.MiddleCenter;
                missionButton.Click      += MissionButton_Click;
                missionButton.Size        = new Size(150, 21);
                this.Controls.Add(missionButton);
                x += missionButton.Width + 5;
            }
            y += 25;
            using (Graphics gr = Graphics.FromHwnd(legendLabel.Handle)) {
                this.legendLabel.Location = new Point(legendLabel.Location.X, y);
                y += (int)gr.MeasureString(this.legendLabel.Text, this.legendLabel.Font, this.legendLabel.MaximumSize.Width).Height + 20;
            }

            if (this.quest.additionalRequirements.Count > 0 || this.quest.questRequirements.Count > 0)
            {
                Label label = new Label();
                label.Text      = "Requirements";
                label.Location  = new Point(5, y);
                label.ForeColor = StyleManager.NotificationTextColor;
                label.BackColor = Color.Transparent;
                label.Font      = questTitle.Font;
                label.Size      = new Size(this.Size.Width - 10, label.Height);
                this.Controls.Add(label);
                y += 25;

                // Item requirements
                if (this.quest.questRequirements.Count > 0)
                {
                    List <Tuple <int, Item> > requirements = new List <Tuple <int, Item> >();
                    foreach (Tuple <int, int> tpl in quest.questRequirements)
                    {
                        Item item = StorageManager.getItem(tpl.Item2);
                        requirements.Add(new Tuple <int, Item>(tpl.Item1, item));
                    }
                    requirements = requirements.OrderBy(o => o.Item1 * o.Item2.GetMaxValue()).ToList();
                    List <TibiaObject> itemList = requirements.Select(o => o.Item2).ToList <TibiaObject>();

                    List <Control> itemControls = new List <Control>();
                    y = y + UIManager.DisplayCreatureList(this.Controls, itemList, 10, y, this.Size.Width - 10, 1, null, 1, itemControls);
                    int itemnr = 0;
                    foreach (Control control in itemControls)
                    {
                        control.BackgroundImage = StyleManager.GetImage("item_background.png");
                        int  itemCount = requirements[itemnr].Item1;
                        Item item      = requirements[itemnr].Item2;

                        (control as PictureBox).Image = LootDropForm.DrawCountOnItem(item, itemCount);

                        itemnr++;
                    }
                }

                // Text requirements
                if (this.quest.additionalRequirements.Count > 0)
                {
                    List <string> requirementStrings = this.quest.additionalRequirements.ToList();
                    if (this.quest.minlevel > 0)
                    {
                        requirementStrings.Add(String.Format("You must be at least level {0}.", this.quest.minlevel));
                    }

                    y += 5;
                    Regex questRegex = new Regex("\\[([^]]+)\\]");
                    foreach (string text in requirementStrings)
                    {
                        label = new Label();
                        string txt = text;
                        Match  m   = questRegex.Match(txt);
                        label.ForeColor = StyleManager.NotificationTextColor;
                        if (m != null && m.Groups.Count > 1)
                        {
                            string requiredQuestName = m.Groups[1].Value;
                            txt             = txt.Replace(m.Groups[0].Value, requiredQuestName);
                            label.Name      = StorageManager.getQuest(requiredQuestName.ToLower()).GetCommand();
                            label.ForeColor = StyleManager.ClickableLinkColor;
                            label.Click    += MissionButton_Click;
                        }
                        label.Text      = txt == "" ? "" : "- " + txt;
                        label.Location  = new Point(5, y);
                        label.BackColor = Color.Transparent;
                        label.Font      = QuestGuideForm.requirementFont;
                        Size size;
                        using (Graphics gr = Graphics.FromHwnd(label.Handle)) {
                            size       = gr.MeasureString(label.Text, label.Font, this.Size.Width - 50).ToSize();
                            label.Size = new Size(this.Size.Width - 10, (int)(size.Height * 1.2));
                        }
                        this.Controls.Add(label);
                        y += label.Size.Height;
                    }
                }
            }

            if (rewards.Count > 0 || quest.rewardOutfits.Count > 0)
            {
                Label label = new Label();
                label.Text      = "Rewards";
                label.Location  = new Point(40, y);
                label.ForeColor = StyleManager.NotificationTextColor;
                label.BackColor = Color.Transparent;
                label.Font      = questTitle.Font;
                this.Controls.Add(label);
                y += 25;
                if (rewards.Count > 0)
                {
                    List <Control> itemControls = new List <Control>();
                    y = y + UIManager.DisplayCreatureList(this.Controls, rewards, 10, y, this.Size.Width - 10, 1, null, 1, itemControls);
                }
                if (quest.rewardOutfits.Count > 0)
                {
                    List <Control> outfitControls = new List <Control>();

                    List <TibiaObject> rewardOutfits = new List <TibiaObject>();
                    foreach (int reward in quest.rewardOutfits)
                    {
                        Outfit outfit = StorageManager.getOutfit(reward);
                        rewardOutfits.Add(outfit);
                    }

                    y = y + UIManager.DisplayCreatureList(this.Controls, rewardOutfits, 10, y, this.Size.Width - 10, 4, null, 1, outfitControls);
                }
            }
            this.Size = new Size(this.Size.Width, y + 20);

            base.NotificationFinalize();
            this.ResumeLayout(false);
        }
Exemplo n.º 22
0
        /*==================== Common callbacks for success \ failure \ finish ====================*/

        /**
         * Checks the state of the purchase and responds accordingly, giving the user an item,
         * throwing an error, or taking the item away and paying the user back.
         *
         * @param purchase purchase whose state is to be checked.
         */
        private void handleSuccessfulPurchase(/*IabPurchase*/ string productId)
        {
            SoomlaUtils.LogDebug(TAG, "TODO handleSuccessfulPurchase");

            PurchasableVirtualItem pvi;

            try
            {
                pvi = StoreInfo.getPurchasableItem(productId);
            }
            catch (VirtualItemNotFoundException e)
            {
                SoomlaUtils.LogError(TAG, "(handleSuccessfulPurchase - purchase or query-inventory) "
                                     + "ERROR : Couldn't find the " +
                                     " VirtualCurrencyPack OR MarketItem  with productId: " + productId +
                                     ". It's unexpected so an unexpected error is being emitted." + " " + e.Message);
                StoreEvents.GetInstance().PostUnexpectedStoreErrorEvent("Couldn't find the productId "
                                                                        + "of a product after purchase or query-inventory." + " " + e.Message);
                return;
            }

            SoomlaUtils.LogDebug(TAG, "IabPurchase successful.");

            // if the purchasable item is NonConsumableItem and it already exists then we
            // don't fire any events.
            // fixes: https://github.com/soomla/unity3d-store/issues/192
            if (pvi is NonConsumableItem)
            {
                bool exists = StorageManager.getNonConsumableItemsStorage().
                              nonConsumableItemExists((NonConsumableItem)pvi);
                if (exists)
                {
                    return;
                }
            }

            StoreEvents.GetInstance().PostMarketPurchaseEvent(pvi, null, null);
            pvi.give(1);

            StoreEvents.GetInstance().PostItemPurchasedEvent(pvi, null);
            consumeIfConsumable(pvi);

            /*
             * String sku = purchase.getSku();
             * String developerPayload = purchase.getDeveloperPayload();
             * String token = purchase.getToken();
             *
             * PurchasableVirtualItem pvi;
             * try {
             *  pvi = StoreInfo.getPurchasableItem(sku);
             * } catch (VirtualItemNotFoundException e) {
             *  SoomlaUtils.LogError(TAG, "(handleSuccessfulPurchase - purchase or query-inventory) "
             + "ERROR : Couldn't find the " +
             +          " VirtualCurrencyPack OR MarketItem  with productId: " + sku +
             +          ". It's unexpected so an unexpected error is being emitted.");
             +  BusProvider.getInstance().post(new OnUnexpectedStoreErrorEvent("Couldn't find the sku "
             + "of a product after purchase or query-inventory."));
             +  return;
             + }
             +
             + switch (purchase.getPurchaseState()) {
             +  case 0:
             +      SoomlaUtils.LogDebug(TAG, "IabPurchase successful.");
             +
             +      // if the purchasable item is NonConsumableItem and it already exists then we
             +      // don't fire any events.
             +      // fixes: https://github.com/soomla/unity3d-store/issues/192
             +      if (pvi instanceof NonConsumableItem) {
             +          boolean exists = StorageManager.getNonConsumableItemsStorage().
             +                  nonConsumableItemExists((NonConsumableItem) pvi);
             +          if (exists) {
             +              return;
             +          }
             +      }
             +
             +      BusProvider.getInstance().post(new OnMarketPurchaseEvent
             +              (pvi, developerPayload, token));
             +      pvi.give(1);
             +      BusProvider.getInstance().post(new OnItemPurchasedEvent(pvi, developerPayload));
             +
             +      consumeIfConsumable(purchase, pvi);
             +
             +      break;
             +
             +  case 1:
             +
             +  case 2:
             +      SoomlaUtils.LogDebug(TAG, "IabPurchase refunded.");
             +      if (!StoreConfig.friendlyRefunds) {
             +          pvi.take(1);
             +      }
             +      BusProvider.getInstance().post(new MarketRefundEvent(pvi, developerPayload));
             +      break;
             + }
             */
        }
Exemplo n.º 23
0
        public MainForm()
        {
            startup = true;
            Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
            mainForm = this;
            InitializeComponent();

            SettingsManager.LoadSettings(Constants.SettingsFile);

            LootDatabaseManager.LootChanged     += NotificationManager.UpdateLootDisplay;
            LootDatabaseManager.LootChanged     += UpdateLogDisplay;
            GlobalDataManager.ExperienceChanged += NotificationManager.UpdateExperienceDisplay;
            GlobalDataManager.DamageChanged     += NotificationManager.UpdateDamageDisplay;
            GlobalDataManager.UsedItemsChanged  += NotificationManager.UpdateUsedItemsDisplay;

            if (!File.Exists(Constants.DatabaseFile))
            {
                ExitWithError("Fatal Error", String.Format("Could not find database file {0}.", Constants.DatabaseFile));
            }

            if (!File.Exists(Constants.NodeDatabase))
            {
                ExitWithError("Fatal Error", String.Format("Could not find database file {0}.", Constants.NodeDatabase));
            }

            LootDatabaseManager.Initialize();
            StyleManager.InitializeStyle();
            NotificationForm.Initialize();
            Parser.Initialize();
            PopupManager.Initialize(this.notifyIcon1);

            prevent_settings_update = true;
            try {
                StorageManager.InitializeStorage();
            } catch (Exception e) {
                ExitWithError("Fatal Error", String.Format("Corrupted database {0}.\nMessage: {1}", Constants.DatabaseFile, e.Message));
            }
            ProcessManager.Initialize();
            this.initializeSettings();
            try {
                Pathfinder.LoadFromDatabase(Constants.NodeDatabase);
            } catch (Exception e) {
                ExitWithError("Fatal Error", String.Format("Corrupted database {0}.\nMessage: {1}", Constants.NodeDatabase, e.Message));
            }
            prevent_settings_update = false;

            this.InitializeTabs();
            switchTab(0);
            makeDraggable(this.Controls);

            if (SettingsManager.getSettingBool("StartAutohotkeyAutomatically"))
            {
                AutoHotkeyManager.StartAutohotkey();
            }
            ReadMemoryManager.Initialize();
            HuntManager.Initialize();
            UIManager.Initialize();
            MemoryReader.Initialize();
            HUDManager.Initialize();
            GlobalDataManager.Initialize();

            this.Load += MainForm_Load;

            fileWriter = new StreamWriter(Constants.BigLootFile, true);

            tibialyzerLogo.MouseDown += new System.Windows.Forms.MouseEventHandler(this.draggable_MouseDown);
            startup = false;

            ScanningManager.StartScanning();

            scan_tooltip.AutoPopDelay = 60000;
            scan_tooltip.InitialDelay = 500;
            scan_tooltip.ReshowDelay  = 0;
            scan_tooltip.ShowAlways   = true;
            scan_tooltip.UseFading    = true;

            SetScanningImage("scanningbar-red.gif", "No Tibia Client Found...", true);
        }
Exemplo n.º 24
0
 /// <summary>
 /// Steps of initiation are
 /// 1- open DB Connection
 /// 2- Create all required collections, if not existing
 /// 3- Open cursor with active records
 /// </summary>
 private void Init()
 {
     Logger.Debug("Bus manager initialized");
     storeManager = MessageBus.DataBase.Mongo.StorageManager.GetStorageManager();
     storeManager.initQueues(SupportedMessages.GetInstance());
 }
Exemplo n.º 25
0
 void Start()
 {
     storageManagerScript = FindObjectOfType <StorageManager>();
     weightInputField     = GetComponent <InputField>();
 }
Exemplo n.º 26
0
        private async void OnProfileSubmitClicked(object sender, EventArgs e)
        {
            if (!fFirstNameEntry.IsEnabled)
            {
                fFirstNameEntry.IsEnabled = true;
                fSurNameEntry.IsEnabled   = true;
                //fEmailEntry.IsEnabled = true;
                fbirthDatePicker.IsEnabled = true;
                fSexPicker.IsEnabled       = true;
                fHeightPicker.IsEnabled    = true;
                fWeightPicker.IsEnabled    = true;
                fDietTypePicker.IsEnabled  = true;
                fHeightEntry.IsEnabled     = true;
                fSkeletonEntry.IsEnabled   = true;
                fLocationEntry.IsEnabled   = true;
                btnTA.IsVisible            = true;
                btnPA.IsVisible            = true;
                btnTB.IsVisible            = true;
                btnPB.IsVisible            = true;
            }
            else
            {
                ProfileBtn.Text = Properties.LangResource.edit;
                if (fFirstNameEntry.IsEnabled || fSurNameEntry.IsEnabled || fbirthDatePicker.IsEnabled ||
                    fSexPicker.IsEnabled || fHeightPicker.IsEnabled || fWeightPicker.IsEnabled || fHeightEntry.IsEnabled || fLocationEntry.IsEnabled)
                {
                    if (AllFieldsAreFilled())
                    {
                        if (Aweighttype != user.WeightType)
                        {
                            var answer = await App.Current.MainPage.DisplayAlert(Properties.LangResource.changeWeightTypeTitle, Properties.LangResource.changeWeightType, Properties.LangResource.yes, Properties.LangResource.no);

                            if (answer == true)
                            {
                                IEnumerable <Weight> Wrecords = conn.Query <Weight>("select * from weight where iduser=" + user.IDUser);

                                if (Aweighttype == 1)
                                {
                                    if (user.WeightType == 2)
                                    {
                                        foreach (Weight wrecord in Wrecords)
                                        {
                                            wrecord.WValue = Math.Round(wrecord.WValue * 2.204, 2);
                                            StorageManager.UpdateData <Weight>(wrecord);
                                        }
                                    }
                                    else if (user.WeightType == 3)
                                    {
                                        foreach (Weight wrecord in Wrecords)
                                        {
                                            wrecord.WValue = Math.Round(wrecord.WValue * 35.273, 2);
                                            StorageManager.UpdateData <Weight>(wrecord);
                                        }
                                    }
                                }
                                else if (Aweighttype == 2)
                                {
                                    if (user.WeightType == 1)
                                    {
                                        foreach (Weight wrecord in Wrecords)
                                        {
                                            wrecord.WValue = Math.Round(wrecord.WValue * 0.453, 2);
                                            StorageManager.UpdateData <Weight>(wrecord);
                                        }
                                    }
                                    else if (user.WeightType == 3)
                                    {
                                        foreach (Weight wrecord in Wrecords)
                                        {
                                            wrecord.WValue = Math.Round(wrecord.WValue * 16, 2);
                                            StorageManager.UpdateData <Weight>(wrecord);
                                        }
                                    }
                                }
                                else if (Aweighttype == 3)
                                {
                                    if (user.WeightType == 1)
                                    {
                                        foreach (Weight wrecord in Wrecords)
                                        {
                                            wrecord.WValue = Math.Round(wrecord.WValue * 0.028, 2);
                                            StorageManager.UpdateData <Weight>(wrecord);
                                        }
                                    }
                                    else if (user.WeightType == 2)
                                    {
                                        foreach (Weight wrecord in Wrecords)
                                        {
                                            wrecord.WValue = Math.Round(wrecord.WValue * 0.0625, 2);
                                            StorageManager.UpdateData <Weight>(wrecord);
                                        }
                                    }
                                }
                            }
                            Aweighttype = user.WeightType;
                        }
                        //  var user = StorageManager.GetConnectionInfo().LoginUser;
                        user.UpdateDate = DateTime.UtcNow;
                        //  int heightType = heights[fHeightPicker.Items[fHeightPicker.SelectedIndex]];
                        //  int genderType = genders[fSexPicker.Items[fSexPicker.SelectedIndex]];
                        //  user.FirstName = fFirstNameEntry.Text;
                        //  user.LastName = fSurNameEntry.Text;
                        //  user.Birthdate = fbirthDatePicker.Date;
                        //  user.Gender = genderType;
                        //  user.HeightType = heightType;
                        //  user.Height = Convert.ToDouble(fHeightEntry.Text);
                        //  user.Skeleton = Convert.ToDouble(fSkeletonEntry.Text);
                        //  user.Location = fLocationEntry.Text;
                        StorageManager.UpdateData(user);
                        RefreshPage();
                    }
                    else
                    {
                        ProfileBtn.Text = Properties.LangResource.save;
                    }
                }
            }
        }
Exemplo n.º 27
0
        private void InitMember()
        {
            problemPanel.Visible = true;
            // Detail
            txtName.Text     = this.Member.Name;
            txtLastName.Text = this.Member.LastName;
            txtThaiId.Text   = this.Member.ThaiId;

            textBox1.Text  = this.Member.BirthDate.Day.ToString();
            comboBox1.Text = this.Member.BirthDate.Date.ToString("MMMM", new System.Globalization.CultureInfo("th-TH"));
            textBox2.Text  = this.Member.BirthDate.Date.ToString("yyyy", new System.Globalization.CultureInfo("th-TH"));

            if (this.Member.ExpireDate != null)
            {
                textBox6.Text  = this.Member.ExpireDate?.Day.ToString();
                comboBox3.Text = this.Member.ExpireDate?.Date.ToString("MMMM", new System.Globalization.CultureInfo("th-TH"));
                textBox5.Text  = this.Member.ExpireDate?.Date.ToString("yyyy", new System.Globalization.CultureInfo("th-TH"));
            }
            m_currentMemberCourse = StorageManager.GetSingleton().GetApplyCourseLogByMemberID(this.Member.MemberId);
            if (m_currentMemberCourse != null)
            {
                button1.Visible = true;
                textBox4.Text   = m_currentMemberCourse.ApplyDate.Day.ToString();
                comboBox2.Text  = m_currentMemberCourse.ApplyDate.Date.ToString("MMMM", new System.Globalization.CultureInfo("th-TH"));
                textBox3.Text   = m_currentMemberCourse.ApplyDate.Date.ToString("yyyy", new System.Globalization.CultureInfo("th-TH"));
                textBox7.Text   = m_currentMemberCourse.CoursePrice.ToString();
            }
            else
            {
                textBox7.Text   = "0";
                button1.Visible = false;
                textBox4.Text   = DateTime.Now.Day.ToString();
                comboBox2.Text  = DateTime.Now.Date.ToString("MMMM", new System.Globalization.CultureInfo("th-TH"));
                textBox3.Text   = DateTime.Now.Date.ToString("yyyy", new System.Globalization.CultureInfo("th-TH"));

                textBox6.Text  = DateTime.Now.Day.ToString();
                comboBox3.Text = DateTime.Now.Date.ToString("MMMM", new System.Globalization.CultureInfo("th-TH"));
                textBox5.Text  = DateTime.Now.Date.ToString("yyyy", new System.Globalization.CultureInfo("th-TH"));
            }
            txtAge.Text         = this.Member.Age.ToString();
            lblFingerPrint.Text = this.Member.FingerPrint;

            chkMale.Checked   = (this.Member.Gender == enumGender.Male);
            chkFemale.Checked = (this.Member.Gender == enumGender.Female);

            txtHouseNumber.Text   = this.Member.HouseNumber;
            txtVillageNumber.Text = this.Member.VillageNumber;
            txtVillageName.Text   = this.Member.VillageName;
            txtLane.Text          = this.Member.Lane;
            txtRoad.Text          = this.Member.Road;
            txtSubDistrict.Text   = this.Member.SubDistrict;
            txtDistrict.Text      = this.Member.District;
            txtProvince.Text      = this.Member.Province;
            txtPostCode.Text      = this.Member.PostCode;
            txtPhoneNumber.Text   = this.Member.PhoneNumber;
            txtEmail.Text         = this.Member.Email;

            if (this.Member.MemberProfile != null)
            {
                Image img = (Bitmap)((new ImageConverter()).ConvertFrom(this.Member.MemberProfile.ImageByte));
                memberProfileImage.Image = img;
            }
        }
Exemplo n.º 28
0
        public static bool ScanMemory()
        {
            ReadMemoryResults  readMemoryResults  = ReadMemoryManager.ReadMemory();
            ParseMemoryResults parseMemoryResults = Parser.ParseLogResults(readMemoryResults);

            if (parseMemoryResults != null)
            {
                lastResults = parseMemoryResults;
                if (parseMemoryResults.newDamage)
                {
                    GlobalDataManager.UpdateDamage();
                }
            }

            if (readMemoryResults != null && readMemoryResults.newAdvances.Count > 0)
            {
                if (SettingsManager.getSettingBool("AutoScreenshotAdvance"))
                {
                    MainForm.mainForm.Invoke((MethodInvoker) delegate {
                        ScreenshotManager.saveScreenshot("Advance", ScreenshotManager.takeScreenshot());
                    });
                }
                if (SettingsManager.getSettingBool("CopyAdvances"))
                {
                    foreach (object obj in readMemoryResults.newAdvances)
                    {
                        MainForm.mainForm.Invoke((MethodInvoker) delegate {
                            Clipboard.SetText(obj.ToString());
                        });
                    }
                }
                readMemoryResults.newAdvances.Clear();
            }

            if (parseMemoryResults != null && parseMemoryResults.death)
            {
                if (SettingsManager.getSettingBool("AutoScreenshotDeath"))
                {
                    MainForm.mainForm.Invoke((MethodInvoker) delegate {
                        ScreenshotManager.saveScreenshot("Death", ScreenshotManager.takeScreenshot());
                    });
                }
                parseMemoryResults.death = false;
            }

            if (parseMemoryResults != null)
            {
                if (parseMemoryResults.newEventMessages.Count > 0)
                {
                    if (SettingsManager.getSettingBool("EnableEventNotifications"))
                    {
                        foreach (Tuple <Event, string> tpl in parseMemoryResults.newEventMessages)
                        {
                            Event    ev = tpl.Item1;
                            Creature cr = StorageManager.getCreature(ev.creatureid);
                            MainForm.mainForm.Invoke((MethodInvoker) delegate {
                                if (!SettingsManager.getSettingBool("UseRichNotificationType"))
                                {
                                    PopupManager.ShowSimpleNotification("Event in " + ev.location, tpl.Item2, cr.image);
                                }
                                else
                                {
                                    PopupManager.ShowSimpleNotification(new SimpleTextNotification(cr.image, "Event in " + ev.location, tpl.Item2));
                                }
                            });
                        }
                    }
                    parseMemoryResults.newEventMessages.Clear();
                }
            }

            if (SettingsManager.getSettingBool("LookMode") && readMemoryResults != null)
            {
                foreach (string msg in parseMemoryResults.newLooks)
                {
                    string itemName = Parser.parseLookItem(msg).ToLower();
                    if (StorageManager.itemExists(itemName))
                    {
                        MainForm.mainForm.Invoke((MethodInvoker) delegate {
                            CommandManager.ExecuteCommand("item@" + itemName);
                        });
                    }
                    else if (StorageManager.creatureExists(itemName) ||
                             (itemName.Contains("dead ") && (itemName = itemName.Replace("dead ", "")) != null && StorageManager.creatureExists(itemName)) ||
                             (itemName.Contains("slain ") && (itemName = itemName.Replace("slain ", "")) != null && StorageManager.creatureExists(itemName)))
                    {
                        MainForm.mainForm.Invoke((MethodInvoker) delegate {
                            CommandManager.ExecuteCommand("creature@" + itemName);
                        });
                    }
                    else
                    {
                        NPC npc = StorageManager.getNPC(itemName);
                        if (npc != null)
                        {
                            MainForm.mainForm.Invoke((MethodInvoker) delegate {
                                CommandManager.ExecuteCommand("npc@" + itemName);
                            });
                        }
                    }
                }
                parseMemoryResults.newLooks.Clear();
            }

            List <string> commands = parseMemoryResults == null ? new List <string>() : parseMemoryResults.newCommands.ToList();

            commands.Reverse();

            foreach (string command in commands)
            {
                MainForm.mainForm.Invoke((MethodInvoker) delegate {
                    if (!CommandManager.ExecuteCommand(command, parseMemoryResults) && SettingsManager.getSettingBool("EnableUnrecognizedNotifications"))
                    {
                        if (!SettingsManager.getSettingBool("UseRichNotificationType"))
                        {
                            PopupManager.ShowSimpleNotification("Unrecognized command", "Unrecognized command: " + command, StyleManager.GetImage("tibia.png"));
                        }
                        else
                        {
                            PopupManager.ShowSimpleNotification(new SimpleTextNotification(null, "Unrecognized command", "Unrecognized command: " + command));
                        }
                    }
                });
            }
            if (parseMemoryResults != null)
            {
                if (parseMemoryResults.newItems.Count > 0)
                {
                    MainForm.mainForm.Invoke((MethodInvoker) delegate {
                        LootDatabaseManager.UpdateLoot();
                    });
                }
                foreach (Tuple <Creature, List <Tuple <Item, int> > > tpl in parseMemoryResults.newItems)
                {
                    Creature cr = tpl.Item1;
                    List <Tuple <Item, int> > items = tpl.Item2;
                    bool showNotification           = PopupManager.ShowDropNotification(tpl);
                    if (showNotification)
                    {
                        if (!SettingsManager.getSettingBool("UseRichNotificationType"))
                        {
                            Console.WriteLine("Rich Notification");
                            PopupManager.ShowSimpleNotification(cr.displayname, cr.displayname + " dropped a valuable item.", cr.image);
                        }
                        else
                        {
                            MainForm.mainForm.Invoke((MethodInvoker) delegate {
                                PopupManager.ShowSimpleNotification(new SimpleLootNotification(cr, items));
                            });
                        }

                        if (SettingsManager.getSettingBool("AutoScreenshotItemDrop"))
                        {
                            // Take a screenshot if Tibialyzer is set to take screenshots of valuable loot
                            Bitmap screenshot = ScreenshotManager.takeScreenshot();
                            if (screenshot == null)
                            {
                                continue;
                            }
                            // Add a notification to the screenshot
                            SimpleLootNotification screenshotNotification = new SimpleLootNotification(cr, items);
                            Bitmap notification = new Bitmap(screenshotNotification.Width, screenshotNotification.Height);
                            screenshotNotification.DrawToBitmap(notification, new Rectangle(0, 0, screenshotNotification.Width, screenshotNotification.Height));
                            foreach (Control c in screenshotNotification.Controls)
                            {
                                c.DrawToBitmap(notification, new Rectangle(c.Location, c.Size));
                            }
                            screenshotNotification.Dispose();
                            int widthOffset  = notification.Width + 10;
                            int heightOffset = notification.Height + 10;
                            if (screenshot.Width > widthOffset && screenshot.Height > heightOffset)
                            {
                                using (Graphics gr = Graphics.FromImage(screenshot)) {
                                    gr.DrawImage(notification, new Point(screenshot.Width - widthOffset, screenshot.Height - heightOffset));
                                }
                            }
                            notification.Dispose();
                            MainForm.mainForm.Invoke((MethodInvoker) delegate {
                                ScreenshotManager.saveScreenshot("Loot", screenshot);
                            });
                        }
                    }
                }
            }
            return(readMemoryResults != null);
        }
Exemplo n.º 29
0
        public static List <MailAttachment> ChangeEmbededAttachmentLinksForStoring(this MailDraft draft,
                                                                                   MailBoxManager manager,
                                                                                   ILogger log = null)
        {
            if (log == null)
            {
                log = new NullLogger();
            }

            //Todo: This method can be separated in two
            var fckStorage        = StorageManager.GetDataStoreForCkImages(draft.Mailbox.TenantId);
            var attachmentStorage = StorageManager.GetDataStoreForAttachments(draft.Mailbox.TenantId);

            var currentMailFckeditorUrl        = fckStorage.GetUri(StorageManager.CKEDITOR_IMAGES_DOMAIN, "").ToString();
            var currentMailAttachmentFolderUrl = MailStoragePathCombiner.GetMessageDirectory(draft.Mailbox.UserId, draft.StreamId);
            var currentUserStorageUrl          = MailStoragePathCombiner.GetUserMailsDirectory(draft.Mailbox.UserId);

            log.Info("ChangeEmbededAttachmentLinksForStoring() Fckeditor storage base url: {0}", currentMailFckeditorUrl);
            log.Info("ChangeEmbededAttachmentLinksForStoring() Current mail attachment folder storage base url: {0}",
                     currentMailAttachmentFolderUrl);
            log.Info("ChangeEmbededAttachmentLinksForStoring() Current user folder storage base url: {0}",
                     currentUserStorageUrl);

            var xpathQuery = StorageManager.GetXpathQueryForAttachmentsToResaving(currentMailFckeditorUrl,
                                                                                  currentMailAttachmentFolderUrl,
                                                                                  currentUserStorageUrl);

            log.Info(
                "ChangeEmbededAttachmentLinksForStoring() Xpath Query selector for embedded attachment links: {0}",
                xpathQuery);
            var attachmentsForSaving = new List <MailAttachment>();

            var doc = new HtmlDocument();

            doc.LoadHtml(draft.HtmlBody);

            var linkNodes = doc.DocumentNode.SelectNodes(xpathQuery);

            if (linkNodes != null)
            {
                foreach (var linkNode in linkNodes)
                {
                    try
                    {
                        var link = linkNode.Attributes["src"].Value;

                        log.Info("ChangeEmbededAttachmentLinksForStoring() Original selected file_link: {0}", link);

                        var isFckImage   = link.StartsWith(currentMailFckeditorUrl);
                        var prefixLength = isFckImage
                                               ? currentMailFckeditorUrl.Length
                                               : link.IndexOf(currentUserStorageUrl, StringComparison.Ordinal) +
                                           currentUserStorageUrl.Length + 1;
                        var fileLink = HttpUtility.UrlDecode(link.Substring(prefixLength));

                        var fileName = Path.GetFileName(fileLink);
                        var attach   = CreateEmbbededAttachment(fileName, link, fileLink, draft.Mailbox.UserId, draft.Mailbox.TenantId,
                                                                draft.Mailbox.MailBoxId, draft.StreamId);

                        var savedAttachmentId  = manager.GetAttachmentId(draft.Id, attach.contentId);
                        var attachmentWasSaved = savedAttachmentId != 0;
                        var currentImgStorage  = isFckImage ? fckStorage : attachmentStorage;
                        var domain             = isFckImage ? StorageManager.CKEDITOR_IMAGES_DOMAIN : draft.Mailbox.UserId;

                        if (draft.Id == 0 || !attachmentWasSaved)
                        {
                            attach.data = StorageManager.LoadDataStoreItemData(domain, fileLink, currentImgStorage);
                            manager.StoreAttachmentWithoutQuota(draft.Mailbox.TenantId, draft.Mailbox.UserId, attach);
                            attachmentsForSaving.Add(attach);
                        }

                        if (attachmentWasSaved)
                        {
                            attach = manager.GetMessageAttachment(savedAttachmentId, draft.Mailbox.TenantId, draft.Mailbox.UserId);
                            var path = MailStoragePathCombiner.GerStoredFilePath(attach);
                            currentImgStorage    = attachmentStorage;
                            attach.storedFileUrl =
                                MailStoragePathCombiner.GetStoredUrl(currentImgStorage.GetUri(path));
                        }

                        log.Info("ChangeEmbededAttachmentLinksForStoring() Restored new file_link: {0}",
                                 attach.storedFileUrl);
                        linkNode.SetAttributeValue("src", attach.storedFileUrl);
                    }
                    catch (Exception ex)
                    {
                        log.Error("ChangeEmbededAttachmentLinksForStoring() failed with exception: {0}", ex.ToString());
                    }
                }

                draft.HtmlBody = doc.DocumentNode.OuterHtml;
            }

            return(attachmentsForSaving);
        }
        public async Task RetrieveAsync_WithStorageFolder_ThrowsException_IfNameIsEmpty()
        {
            StorageManager storageManager = new StorageManager();

            StorageFolder folder = ApplicationData.Current.TemporaryFolder;
            var e = await Assert.ThrowsAsync<ArgumentException>(() => storageManager.RetrieveAsync<TestData>(folder, ""));

            Assert.Equal("The argument cannot be null or an empty string.\r\nParameter name: name", e.Message);
            Assert.Equal("name", e.ParamName);
        }
 public SpawnGoldBarCommand(GoldBarsSpawnerController goldBarsSpawnerController, StorageManager storageManager) :
     base(storageManager, goldBarsSpawnerController)
 {
     _goldBarsSpawnerController = goldBarsSpawnerController;
 }
        public async Task StoreAsyncRetrieveAsync_WithStorageFile_PersistsFileViaStorage()
        {
            StorageManager storageManager = new StorageManager();
            StorageFolder folder = ApplicationData.Current.TemporaryFolder;
            StorageFile file = await folder.CreateFileAsync(GetTestFilename(), CreationCollisionOption.ReplaceExisting);

            // Store some test data

            TestData data = new TestData() { Text = "Test Text", Number = 42 };
            await storageManager.StoreAsync(file, data);

            // Retrieve and validate the data from the file

            TestData retrievedData = await storageManager.RetrieveAsync<TestData>(file);

            Assert.Equal("Test Text", retrievedData.Text);
            Assert.Equal(42, retrievedData.Number);
        }
Exemplo n.º 33
0
 public TestGrainRuntime(IGrainFactory grainFactory, ITimerRegistry timerRegistry, IReminderRegistry reminderRegistry, IServiceProvider serviceProvider, StorageManager storageManager)
 {
     GrainFactory     = grainFactory ?? throw new ArgumentNullException(nameof(grainFactory));
     TimerRegistry    = timerRegistry ?? throw new ArgumentNullException(nameof(timerRegistry));
     ReminderRegistry = reminderRegistry ?? throw new ArgumentNullException(nameof(reminderRegistry));
     ServiceProvider  = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
     _storageManager  = storageManager ?? throw new ArgumentNullException(nameof(storageManager));
 }
Exemplo n.º 34
0
        public async Task RetrieveAsync_WithStorageFolder_ThrowsException_IfNameIsEmpty()
        {
            StorageManager storageManager = new StorageManager();

            StorageFolder folder = ApplicationData.Current.TemporaryFolder;
            await AssertEx.ThrowsExceptionAsync<ArgumentException>(() => storageManager.RetrieveAsync<TestData>(folder, ""));
        }
        /// <summary>
        ///   Initializes a new instance of the <see cref="MockEventProcessorClient" /> class.
        /// </summary>
        ///
        /// <param name="storageManager">The client responsible for interaction with durable storage, responsible for persisting checkpoints and load-balancing state.</param>
        /// <param name="consumerGroup">The name of the consumer group this processor is associated with.  Events are read in the context of this group.</param>
        /// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace to connect to.  This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
        /// <param name="eventHubName">The name of the specific Event Hub to associate the processor with.</param>
        /// <param name="connectionFactory">A factory used to provide new <see cref="EventHubConnection" /> instances.</param>
        /// <param name="clientOptions">The set of options to use for this processor.</param>
        /// <param name="fakePartitionProcessing"><c>true</c> if <see cref="RunPartitionProcessingAsync" /> should be overridden; otherwise, <c>false</c>.</param>
        /// <param name="numberOfPartitions">The amount of partitions the associated Event Hub has.</param>
        /// <param name="loadBalancer">The <see cref="PartitionLoadBalancer" /> used to manage partition load balance operations.</param>
        ///
        internal MockEventProcessorClient(StorageManager storageManager,
                                          string consumerGroup           = "consumerGroup",
                                          string fullyQualifiedNamespace = "somehost.com",
                                          string eventHubName            = "somehub",
                                          Func <EventHubConnection> connectionFactory = default,
                                          EventProcessorClientOptions clientOptions   = default,
                                          bool fakePartitionProcessing       = true,
                                          int numberOfPartitions             = 3,
                                          PartitionLoadBalancer loadBalancer = default) : base(storageManager, consumerGroup, fullyQualifiedNamespace, eventHubName, connectionFactory, clientOptions, loadBalancer)
        {
            StorageManager = storageManager;

            var partitionIds = Enumerable
                               .Range(1, numberOfPartitions)
                               .Select(p => p.ToString())
                               .ToArray();

            foreach (var partitionId in partitionIds)
            {
                EventPipeline[partitionId] = new ConcurrentQueue <EventData>();
            }

            FakeRunPartitionProcessingAsync = fakePartitionProcessing;

            ProcessErrorAsync += eventArgs =>
            {
                Exception[] newException = new Exception[] { eventArgs.Exception };
                ExceptionCalls.AddOrUpdate(
                    eventArgs.PartitionId,
                    newException,
                    (partitionId, value) => value.Concat(newException).ToArray());

                return(Task.CompletedTask);
            };

            ProcessEventAsync += eventArgs =>
            {
                EventData[] newEvent = new EventData[] { eventArgs.Data };
                ProcessEventCalls.AddOrUpdate(
                    eventArgs.Partition.PartitionId,
                    newEvent,
                    (partitionId, value) => value.Concat(newEvent).ToArray());

                return(Task.CompletedTask);
            };

            PartitionInitializingAsync += eventArgs =>
            {
                InitializeCalls.AddOrUpdate(eventArgs.PartitionId, 1, (partitionId, value) => value + 1);

                return(Task.CompletedTask);
            };

            PartitionClosingAsync += eventArgs =>
            {
                CloseCalls.AddOrUpdate(eventArgs.PartitionId, 1, (partitionId, value) => value + 1);
                StopReasons[eventArgs.PartitionId] = eventArgs.Reason;

                return(Task.CompletedTask);
            };
        }
Exemplo n.º 36
0
        public async Task RetrieveAsync_WithStorageFile_ThrowsException_IfFileIsNull()
        {
            StorageManager storageManager = new StorageManager();

            await AssertEx.ThrowsExceptionAsync<ArgumentNullException>(() => storageManager.RetrieveAsync<TestData>(null));
        }
Exemplo n.º 37
0
 public DBFailoverKafkaConsumerTestEngine(KafKaConfig Config, string topic, StorageManager storageManager) : base(Config, topic, storageManager)
 {
 }
Exemplo n.º 38
0
		public override void OnRegister(IServiceProvider serviceProvider)
		{
			storages = (StorageManager)serviceProvider.GetService(typeof(StorageManager));
			sender = (IXmppSender)serviceProvider.GetService(typeof(IXmppSender));
			sessionManager = (XmppSessionManager)serviceProvider.GetService(typeof(XmppSessionManager));
		}
Exemplo n.º 39
0
 public void save()
 {
     StorageManager.storeOnDisk(StorageManager.LIFES, lifes);
     StorageManager.storeOnDisk(StorageManager.LAST_ACCESS, lastAccess);
 }
Exemplo n.º 40
0
        public void SM_TestReadWriteReservations()
        {
            string dataFile = "SM_TestData3.tpdb";

            if (File.Exists(dataFile))
            {
                File.Delete(dataFile);
            }

            // cerate the storage manager
            StorageManager mgr = StorageManager.CreateObject(dataFile);

            // TEST write
            Reservation[] data =
            {
                new Reservation(new Customer(), new RID[] { new RID(RID.Type.FLIGHT, "1234"), new RID(RID.Type.CAR, "Boston"),  new RID(RID.Type.ROOM, "Boston")   })
                ,                               new Reservation(new Customer(), new RID[]{ new RID(RID.Type.FLIGHT, "1234"), new RID(RID.Type.CAR, "Miami"),   new RID(RID.Type.ROOM, "New York") })
                ,                               new Reservation(new Customer(), new RID[]{ new RID(RID.Type.FLIGHT, "2345"), new RID(RID.Type.CAR, "Seattle"), new RID(RID.Type.ROOM, "Portland") })
                ,                               new Reservation(new Customer(), new RID[]{ new RID(RID.Type.FLIGHT, "3456"), new RID(RID.Type.CAR, "Seattle"), new RID(RID.Type.ROOM, "Boston")   })
                ,                               new Reservation(new Customer(), new RID[]{ new RID(RID.Type.FLIGHT, "4567"), new RID(RID.Type.CAR, "Miami"),   new RID(RID.Type.ROOM, "Boston")   })
            };

            // write the data
            WriteReservations(null, mgr, data, false);

            // read the data in a new transaction
            ReadReservations(null, mgr, data);

            // TEST write abort
            Reservation[] data2 =
            {
                new Reservation(data[0].Id, new RID[] { new RID(RID.Type.FLIGHT, "6767"), new RID(RID.Type.CAR, "Boston"),  new RID(RID.Type.ROOM, "Dallas")   })
                ,                           new Reservation(data[1].Id, new RID[]{ new RID(RID.Type.FLIGHT, "9933"), new RID(RID.Type.CAR, "Chicago"), new RID(RID.Type.ROOM, "New York") })
            };

            // write the data
            WriteReservations(null, mgr, data2, true);

            // read the data in a new transaction
            ReadReservations(null, mgr, data);

            // TEST update
            Reservation[] data3 = data;
            data3[0].Resources = data2[0].Resources;
            data3[1].Resources = data2[1].Resources;

            // write the data
            WriteReservations(null, mgr, data2, false);

            // read the data in a new transaction
            ReadReservations(null, mgr, data3);

            // TEST read non existing data
            Transaction context2    = new Transaction();
            Resource    missingItem = null;

            if (mgr.Read(context2, new RID(RID.Type.FLIGHT, "DOES NOT EXIST"), out missingItem) ||
                null != missingItem)
            {
                Assert.Fail("Test read of missing item failed.");
            }

            // TEST read resource list
            List <Customer> customerList = null;

            if (!mgr.Read(context2, out customerList))
            {
                Assert.Fail("Test read of customer list failed.");
            }
            foreach (var customer in data3.Select(c => c.Id))
            {
                if (!customerList.Contains(customer))
                {
                    Assert.Fail("{0}: Read resource list failed to retrieve [{1}].", context2.Id.ToString(), customer);
                }
            }

            mgr.Prepare(context2);
            mgr.Commit(context2);
        }
Exemplo n.º 41
0
 /// <summary>
 /// Save settings to disk.
 /// </summary>
 public void Save() => StorageManager <Options> .Save();
Exemplo n.º 42
0
        public Scene(RegionInfo regInfo, AgentCircuitManager authen,
                     CommunicationsManager commsMan, SceneCommunicationService sceneGridService,
                     StorageManager storeManager,
                     ModuleLoader moduleLoader, bool dumpAssetsToFile, bool physicalPrim,
                     bool SeeIntoRegionFromNeighbor, IConfigSource config, string simulatorVersion)
        {
            m_config = config;

            Random random = new Random();
            m_lastAllocatedLocalId = (uint)(random.NextDouble() * (double)(uint.MaxValue/2))+(uint)(uint.MaxValue/4);
            m_moduleLoader = moduleLoader;
            m_authenticateHandler = authen;
            CommsManager = commsMan;
            m_sceneGridService = sceneGridService;
            m_storageManager = storeManager;
            m_regInfo = regInfo;
            m_regionHandle = m_regInfo.RegionHandle;
            m_regionName = m_regInfo.RegionName;
            m_datastore = m_regInfo.DataStore;

            m_physicalPrim = physicalPrim;
            m_seeIntoRegionFromNeighbor = SeeIntoRegionFromNeighbor;

            m_eventManager = new EventManager();
            m_permissions = new ScenePermissions(this);

            m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this);
            m_asyncSceneObjectDeleter.Enabled = true;

            // Load region settings
            m_regInfo.RegionSettings = m_storageManager.DataStore.LoadRegionSettings(m_regInfo.RegionID);
            if (m_storageManager.EstateDataStore != null)
            {
                m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(m_regInfo.RegionID);
            }

            //Bind Storage Manager functions to some land manager functions for this scene
            EventManager.OnLandObjectAdded +=
                new EventManager.LandObjectAdded(m_storageManager.DataStore.StoreLandObject);
            EventManager.OnLandObjectRemoved +=
                new EventManager.LandObjectRemoved(m_storageManager.DataStore.RemoveLandObject);

            m_sceneGraph = new SceneGraph(this, m_regInfo);

            // If the scene graph has an Unrecoverable error, restart this sim.
            // Currently the only thing that causes it to happen is two kinds of specific
            // Physics based crashes.
            //
            // Out of memory
            // Operating system has killed the plugin
            m_sceneGraph.UnRecoverableError += RestartNow;

            RegisterDefaultSceneEvents();

            DumpAssetsToFile = dumpAssetsToFile;

            m_scripts_enabled = !RegionInfo.RegionSettings.DisableScripts;

            m_physics_enabled = !RegionInfo.RegionSettings.DisablePhysics;

            StatsReporter = new SimStatsReporter(this);
            StatsReporter.OnSendStatsResult += SendSimStatsPackets;
            StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats;

            StatsReporter.SetObjectCapacity(objectCapacity);

            m_simulatorVersion = simulatorVersion
                + " (OS " + Util.GetOperatingSystemInformation() + ")"
                + " ChilTasks:" + m_seeIntoRegionFromNeighbor.ToString()
                + " PhysPrim:" + m_physicalPrim.ToString();

            try
            {
                // Region config overrides global config
                //
                IConfig startupConfig = m_config.Configs["Startup"];

                //Animation states
                m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
                // TODO: Change default to true once the feature is supported
                m_usePreJump = startupConfig.GetBoolean("enableprejump", false);

                m_maxNonphys = startupConfig.GetFloat("NonPhysicalPrimMax", m_maxNonphys);
                if (RegionInfo.NonphysPrimMax > 0)
                {
                    m_maxNonphys = RegionInfo.NonphysPrimMax;
                }

                m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys);

                if (RegionInfo.PhysPrimMax > 0)
                {
                    m_maxPhys = RegionInfo.PhysPrimMax;
                }

                // Here, if clamping is requested in either global or
                // local config, it will be used
                //
                m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", m_clampPrimSize);
                if (RegionInfo.ClampPrimSize)
                {
                    m_clampPrimSize = true;
                }

                m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries);
                m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings);
                m_dontPersistBefore =
                  startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
                m_dontPersistBefore *= 10000000;
                m_persistAfter =
                  startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
                m_persistAfter *= 10000000;

                m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "DotNetEngine");

                m_maxPrimsPerFrame = startupConfig.GetInt("MaxPrimsPerFrame", 200);
                IConfig packetConfig = m_config.Configs["PacketPool"];
                if (packetConfig != null)
                {
                    PacketPool.Instance.RecyclePackets = packetConfig.GetBoolean("RecyclePackets", true);
                    PacketPool.Instance.RecycleDataBlocks = packetConfig.GetBoolean("RecycleDataBlocks", true);
                }

                m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl);
            }
            catch
            {
                m_log.Warn("[SCENE]: Failed to load StartupConfig");
            }
        }
Exemplo n.º 43
0
 public void load()
 {
     setSkin(StorageManager.loadStringFromDisk(StorageManager.SKIN));
     setId(StorageManager.loadStringFromDisk(StorageManager.ID));
 }
Exemplo n.º 44
0
        public Scene(RegionInfo regInfo, AgentCircuitManager authen,
                     SceneCommunicationService sceneGridService,
                     StorageManager storeManager,
                     ModuleLoader moduleLoader, bool dumpAssetsToFile, bool physicalPrim,
                     bool SeeIntoRegionFromNeighbor, IConfigSource config, string simulatorVersion)
        {
            m_config = config;

            Random random = new Random();
            
            BordersLocked = true;

            Border northBorder = new Border();
            northBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, (int)Constants.RegionSize);  //<---
            northBorder.CrossDirection = Cardinals.N;
            NorthBorders.Add(northBorder);

            Border southBorder = new Border();
            southBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, 0);    //--->
            southBorder.CrossDirection = Cardinals.S;
            SouthBorders.Add(southBorder);

            Border eastBorder = new Border();
            eastBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, (int)Constants.RegionSize);   //<---
            eastBorder.CrossDirection = Cardinals.E;
            EastBorders.Add(eastBorder);

            Border westBorder = new Border();
            westBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, 0);     //--->
            westBorder.CrossDirection = Cardinals.W;
            WestBorders.Add(westBorder);

            BordersLocked = false;

            m_lastAllocatedLocalId = (uint)(random.NextDouble() * (double)(uint.MaxValue/2))+(uint)(uint.MaxValue/4);
            m_moduleLoader = moduleLoader;
            m_authenticateHandler = authen;
            m_sceneGridService = sceneGridService;
            m_storageManager = storeManager;
            m_regInfo = regInfo;
            m_regionHandle = m_regInfo.RegionHandle;
            m_regionName = m_regInfo.RegionName;
            m_datastore = m_regInfo.DataStore;
            m_lastUpdate = Util.EnvironmentTickCount();

            m_physicalPrim = physicalPrim;
            m_seeIntoRegionFromNeighbor = SeeIntoRegionFromNeighbor;

            m_eventManager = new EventManager();
            m_permissions = new ScenePermissions(this);

            m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this);
            m_asyncSceneObjectDeleter.Enabled = true;

            #region Region Settings

            // Load region settings
            m_regInfo.RegionSettings = m_storageManager.DataStore.LoadRegionSettings(m_regInfo.RegionID);
            if (m_storageManager.EstateDataStore != null)
            {
                m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(m_regInfo.RegionID, false);
                if (m_regInfo.EstateSettings.EstateID == 0) // No record at all
                {
                    MainConsole.Instance.Output("Your region is not part of an estate.");
                    while (true)
                    {
                        string response = MainConsole.Instance.CmdPrompt("Do you wish to join an existing estate?", "no", new List<string>() {"yes", "no"});
                        if (response == "no")
                        {
                            // Create a new estate
                            m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(m_regInfo.RegionID, true);

                            m_regInfo.EstateSettings.EstateName = MainConsole.Instance.CmdPrompt("New estate name", m_regInfo.EstateSettings.EstateName);
                            m_regInfo.EstateSettings.Save();
                            break;
                        }
                        else
                        {
                            response = MainConsole.Instance.CmdPrompt("Estate name to join", "None");
                            if (response == "None")
                                continue;

                            List<int> estateIDs = m_storageManager.EstateDataStore.GetEstates(response);
                            if (estateIDs.Count < 1)
                            {
                                MainConsole.Instance.Output("The name you have entered matches no known estate. Please try again");
                                continue;
                            }

                            int estateID = estateIDs[0];

                            m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(estateID);

                            if (m_storageManager.EstateDataStore.LinkRegion(m_regInfo.RegionID, estateID))
                                break;

                            MainConsole.Instance.Output("Joining the estate failed. Please try again.");
                        }
                    }
                }
            }

            #endregion Region Settings

            MainConsole.Instance.Commands.AddCommand("region", false, "reload estate",
                                          "reload estate",
                                          "Reload the estate data", HandleReloadEstate);

            //Bind Storage Manager functions to some land manager functions for this scene
            EventManager.OnLandObjectAdded +=
                new EventManager.LandObjectAdded(m_storageManager.DataStore.StoreLandObject);
            EventManager.OnLandObjectRemoved +=
                new EventManager.LandObjectRemoved(m_storageManager.DataStore.RemoveLandObject);

            m_sceneGraph = new SceneGraph(this, m_regInfo);

            // If the scene graph has an Unrecoverable error, restart this sim.
            // Currently the only thing that causes it to happen is two kinds of specific
            // Physics based crashes.
            //
            // Out of memory
            // Operating system has killed the plugin
            m_sceneGraph.UnRecoverableError += RestartNow;

            RegisterDefaultSceneEvents();

            DumpAssetsToFile = dumpAssetsToFile;

            m_scripts_enabled = !RegionInfo.RegionSettings.DisableScripts;

            m_physics_enabled = !RegionInfo.RegionSettings.DisablePhysics;

            StatsReporter = new SimStatsReporter(this);
            StatsReporter.OnSendStatsResult += SendSimStatsPackets;
            StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats;

            StatsReporter.SetObjectCapacity(objectCapacity);

            // Old
            /*
            m_simulatorVersion = simulatorVersion
                + " (OS " + Util.GetOperatingSystemInformation() + ")"
                + " ChilTasks:" + m_seeIntoRegionFromNeighbor.ToString()
                + " PhysPrim:" + m_physicalPrim.ToString();
            */

            m_simulatorVersion = simulatorVersion + " (" + Util.GetRuntimeInformation() + ")";

            #region Region Config

            try
            {
                // Region config overrides global config
                //
                IConfig startupConfig = m_config.Configs["Startup"];

                //Animation states
                m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
                // TODO: Change default to true once the feature is supported
                m_usePreJump = startupConfig.GetBoolean("enableprejump", false);

                m_maxNonphys = startupConfig.GetFloat("NonPhysicalPrimMax", m_maxNonphys);
                if (RegionInfo.NonphysPrimMax > 0)
                {
                    m_maxNonphys = RegionInfo.NonphysPrimMax;
                }

                m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys);

                if (RegionInfo.PhysPrimMax > 0)
                {
                    m_maxPhys = RegionInfo.PhysPrimMax;
                }

                // Here, if clamping is requested in either global or
                // local config, it will be used
                //
                m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", m_clampPrimSize);
                if (RegionInfo.ClampPrimSize)
                {
                    m_clampPrimSize = true;
                }

                m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries);
                m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings);
                m_dontPersistBefore =
                  startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
                m_dontPersistBefore *= 10000000;
                m_persistAfter =
                  startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
                m_persistAfter *= 10000000;

                m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "XEngine");

                IConfig packetConfig = m_config.Configs["PacketPool"];
                if (packetConfig != null)
                {
                    PacketPool.Instance.RecyclePackets = packetConfig.GetBoolean("RecyclePackets", true);
                    PacketPool.Instance.RecycleDataBlocks = packetConfig.GetBoolean("RecycleDataBlocks", true);
                }

                m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl);

                #region BinaryStats

                try
                {
                    IConfig statConfig = m_config.Configs["Statistics.Binary"];
                    if (statConfig.Contains("enabled") && statConfig.GetBoolean("enabled"))
                    {
                        if (statConfig.Contains("collect_region_stats"))
                        {
                            if (statConfig.GetBoolean("collect_region_stats"))
                            {
                                // if enabled, add us to the event. If not enabled, I won't get called
                                StatsReporter.OnSendStatsResult += LogSimStats;
                            }
                        }
                        if (statConfig.Contains("region_stats_period_seconds"))
                        {
                            m_statLogPeriod = TimeSpan.FromSeconds(statConfig.GetInt("region_stats_period_seconds"));
                        }
                        if (statConfig.Contains("stats_dir"))
                        {
                            m_statsDir = statConfig.GetString("stats_dir");
                        }
                    }
                }
                catch
                {
                    // if it doesn't work, we don't collect anything
                }

                #endregion BinaryStats
            }
            catch
            {
                m_log.Warn("[SCENE]: Failed to load StartupConfig");
            }

            #endregion Region Config

            #region Interest Management

            if (m_config != null)
            {
                IConfig interestConfig = m_config.Configs["InterestManagement"];
                if (interestConfig != null)
                {
                    string update_prioritization_scheme = interestConfig.GetString("UpdatePrioritizationScheme", "Time").Trim().ToLower();

                    try
                    {
                        m_priorityScheme = (UpdatePrioritizationSchemes)Enum.Parse(typeof(UpdatePrioritizationSchemes), update_prioritization_scheme, true);
                    }
                    catch (Exception)
                    {
                        m_log.Warn("[PRIORITIZER]: UpdatePrioritizationScheme was not recognized, setting to default prioritizer Time");
                        m_priorityScheme = UpdatePrioritizationSchemes.Time;
                    }

                    m_reprioritizationEnabled = interestConfig.GetBoolean("ReprioritizationEnabled", true);
                    m_reprioritizationInterval = interestConfig.GetDouble("ReprioritizationInterval", 5000.0);
                    m_rootReprioritizationDistance = interestConfig.GetDouble("RootReprioritizationDistance", 10.0);
                    m_childReprioritizationDistance = interestConfig.GetDouble("ChildReprioritizationDistance", 20.0);
                }
            }

            m_log.Info("[SCENE]: Using the " + m_priorityScheme + " prioritization scheme");

            #endregion Interest Management
        }
Exemplo n.º 45
0
 /// <summary>
 /// Constructor used to set the manager reference
 /// </summary>
 internal StorageActivity(StorageManager manager)
 {
     Manager = manager;
     _client = new StorageClient(manager.SubscriptionId, manager.ManagementCertificate);
 }
Exemplo n.º 46
0
 public class NodeController : ODataControllerBase <Node> { public NodeController() : base(StorageManager.Storage <Node>())
                                                            {
                                                            }
Exemplo n.º 47
0
        private static void ReadResources(Transaction context, StorageManager storage, Resource[] data)
        {
            bool createTransaction = (null == context);
            if (createTransaction)
            {
                context = new Transaction();
            }

            foreach (var item in data)
            {
                Resource output = null;
                if (!storage.Read(context, item.Id, out output))
                {
                    Assert.Fail("{0}: Read of [{1}] was un-successful.", context.Id.ToString(), item.Id.ToString());
                }
                Assert.AreEqual<Resource>(item, output, "{0}: Read was un-successful.", context.Id.ToString());
            }

            if (createTransaction)
            {
                storage.Prepare(context);
                storage.Commit(context);
            }
        }
Exemplo n.º 48
0
 public class CrimeController : ODataControllerBase <Crime> { public CrimeController() : base(StorageManager.Storage <Crime>())
                                                              {
                                                              }
Exemplo n.º 49
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                int resultId = Int32.Parse(Request["ResultId"]);
                if (resultId == CommunicationService.StartRssFeedConstant)
                {
                    InnerText = "<h1>Benvenuto</h1>";
                }
                else
                {
                    StorageManager manager = new StorageManager();
                    Result         result  = manager.getEntityByID <Result>(resultId);


                    if (result != null)
                    {
                        Publication pub = result.Publication;
                        if (pub == null)
                        {
                            pub = result.CompilationRequest.Publication;
                        }

                        Uri    uri   = new Uri(pub.URIUpload);
                        string token = uri.Query.Substring(7);
                        if (pub.publicationID != Int32.Parse(Request["PubId"]) ||
                            !(Request["token"] != null && token.Equals(Request["token"])))
                        {
                            Response.StatusCode = 400;
                            Response.Write("HTTP 400 BAD REQUEST");
                            Response.End();
                            return;
                        }
                        StringBuilder            builder = new StringBuilder();
                        System.Xml.Linq.XElement xmlRes  = result.xmlResult;
                        builder.Append("<h1>" + XmlConvert.DecodeName(xmlRes.Name.LocalName) + "</h1>");
                        System.Collections.Generic.IEnumerable <XElement> elements = xmlRes.Elements();
                        foreach (System.Xml.Linq.XElement el in elements)
                        {
                            builder.Append("<div>");
                            builder.Append("<h3 class=\"step\">" + XmlConvert.DecodeName(el.Name.LocalName) + "</h3>");
                            System.Collections.Generic.IEnumerable <XElement> childsEnum = el.Elements();
                            foreach (System.Xml.Linq.XElement quest in childsEnum)
                            {
                                builder.Append("<p> <span class=\"question\">" + XmlConvert.DecodeName(quest.Name.LocalName) +
                                               " = </span>  <span class=\"answer\">" + XmlConvert.DecodeName(quest.Value) + "</span> </p>");
                            }
                            builder.Append("</div>");
                        }
                        InnerText = builder.ToString();
                    }
                    else
                    {
                        Response.StatusCode = 400;
                        Response.Write("HTTP 400 BAD REQUEST");
                        Response.End();
                    }
                }
            }
            catch (Exception ex)
            {
                if (Response.StatusCode != 400)
                {
                    Response.StatusCode = 400;
                    Response.Write("HTTP 400 BAD REQUEST");
                    Response.End();
                }
            }
        }
Exemplo n.º 50
0
 public class AgentController : ODataControllerBase <Agent> { public AgentController() : base(StorageManager.Storage <Agent>())
                                                              {
                                                              }
Exemplo n.º 51
0
 /// <summary>
 /// Constructor used to set the manager reference 
 /// </summary>
 internal StorageActivity(StorageManager manager)
 {
     Manager = manager;
 }
Exemplo n.º 52
0
        private async void StorageTester()
        {
            StorageManager manager = new StorageManager();

            var path = "/root/child1/child2/test.txt";

            await manager.SaveDataAsync(path, new string[] { "poney" });

            try
            {
                var data = await manager.LoadDataAsync<string[]>(path);
            }
            catch
            {

            }
            var folder = await manager.GetDataFoldersAsync("/root/child1");

        }
Exemplo n.º 53
0
        public override object ParseFromStack(Data[] stack, int stackIndex, Memory <byte> memory, StorageManager storageManager)
        {
            // If we exceeded our stack size
            if (stack.Length <= stackIndex)
            {
                throw new VarResolvingException("Could not parse variable from stack using reference type method because the stack is not populated up to the target index.");
            }

            // Obtain our pointer data from the stack.
            Memory <byte> stackEntryData = stack[stackIndex].GetBytes();

            // Switch on our location
            switch (VariableLocation)
            {
            case VarLocation.Memory:
                // Parse our pointer from the bytes.
                BigInteger pointer = BigIntegerConverter.GetBigInteger(stackEntryData.Span, false, UInt256.SIZE);

                // Parse our dereferenced value from memory. (Using our stack data as a data offset)
                return(ParseDereferencedFromMemory(memory, (int)pointer));

            case VarLocation.Storage:
                // Parse our stack data as a storage key
                StorageLocation storageLocation = new StorageLocation(stackEntryData, 0);

                // Parse our value from storage. (Using our stack data as a storage key)
                return(ParseFromStorage(storageManager, storageLocation));

            default:
                throw new VarResolvingException("Could not parse variable from stack using reference type because the provided underlying location is invalid.");
            }
        }
Exemplo n.º 54
0
        public override void LoadForm()
        {
            if (npc == null)
            {
                return;
            }

            this.SuspendForm();
            NotificationInitialize();
            npcImage.Image    = npc.GetImage();
            creatureName.Text = npc.city.ToTitle();
            Font f = StyleManager.FontList[0];

            for (int i = 0; i < StyleManager.FontList.Count; i++)
            {
                Font font = StyleManager.FontList[i];
                Size size = TextRenderer.MeasureText(this.creatureName.Text, font);
                if (size.Width < creatureName.MaximumSize.Width && size.Height < creatureName.MaximumSize.Height)
                {
                    f = font;
                }
                else
                {
                    break;
                }
            }
            this.creatureName.Font = f;

            for (int i = 0; i < headers.Length; i++)
            {
                objectList[i] = new List <TibiaObject>();
            }
            extraAttributes[0]        = "Value";
            attributeFunctions[0]     = SellPrice;
            attributeSortFunctions[0] = SellSort;
            removedLists[0]           = new List <string> {
                "Value"
            };
            foreach (ItemSold itemSold in npc.sellItems)
            {
                objectList[0].Add(new LazyTibiaObject {
                    id = itemSold.itemid, type = TibiaObjectType.Item
                });
            }
            extraAttributes[1]        = "Price";
            attributeFunctions[1]     = BuyPrice;
            attributeSortFunctions[1] = BuySort;
            removedLists[1]           = new List <string> {
                "Value"
            };
            foreach (ItemSold itemSold in npc.buyItems)
            {
                objectList[1].Add(new LazyTibiaObject {
                    id = itemSold.itemid, type = TibiaObjectType.Item
                });
            }
            extraAttributes[2]        = "Vocation";
            attributeFunctions[2]     = SpellVoc;
            attributeSortFunctions[2] = SpellSort;
            removedLists[2]           = new List <string> {
                "Words"
            };
            foreach (SpellTaught spellTaught in npc.spellsTaught)
            {
                objectList[2].Add(new LazyTibiaObject {
                    id = spellTaught.spellid, type = TibiaObjectType.Spell
                });
            }
            // Transport
            foreach (Transport transport in npc.transportOffered)
            {
                objectList[3].Add(transport);
            }
            // Quests Involved In
            foreach (Quest q in npc.involvedQuests)
            {
                objectList[4].Add(q);
            }

            base_y = this.Size.Height;
            int x = 5;

            for (int i = 0; i < headers.Length; i++)
            {
                if (objectList[i].Count > 0)
                {
                    Label label = new Label();
                    label.Text        = headers[i];
                    label.Location    = new Point(x, base_y);
                    label.ForeColor   = StyleManager.NotificationTextColor;
                    label.BackColor   = Color.Transparent;
                    label.Font        = StyleManager.TextFont;
                    label.Size        = new Size(90, 25);
                    label.TextAlign   = ContentAlignment.MiddleCenter;
                    label.BorderStyle = BorderStyle.FixedSingle;
                    label.Name        = i.ToString();
                    label.Click      += toggleObjectDisplay;
                    objectControls[i] = label;
                    this.Controls.Add(label);
                    if (currentControlList < 0 || currentControlList > headers.Length)
                    {
                        currentControlList = i;
                    }
                    x += 90;
                }
                else
                {
                    objectControls[i] = null;
                }
            }
            base_y += 25;

            Map m = StorageManager.getMap(npc.pos.z);

            mapBox.map      = m;
            mapBox.mapImage = null;

            Target t = new Target();

            t.coordinate = new Coordinate(npc.pos);
            t.image      = npc.GetImage();
            t.size       = 20;

            mapBox.targets.Add(t);
            mapBox.sourceWidth   = mapBox.Width;
            mapBox.mapCoordinate = new Coordinate(npc.pos);
            mapBox.zCoordinate   = npc.pos.z;
            mapBox.UpdateMap();

            mapBox.Click -= c_Click;

            this.mapUpLevel.Image    = StyleManager.GetImage("mapup.png");
            this.mapUpLevel.Click   -= c_Click;
            this.mapUpLevel.Click   += mapUpLevel_Click;
            this.mapDownLevel.Image  = StyleManager.GetImage("mapdown.png");
            this.mapDownLevel.Click -= c_Click;
            this.mapDownLevel.Click += mapDownLevel_Click;

            refresh();
            base.NotificationFinalize();
            this.ResumeForm();
        }
Exemplo n.º 55
0
        public MailAttachmentData AttachFile(int tenant, string user, MailMessageData message,
                                             string name, Stream inputStream, long contentLength, string contentType = null, bool needSaveToTemp = false)
        {
            if (message == null)
            {
                throw new AttachmentsException(AttachmentsException.Types.MessageNotFound, "Message not found.");
            }

            if (string.IsNullOrEmpty(message.StreamId))
            {
                throw new AttachmentsException(AttachmentsException.Types.MessageNotFound, "StreamId is empty.");
            }

            var messageId = message.Id;

            var engine = new EngineFactory(tenant, user);

            var totalSize =
                engine.AttachmentEngine.GetAttachmentsSize(new ConcreteMessageAttachmentsExp(messageId, tenant, user));

            totalSize += contentLength;

            if (totalSize > Defines.ATTACHMENTS_TOTAL_SIZE_LIMIT)
            {
                throw new AttachmentsException(AttachmentsException.Types.TotalSizeExceeded,
                                               "Total size of all files exceeds limit!");
            }

            var fileNumber =
                engine.AttachmentEngine.GetAttachmentNextFileNumber(new ConcreteMessageAttachmentsExp(messageId, tenant,
                                                                                                      user));

            var attachment = new MailAttachmentData
            {
                fileName       = name,
                contentType    = string.IsNullOrEmpty(contentType) ? MimeMapping.GetMimeMapping(name) : contentType,
                needSaveToTemp = needSaveToTemp,
                fileNumber     = fileNumber,
                size           = contentLength,
                data           = inputStream.ReadToEnd(),
                streamId       = message.StreamId,
                tenant         = tenant,
                user           = user,
                mailboxId      = message.MailboxId
            };

            engine.QuotaEngine.QuotaUsedAdd(contentLength);

            try
            {
                var storage = new StorageManager(tenant, user);
                storage.StoreAttachmentWithoutQuota(attachment);
            }
            catch
            {
                engine.QuotaEngine.QuotaUsedDelete(contentLength);
                throw;
            }

            if (!needSaveToTemp)
            {
                int attachCount;

                using (var daoFactory = new DaoFactory())
                {
                    var db = daoFactory.DbManager;

                    using (var tx = db.BeginTransaction())
                    {
                        var daoAttachment = daoFactory.CreateAttachmentDao(tenant, user);

                        attachment.fileId = daoAttachment.SaveAttachment(attachment.ToAttachmnet(messageId));

                        attachCount = daoAttachment.GetAttachmentsCount(
                            new ConcreteMessageAttachmentsExp(messageId, tenant, user));

                        var daoMailInfo = daoFactory.CreateMailInfoDao(tenant, user);

                        daoMailInfo.SetFieldValue(
                            SimpleMessagesExp.CreateBuilder(tenant, user)
                            .SetMessageId(messageId)
                            .Build(),
                            MailTable.Columns.AttachCount,
                            attachCount);

                        engine.ChainEngine.UpdateMessageChainAttachmentsFlag(daoFactory, tenant, user, messageId);

                        tx.Commit();
                    }
                }

                if (attachCount == 1)
                {
                    var data = new MailWrapper
                    {
                        HasAttachments = true
                    };

                    engine.IndexEngine.Update(data, s => s.Where(m => m.Id, messageId), wrapper => wrapper.HasAttachments);
                }
            }

            return(attachment);
        }
Exemplo n.º 56
0
 /// <summary>
 /// Constructor used to set the manager reference 
 /// </summary>
 internal StorageActivity(StorageManager manager)
 {
     Manager = manager;
     _client = new StorageClient(manager.SubscriptionId, manager.ManagementCertificate);
 }
Exemplo n.º 57
0
        public void SM_TestReadWriteResource()
        {
            string dataFile = "SM_TestData2.tpdb";

            if (File.Exists(dataFile))
            {
                File.Delete(dataFile);
            }

            // cerate the storage manager
            StorageManager mgr = StorageManager.CreateObject(dataFile);

            // TEST write
            Resource[] data =
            {
                new Resource(new RID(RID.Type.CAR, "Seattle"),                                          10,                                  45)
                ,                                  new Resource(new RID(RID.Type.CAR,    "Boston"),         10, 45)
                ,                                  new Resource(new RID(RID.Type.CAR,    "San Diego"),      10, 45)
                ,                                  new Resource(new RID(RID.Type.FLIGHT, "New York"),       10, 45)
                ,                                  new Resource(new RID(RID.Type.CAR,    "Dallas"),         10, 45)
                ,                                  new Resource(new RID(RID.Type.CAR,    "Houston"),        10, 45)
                ,                                  new Resource(new RID(RID.Type.ROOM,   "Toronto"),        10, 45)
                ,                                  new Resource(new RID(RID.Type.CAR,    "Montreal"),       10, 45)
                ,                                  new Resource(new RID(RID.Type.FLIGHT, "Vancouver"),      10, 45)
                ,                                  new Resource(new RID(RID.Type.CAR,    "Ottawa"),         10, 45)
                ,                                  new Resource(new RID(RID.Type.ROOM,   "Portland"),       10, 45)
                ,                                  new Resource(new RID(RID.Type.CAR,    "New Jersey"),     10, 45)
                ,                                  new Resource(new RID(RID.Type.ROOM,   "Salt Lake City"), 10, 45)
                ,                                  new Resource(new RID(RID.Type.CAR,    "Paris"),          10, 45)
            };

            // write the data
            WriteResources(null, mgr, data, false);

            // read the data in a new transaction
            ReadResources(null, mgr, data);

            // TEST write abort
            Resource[] data2 =
            {
                new Resource(data[0].Id,                      11,                        21)
                ,                        new Resource(data[1].Id,12, 22)
            };

            // write the data
            WriteResources(null, mgr, data2, true);

            // read the data in a new transaction
            ReadResources(null, mgr, data);

            // TEST update
            Resource[] data3 = data;
            data3[0].setCount(data2[0].getCount());
            data3[0].setPrice(data2[0].getPrice());
            data3[1].setCount(data2[1].getCount());
            data3[1].setPrice(data2[1].getPrice());

            // write the data
            WriteResources(null, mgr, data2, false);

            // read the data in a new transaction
            ReadResources(null, mgr, data3);

            // TEST read non existing data
            Resource    missingItem = null;
            Transaction context2    = new Transaction();

            if (mgr.Read(context2, new RID(RID.Type.FLIGHT, "DOES NOT EXIST"), out missingItem) ||
                null != missingItem)
            {
                Assert.Fail("Test read of missing item failed.");
            }

            // TEST read resource list
            List <Resource> carList = null;

            if (!mgr.Read(context2, RID.Type.CAR, out carList))
            {
                Assert.Fail("Test read of car list failed.");
            }
            foreach (var car in data3.Where(c => c.Id.getType() == RID.Type.CAR))
            {
                if (!carList.Contains(car))
                {
                    Assert.Fail("{0}: Read resource list failed to retrieve [{1}].", context2.Id.ToString(), car);
                }
            }

            mgr.Prepare(context2);
            mgr.Commit(context2);
        }
        public async Task RetrieveAsync_WithStorageFile_ThrowsException_IfFileIsNull()
        {
            StorageManager storageManager = new StorageManager();

            var e = await Assert.ThrowsAsync<ArgumentNullException>(() => storageManager.RetrieveAsync<TestData>(null));

            Assert.Equal("Value cannot be null.\r\nParameter name: file", e.Message);
            Assert.Equal("file", e.ParamName);
        }
Exemplo n.º 59
0
		public UserManager(StorageManager storageManager)
		{
			if (storageManager == null) throw new ArgumentNullException("storageManager");
			this.storageManager = storageManager;
		}
        public async Task RetrieveAsync_WithStorageFolder_ThrowsException_IfFolderIsNull()
        {
            StorageManager storageManager = new StorageManager();

            StorageFolder folder = null;
            string name = GetTestFilename();
            var e = await Assert.ThrowsAsync<ArgumentNullException>(() => storageManager.RetrieveAsync<TestData>(folder, name));

            Assert.Equal("Value cannot be null.\r\nParameter name: folder", e.Message);
            Assert.Equal("folder", e.ParamName);
        }