示例#1
0
 protected override void OnDisappearing()
 {
     base.OnDisappearing();
     listView.ItemsSource = null;
     _realm.Dispose();
     _realm = null;
 }
示例#2
0
        public static void CreateCharacter(Realm.Characters.Character character)
        {
            lock (DatabaseHandler.ConnectionLocker)
            {
                var sqlText = "INSERT INTO dyn_characters VALUES(@id, @name, @level, @class, @sex, @color, @color2, @color3, @mapinfos, @stats, @items, @spells, @exp)";
                var sqlCommand = new MySqlCommand(sqlText, DatabaseHandler.Connection);

                var P = sqlCommand.Parameters;

                P.Add(new MySqlParameter("@id", character.ID));
                P.Add(new MySqlParameter("@name", character.Name));
                P.Add(new MySqlParameter("@level", character.Level));
                P.Add(new MySqlParameter("@class", character.Class));
                P.Add(new MySqlParameter("@sex", character.Sex));
                P.Add(new MySqlParameter("@color", character.Color));
                P.Add(new MySqlParameter("@color2", character.Color2));
                P.Add(new MySqlParameter("@color3", character.Color3));
                P.Add(new MySqlParameter("@mapinfos", character.MapID + "," + character.MapCell + "," + character.Dir));
                P.Add(new MySqlParameter("@stats", character.SqlStats()));
                P.Add(new MySqlParameter("@items", ""));
                P.Add(new MySqlParameter("@spells", ""));
                P.Add(new MySqlParameter("@exp", 0));

                sqlCommand.ExecuteNonQuery();

                character.isNewCharacter = false;
            }
        }
        /// <summary>
        /// Gets the Identifier to use for the Claimed Identifier and Local Identifier of
        /// an outgoing positive assertion.
        /// </summary>
        /// <param name="localIdentifier">The OP local identifier for the authenticating user.</param>
        /// <param name="relyingPartyRealm">The realm of the relying party receiving the assertion.</param>
        /// <returns>
        /// A valid, discoverable OpenID Identifier that should be used as the value for the
        /// openid.claimed_id and openid.local_id parameters.  Must not be null.
        /// </returns>
        Uri IDirectedIdentityIdentifierProvider.GetIdentifier(Identifier localIdentifier, Realm relyingPartyRealm)
        {
            Contract.Requires(localIdentifier != null);
            Contract.Requires(relyingPartyRealm != null);

            throw new NotImplementedException();
        }
		protected internal override void onCreate(Bundle savedInstanceState)
		{
			base.onCreate(savedInstanceState);

			// Generate a key
			// IMPORTANT! This is a silly way to generate a key. It is also never stored.
			// For proper key handling please consult:
			// * https://developer.android.com/training/articles/keystore.html
			// * http://nelenkov.blogspot.dk/2012/05/storing-application-secrets-in-androids.html
			sbyte[] key = new sbyte[64];
			(new SecureRandom()).NextBytes(key);
			RealmConfiguration realmConfiguration = (new RealmConfiguration.Builder(this)).encryptionKey(key).build();

			// Start with a clean slate every time
			Realm.deleteRealm(realmConfiguration);

			// Open the Realm with encryption enabled
			realm = Realm.getInstance(realmConfiguration);

			// Everything continues to work as normal except for that the file is encrypted on disk
			realm.beginTransaction();
			Person person = realm.createObject(typeof(Person));
			person.Name = "Happy Person";
			person.Age = 14;
			realm.commitTransaction();

			person = realm.@where(typeof(Person)).findFirst();
			Log.i(TAG, string.Format("Person name: {0}", person.Name));
		}
示例#5
0
		void parameterizedProgrammaticOPIdentifierTest(Identifier opIdentifier, ProtocolVersion version,
			Identifier claimedUrl, AuthenticationRequestMode requestMode,
			AuthenticationStatus expectedResult, bool provideStore) {

			var rp = TestSupport.CreateRelyingParty(provideStore ? TestSupport.RelyingPartyStore : null, null, null);

			var returnTo = TestSupport.GetFullUrl(TestSupport.ConsumerPage);
			var realm = new Realm(TestSupport.GetFullUrl(TestSupport.ConsumerPage).AbsoluteUri);
			var request = rp.CreateRequest(opIdentifier, realm, returnTo);
			request.Mode = requestMode;

			var rpResponse = TestSupport.CreateRelyingPartyResponseThroughProvider(request,
				opReq => {
					opReq.IsAuthenticated = expectedResult == AuthenticationStatus.Authenticated;
					if (opReq.IsAuthenticated.Value) {
						opReq.ClaimedIdentifier = claimedUrl;
					}
				});
			Assert.AreEqual(expectedResult, rpResponse.Status);
			if (rpResponse.Status == AuthenticationStatus.Authenticated) {
				Assert.AreEqual(claimedUrl, rpResponse.ClaimedIdentifier);
			} else if (rpResponse.Status == AuthenticationStatus.SetupRequired) {
				Assert.IsNull(rpResponse.ClaimedIdentifier);
				Assert.IsNull(rpResponse.FriendlyIdentifierForDisplay);
				Assert.IsNull(rpResponse.Exception);
				Assert.IsInstanceOfType(typeof(ISetupRequiredAuthenticationResponse), rpResponse);
				Assert.AreEqual(opIdentifier.ToString(), ((ISetupRequiredAuthenticationResponse)rpResponse).ClaimedOrProviderIdentifier.ToString());
			}
		}
示例#6
0
 public void ImplicitConversionToStringTests()
 {
     Realm realm = new Realm("http://host/");
     string realmString = realm;
     Assert.AreEqual("http://host/", realmString);
     realm = null;
     realmString = realm;
     Assert.IsNull(realmString);
 }
        public JournalEntriesViewModel()
        {
            _realm = Realm.GetInstance();

            Entries = _realm.All<JournalEntry>();

            AddEntryCommand = new Command(AddEntry);
            DeleteEntryCommand = new Command<JournalEntry>(DeleteEntry);
        }
		public override void onStart()
		{
			base.onStart();
			// Create Realm instance for the UI thread
			realm = Realm.DefaultInstance;
			allSortedDots = realm.@where(typeof(Dot)).between("x", 25, 75).between("y", 0, 50).findAllSortedAsync("x", RealmResults.SORT_ORDER_ASCENDING, "y", RealmResults.SORT_ORDER_DESCENDING);
			dotAdapter.updateList(allSortedDots);
			allSortedDots.addChangeListener(this);
		}
		protected internal override void onCreate(Bundle savedInstanceState)
		{
			base.onCreate(savedInstanceState);
			ContentView = R.layout.activity_realm_example;

			RealmConfiguration realmConfiguration = (new RealmConfiguration.Builder(this)).build();
			Realm.deleteRealm(realmConfiguration);
			realm = Realm.getInstance(realmConfiguration);
		}
		/// <summary>
		/// Generates AJAX-ready authentication requests that can satisfy the requirements of some OpenID Identifier.
		/// </summary>
		/// <param name="userSuppliedIdentifier">The Identifier supplied by the user.  This may be a URL, an XRI or i-name.</param>
		/// <param name="realm">The shorest URL that describes this relying party web site's address.
		/// For example, if your login page is found at https://www.example.com/login.aspx,
		/// your realm would typically be https://www.example.com/.</param>
		/// <param name="returnToUrl">The URL of the login page, or the page prepared to receive authentication
		/// responses from the OpenID Provider.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <returns>
		/// A sequence of authentication requests, any of which constitutes a valid identity assertion on the Claimed Identifier.
		/// Never null, but may be empty.
		/// </returns>
		/// <remarks>
		///   <para>Any individual generated request can satisfy the authentication.
		/// The generated requests are sorted in preferred order.
		/// Each request is generated as it is enumerated to.  Associations are created only as
		///   <see cref="IAuthenticationRequest.GetRedirectingResponseAsync" /> is called.</para>
		///   <para>No exception is thrown if no OpenID endpoints were discovered.
		/// An empty enumerable is returned instead.</para>
		/// </remarks>
		public override async Task<IEnumerable<IAuthenticationRequest>> CreateRequestsAsync(Identifier userSuppliedIdentifier, Realm realm, Uri returnToUrl, CancellationToken cancellationToken) {
			var requests = await base.CreateRequestsAsync(userSuppliedIdentifier, realm, returnToUrl, cancellationToken);
			var results = new List<IAuthenticationRequest>();

			// Alter the requests so that have AJAX characteristics.
			// Some OPs may be listed multiple times (one with HTTPS and the other with HTTP, for example).
			// Since we're gathering OPs to try one after the other, just take the first choice of each OP
			// and don't try it multiple times.
			requests = requests.Distinct(DuplicateRequestedHostsComparer.Instance);

			// Configure each generated request.
			int reqIndex = 0;
			foreach (var req in requests) {
				// Inform ourselves in return_to that we're in a popup.
				req.SetUntrustedCallbackArgument(OpenIdRelyingPartyControlBase.UIPopupCallbackKey, "1");

				if (req.DiscoveryResult.IsExtensionSupported<UIRequest>()) {
					// Inform the OP that we'll be using a popup window consistent with the UI extension.
					req.AddExtension(new UIRequest());

					// Provide a hint for the client javascript about whether the OP supports the UI extension.
					// This is so the window can be made the correct size for the extension.
					// If the OP doesn't advertise support for the extension, the javascript will use
					// a bigger popup window.
					req.SetUntrustedCallbackArgument(OpenIdRelyingPartyControlBase.PopupUISupportedJSHint, "1");
				}

				req.SetUntrustedCallbackArgument("index", (reqIndex++).ToString(CultureInfo.InvariantCulture));

				// If the ReturnToUrl was explicitly set, we'll need to reset our first parameter
				if (OpenIdElement.Configuration.RelyingParty.PreserveUserSuppliedIdentifier) {
					if (string.IsNullOrEmpty(HttpUtility.ParseQueryString(req.ReturnToUrl.Query)[AuthenticationRequest.UserSuppliedIdentifierParameterName])) {
						req.SetUntrustedCallbackArgument(AuthenticationRequest.UserSuppliedIdentifierParameterName, userSuppliedIdentifier.OriginalString);
					}
				}

				// Our javascript needs to let the user know which endpoint responded.  So we force it here.
				// This gives us the info even for 1.0 OPs and 2.0 setup_required responses.
				req.SetUntrustedCallbackArgument(OpenIdRelyingPartyAjaxControlBase.OPEndpointParameterName, req.Provider.Uri.AbsoluteUri);
				req.SetUntrustedCallbackArgument(OpenIdRelyingPartyAjaxControlBase.ClaimedIdParameterName, (string)req.ClaimedIdentifier ?? string.Empty);

				// Inform ourselves in return_to that we're in a popup or iframe.
				req.SetUntrustedCallbackArgument(OpenIdRelyingPartyAjaxControlBase.UIPopupCallbackKey, "1");

				// We append a # at the end so that if the OP happens to support it,
				// the OpenID response "query string" is appended after the hash rather than before, resulting in the
				// browser being super-speedy in closing the popup window since it doesn't try to pull a newer version
				// of the static resource down from the server merely because of a changed URL.
				// http://www.nabble.com/Re:-Defining-how-OpenID-should-behave-with-fragments-in-the-return_to-url-p22694227.html
				////TODO:

				results.Add(req);
			}

			return results;
		}
示例#11
0
		public void GetHero(Realm realm, string battleTag, uint heroId, Action<Hero> callback)
		{
			string uri = string.Format(heroUri, App.GetDomain(realm), battleTag, heroId);
			Action<string> action = delegate(string json)
			{
				var hero = JsonConvert.DeserializeObject<Hero>(json);
				callback(hero);
			};
			this.SendRequest(uri, action);
		}
示例#12
0
		public void GetProfile(Realm realm, string battleTag, Action<Profile> callback)
		{
			string uri = string.Format(profileUri, App.GetDomain(realm), battleTag);
			Action<string> action = delegate(string json)
			{
				var profile = JsonConvert.DeserializeObject<Profile>(json);
				profile.Realm = realm;
				callback(profile);
			};
			this.SendRequest(uri, action);
		}
示例#13
0
		/// <summary>
		/// Gets the URL of the RP icon for the OP to display.
		/// </summary>
		/// <param name="realm">The realm of the RP where the authentication request originated.</param>
		/// <param name="hostFactories">The host factories.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <returns>
		/// A sequence of the RP's icons it has available for the Provider to display, in decreasing preferred order.
		/// </returns>
		/// <value>The icon URL.</value>
		/// <remarks>
		/// This property is automatically set for the OP with the result of RP discovery.
		/// RPs should set this value by including an entry such as this in their XRDS document.
		/// <example>
		/// &lt;Service xmlns="xri://$xrd*($v*2.0)"&gt;
		/// &lt;Type&gt;http://specs.openid.net/extensions/ui/icon&lt;/Type&gt;
		/// &lt;URI&gt;http://consumer.example.com/images/image.jpg&lt;/URI&gt;
		/// &lt;/Service&gt;
		/// </example>
		/// </remarks>
		public static async Task<IEnumerable<Uri>> GetRelyingPartyIconUrlsAsync(Realm realm, IHostFactories hostFactories, CancellationToken cancellationToken) {
			Requires.NotNull(realm, "realm");
			Requires.NotNull(hostFactories, "hostFactories");

			XrdsDocument xrds = await realm.DiscoverAsync(hostFactories, false, cancellationToken);
			if (xrds == null) {
				return Enumerable.Empty<Uri>();
			} else {
				return xrds.FindRelyingPartyIcons();
			}
		}
示例#14
0
        protected override void OnAppearing()
        {
            base.OnAppearing();
            _realm = Realm.GetInstance();

            var query = _realm.All<DemoObject>().OrderByDescending(o => o.Date) as RealmResults<DemoObject>;
            listView.ItemsSource = query.ToNotifyCollectionChanged(e =>
            {
                // recover from the error - recreate the query or show message to the user
                System.Diagnostics.Debug.WriteLine(e);
            }) as IEnumerable<DemoObject>;
        }
示例#15
0
        public bool HasConditions(Realm.Characters.Character _character)
        {
            foreach (var condi in Conditions)
            {
                if (condi.HasCondition(_character))
                    continue;
                else
                    return false;
            }

            return true;
        }
示例#16
0
 public void ApplyEffects(Realm.Characters.Character character)
 {
     try
     {
         foreach (var effect in Effects.Split('|'))
         {
             var infos = effect.Split(';');
             Realm.Effects.EffectAction.ParseEffect(character, int.Parse(infos[0]), infos[1]);
         }
     }
     catch { }
 }
示例#17
0
 internal void Apply(Realm Realm)
 {
     Vector3i BlockCoords = ChunkCoords * Size;
     for (int x = 0; x < Size.X; x++) {
         for (int y = 0; y < Size.Y; y++) {
             for (int z = 0; z < Size.Z; z++) {
                 Vector3i BlockAt = BlockCoords + new Vector3i(x, y, z);
                 Realm.SetBlock(BlockAt, BlockData[x, y, z]);
             }
         }
     }
 }
示例#18
0
        public void EqualsTest()
        {
            Realm tr1a = new Realm("http://www.yahoo.com");
            Realm tr1b = new Realm("http://www.yahoo.com");
            Realm tr2 = new Realm("http://www.yahoo.com/b");
            Realm tr3 = new Realm("http://*.www.yahoo.com");

            Assert.AreEqual(tr1a, tr1b);
            Assert.AreNotEqual(tr1a, tr2);
            Assert.AreNotEqual(tr1a, null);
            Assert.AreNotEqual(tr1a, tr1a.ToString(), "Although the URLs are equal, different object types shouldn't be equal.");
            Assert.AreNotEqual(tr3, tr1a, "Wildcard difference ignored by Equals");
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="AuthenticationRequest"/> class.
		/// </summary>
		/// <param name="discoveryResult">The endpoint that describes the OpenID Identifier and Provider that will complete the authentication.</param>
		/// <param name="realm">The realm, or root URL, of the host web site.</param>
		/// <param name="returnToUrl">The base return_to URL that the Provider should return the user to to complete authentication.  This should not include callback parameters as these should be added using the <see cref="AddCallbackArguments(string, string)"/> method.</param>
		/// <param name="relyingParty">The relying party that created this instance.</param>
		private AuthenticationRequest(IdentifierDiscoveryResult discoveryResult, Realm realm, Uri returnToUrl, OpenIdRelyingParty relyingParty) {
			Requires.NotNull(discoveryResult, "discoveryResult");
			Requires.NotNull(realm, "realm");
			Requires.NotNull(returnToUrl, "returnToUrl");
			Requires.NotNull(relyingParty, "relyingParty");

			this.DiscoveryResult = discoveryResult;
			this.RelyingParty = relyingParty;
			this.Realm = realm;
			this.ReturnToUrl = returnToUrl;

			this.Mode = AuthenticationRequestMode.Setup;
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="AuthenticationRequest"/> class.
		/// </summary>
		/// <param name="discoveryResult">The endpoint that describes the OpenID Identifier and Provider that will complete the authentication.</param>
		/// <param name="realm">The realm, or root URL, of the host web site.</param>
		/// <param name="returnToUrl">The base return_to URL that the Provider should return the user to to complete authentication.  This should not include callback parameters as these should be added using the <see cref="AddCallbackArguments(string, string)"/> method.</param>
		/// <param name="relyingParty">The relying party that created this instance.</param>
		private AuthenticationRequest(IdentifierDiscoveryResult discoveryResult, Realm realm, Uri returnToUrl, OpenIdRelyingParty relyingParty) {
			Contract.Requires<ArgumentNullException>(discoveryResult != null);
			Contract.Requires<ArgumentNullException>(realm != null);
			Contract.Requires<ArgumentNullException>(returnToUrl != null);
			Contract.Requires<ArgumentNullException>(relyingParty != null);

			this.DiscoveryResult = discoveryResult;
			this.RelyingParty = relyingParty;
			this.Realm = realm;
			this.ReturnToUrl = returnToUrl;

			this.Mode = AuthenticationRequestMode.Setup;
		}
		/// <summary>
		/// Gets the URL of the RP icon for the OP to display.
		/// </summary>
		/// <param name="realm">The realm of the RP where the authentication request originated.</param>
		/// <param name="webRequestHandler">The web request handler to use for discovery.
		/// Usually available via <see cref="Channel.WebRequestHandler">OpenIdProvider.Channel.WebRequestHandler</see>.</param>
		/// <returns>
		/// A sequence of the RP's icons it has available for the Provider to display, in decreasing preferred order.
		/// </returns>
		/// <value>The icon URL.</value>
		/// <remarks>
		/// This property is automatically set for the OP with the result of RP discovery.
		/// RPs should set this value by including an entry such as this in their XRDS document.
		/// <example>
		/// &lt;Service xmlns="xri://$xrd*($v*2.0)"&gt;
		/// &lt;Type&gt;http://specs.openid.net/extensions/ui/icon&lt;/Type&gt;
		/// &lt;URI&gt;http://consumer.example.com/images/image.jpg&lt;/URI&gt;
		/// &lt;/Service&gt;
		/// </example>
		/// </remarks>
		public static IEnumerable<Uri> GetRelyingPartyIconUrls(Realm realm, IDirectWebRequestHandler webRequestHandler) {
			Requires.NotNull(realm, "realm");
			Requires.NotNull(webRequestHandler, "webRequestHandler");
			ErrorUtilities.VerifyArgumentNotNull(realm, "realm");
			ErrorUtilities.VerifyArgumentNotNull(webRequestHandler, "webRequestHandler");

			XrdsDocument xrds = realm.Discover(webRequestHandler, false);
			if (xrds == null) {
				return Enumerable.Empty<Uri>();
			} else {
				return xrds.FindRelyingPartyIcons();
			}
		}
        /// <summary>
        /// Initializes a new instance of the <see cref="AuthenticationRequest"/> class.
        /// </summary>
        /// <param name="endpoint">The endpoint that describes the OpenID Identifier and Provider that will complete the authentication.</param>
        /// <param name="realm">The realm, or root URL, of the host web site.</param>
        /// <param name="returnToUrl">The base return_to URL that the Provider should return the user to to complete authentication.  This should not include callback parameters as these should be added using the <see cref="AddCallbackArguments(string, string)"/> method.</param>
        /// <param name="relyingParty">The relying party that created this instance.</param>
        private AuthenticationRequest(ServiceEndpoint endpoint, Realm realm, Uri returnToUrl, OpenIdRelyingParty relyingParty)
        {
            ErrorUtilities.VerifyArgumentNotNull(endpoint, "endpoint");
            ErrorUtilities.VerifyArgumentNotNull(realm, "realm");
            ErrorUtilities.VerifyArgumentNotNull(returnToUrl, "returnToUrl");
            ErrorUtilities.VerifyArgumentNotNull(relyingParty, "relyingParty");

            this.endpoint = endpoint;
            this.RelyingParty = relyingParty;
            this.Realm = realm;
            this.ReturnToUrl = returnToUrl;

            this.Mode = AuthenticationRequestMode.Setup;
        }
 private void populateRealmList()
 {
     this.realms = new Realms();
     gBattleAPI.BattleNET.RealmStatus statusList = api.getRealmStatus();
     foreach (gBattleAPI.BattleNET.RealmStatus.Realm realm in statusList.realms)
     {
         Realm _realm = new Realm();
         _realm.name = realm.name;
         _realm.slug = realm.slug;
         _realm.type = realm.type;
         this.realms.Add(_realm);
         this.battlegroups[realm.battlegroup].realms.Add(_realm);
     }
     statusList = null;
 }
示例#24
0
		AuthenticationRequest(ServiceEndpoint endpoint,
			Realm realm, Uri returnToUrl, OpenIdRelyingParty relyingParty) {
			if (endpoint == null) throw new ArgumentNullException("endpoint");
			if (realm == null) throw new ArgumentNullException("realm");
			if (returnToUrl == null) throw new ArgumentNullException("returnToUrl");
			if (relyingParty == null) throw new ArgumentNullException("relyingParty");

			this.endpoint = endpoint;
			RelyingParty = relyingParty;
			Realm = realm;
			ReturnToUrl = returnToUrl;

			Mode = AuthenticationRequestMode.Setup;
			OutgoingExtensions = ExtensionArgumentsManager.CreateOutgoingExtensions(endpoint.Protocol);
			ReturnToArgs = new Dictionary<string, string>();
		}
示例#25
0
        private bool Execute(Realm oldRealm, Realm newRealm)
        {
            OldRealm = oldRealm;
            NewRealm = newRealm;

            try
            {
                _configuration.MigrationCallback(this, oldRealm.Config.SchemaVersion);
            }
            catch (Exception e)
            {
                MigrationException = e;
                return false;
            }

            return true;
        }
示例#26
0
        /// <summary>
        /// Creates a message that can be sent to a user agent to redirect them to a 
        /// relying party web site complete with authentication information to 
        /// automatically log them into that web site.
        /// </summary>
        public static IResponse CreateUnsolicitedAssertion(OpenIdProvider provider,
            Realm relyingParty, Identifier claimedIdentifier, Identifier localIdentifier)
        {
            if (relyingParty == null) throw new ArgumentNullException("relyingParty");
            if (claimedIdentifier == null) throw new ArgumentNullException("claimedIdentifier");
            if (localIdentifier == null) throw new ArgumentNullException("localIdentifier");

            var discoveredEndpoints = new List<RelyingPartyReceivingEndpoint>(relyingParty.Discover(true));
            if (discoveredEndpoints.Count == 0) throw new OpenIdException(
                string.Format(CultureInfo.CurrentCulture, Strings.NoRelyingPartyEndpointDiscovered,
                relyingParty.NoWildcardUri));
            var selectedEndpoint = discoveredEndpoints[0];

            EncodableResponse message = EncodableResponse.PrepareIndirectMessage(
                selectedEndpoint.Protocol, selectedEndpoint.RelyingPartyEndpoint, null);
            CreatePositiveAssertion(message, provider, localIdentifier, claimedIdentifier);
            return provider.Encoder.Encode(message);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="netState"></param>
        /// <param name="packetReader"></param>
        public static void Realm_HandleRegisterRealm( NetState netState, PacketReader packetReader )
        {
            RealmExtendData extendData = netState.GetComponent<RealmExtendData>( RealmExtendData.COMPONENT_ID );
            if ( extendData == null )
            {
                Debug.WriteLine( "Realm_PacketHandlers.Realm_HandleRegisterRealm(...) - extendData == null error!" );
                return;
            }

            if ( extendData.IsLoggedIn == true )
            {
                Debug.WriteLine( "Realm_PacketHandlers.Realm_HandleRegisterRealm(...) - extendData.IsLoggedIn == true error!" );
                return;
            }

            Realm realm = new Realm();

            realm.Name = packetReader.ReadUTF8String();
            realm.Address = packetReader.ReadUTF8String();

            string strIcon = packetReader.ReadUTF8String();
            if ( Insensitive.Equals( strIcon, "PVP" ) )
                realm.Icon = (uint)RealmIconType.REALMTYPE_PVP;
            else if ( Insensitive.Equals( strIcon, "RP" ) )
                realm.Icon = (uint)RealmIconType.REALMTYPE_RP;
            else if ( Insensitive.Equals( strIcon, "RPPVP" ) )
                realm.Icon = (uint)RealmIconType.REALMTYPE_RPPVP;
            else
                realm.Icon = (uint)RealmIconType.REALMTYPE_NORMAL;

            realm.Colour = packetReader.ReadUInt32();
            realm.TimeZone = packetReader.ReadUInt32();
            realm.Population = packetReader.ReadFloat();

            extendData.RequestSession.Serial = RealmHandler.RealmsExclusiveSerial.GetExclusiveSerial();

            // Add to the main realm list
            RealmHandler.AddRealm( extendData.RequestSession.Serial, realm );

            extendData.IsLoggedIn = true;

            // Send back response packet.
            netState.Send( new Realm_RegisterRealmResult( extendData.RequestSession.Serial ) );
        }
示例#28
0
        public void SetUp()
        {
            Realm.DeleteRealm(RealmConfiguration.DefaultConfiguration);
            realm = Realm.GetInstance();

            // we don't keep any variables pointing to these as they are all added to Realm
            using (var trans = realm.BeginWrite())
            {
                var o1 = realm.Add(new Owner { Name = "Tim" });

                var d1 = realm.Add(new Dog
                {
                    Name = "Bilbo Fleabaggins",
                    Color = "Black"
                });

                o1.TopDog = d1;  // set a one-one relationship
                o1.Dogs.Add(d1);

                var d2 = realm.Add(new Dog
                {
                    Name = "Earl Yippington III",
                    Color = "White"
                });

                o1.Dogs.Add(d2);

                // lonely people and dogs
                realm.Add(new Owner
                {
                    Name = "Dani" // the dog-less
                });

                realm.Add(new Dog // will remain unassigned
                {
                    Name = "Maggie Mongrel",
                    Color = "Grey"
                });

                trans.Commit();
            }
        }
		protected internal override void onCreate(Bundle savedInstanceState)
		{
			base.onCreate(savedInstanceState);
			ContentView = R.layout.activity_realm_basic_example;

			rootLayout = ((LinearLayout) findViewById(R.id.container));
			rootLayout.removeAllViews();

			// 3 versions of the databases for testing. Normally you would only have one.
			copyBundledRealmFile(this.Resources.openRawResource(R.raw.default0), "default0");
			copyBundledRealmFile(this.Resources.openRawResource(R.raw.default1), "default1");
			copyBundledRealmFile(this.Resources.openRawResource(R.raw.default2), "default2");

			// When you create a RealmConfiguration you can specify the version of the schema.
			// If the schema does not have that version a RealmMigrationNeededException will be thrown.
			RealmConfiguration config0 = (new RealmConfiguration.Builder(this)).name("default0").schemaVersion(3).build();

			// You can then manually call Realm.migrateRealm().
			Realm.migrateRealm(config0, new Migration());
			realm = Realm.getInstance(config0);
			showStatus("Default0");
			showStatus(realm);
			realm.close();

			// Or you can add the migration code to the configuration. This will run the migration code without throwing
			// a RealmMigrationNeededException.
			RealmConfiguration config1 = (new RealmConfiguration.Builder(this)).name("default1").schemaVersion(3).migration(new Migration()).build();

			realm = Realm.getInstance(config1); // Automatically run migration if needed
			showStatus("Default1");
			showStatus(realm);
			realm.close();

			// or you can set .deleteRealmIfMigrationNeeded() if you don't want to bother with migrations.
			// WARNING: This will delete all data in the Realm though.
			RealmConfiguration config2 = (new RealmConfiguration.Builder(this)).name("default2").schemaVersion(3).deleteRealmIfMigrationNeeded().build();

			realm = Realm.getInstance(config2);
			showStatus("default2");
			showStatus(realm);
			realm.close();
		}
示例#30
0
        AuthenticationRequest(string token, Association assoc, ServiceEndpoint endpoint,
            Realm realm, Uri returnToUrl, OpenIdRelyingParty relyingParty)
        {
            if (endpoint == null) throw new ArgumentNullException("endpoint");
            if (realm == null) throw new ArgumentNullException("realm");
            if (returnToUrl == null) throw new ArgumentNullException("returnToUrl");
            if (relyingParty == null) throw new ArgumentNullException("relyingParty");

            this.assoc = assoc;
            this.endpoint = endpoint;
            RelyingParty = relyingParty;
            Realm = realm;
            ReturnToUrl = returnToUrl;

            Mode = AuthenticationRequestMode.Setup;
            OutgoingExtensions = ExtensionArgumentsManager.CreateOutgoingExtensions(endpoint.Protocol);
            ReturnToArgs = new Dictionary<string, string>();
            if (token != null)
                AddCallbackArguments(DotNetOpenId.RelyingParty.Token.TokenKey, token);
        }
示例#31
0
        public void GetInstanceAsync_ExecutesMigrationsInBackground()
        {
            AsyncContext.Run(async() =>
            {
                Realm realm = null;
                var config  = new RealmConfiguration("asyncmigration.realm")
                {
                    SchemaVersion = 1,
                };

                Realm.DeleteRealm(config);

                using (var firstRealm = Realm.GetInstance(config))
                {
                    Assert.That(firstRealm.All <IntPrimaryKeyWithValueObject>().Count(), Is.Zero);
                }

                var threadId = Environment.CurrentManagedThreadId;
                var hasCompletedMigration = false;
                config.SchemaVersion      = 2;
                config.MigrationCallback  = (migration, oldSchemaVersion) =>
                {
                    Assert.That(Environment.CurrentManagedThreadId, Is.Not.EqualTo(threadId));
                    Thread.Sleep(300);
                    migration.NewRealm.Add(new IntPrimaryKeyWithValueObject
                    {
                        Id = 123
                    });
                    hasCompletedMigration = true;
                };

                Exception ex = null;
                Realm.GetInstanceAsync(config)
                .ContinueWith(t =>
                {
                    if (t.IsFaulted)
                    {
                        ex = t.Exception;
                    }
                    else
                    {
                        realm = t.Result;
                    }
                }, TaskScheduler.FromCurrentSynchronizationContext());

                var ticks = 0;
                while (realm == null)
                {
                    await Task.Delay(100);
                    ticks++;

                    if (ticks > 10)
                    {
                        Assert.Fail("Migration should have completed by now.");
                    }
                }

                Assert.That(ex, Is.Null);
                Assert.That(hasCompletedMigration);
                Assert.That(ticks, Is.GreaterThanOrEqualTo(3));
                Assert.That(realm.All <IntPrimaryKeyWithValueObject>().Count(), Is.EqualTo(1));
                realm.Dispose();
            });
        }
示例#32
0
 public void GetInstanceTest()
 {
     // Arrange, act and "assert" that no exception is thrown, using default location
     Realm.GetInstance().Dispose();
 }
示例#33
0
 public void SetUp()
 {
     Realm.DeleteRealm(new RealmConfiguration("LifetimeTests.realm"));
 }
示例#34
0
        public async Task <ApiResponse <AchievementFirst> > GetAchievementFirstsAsync(Realm realm)
        {
            ApiParams param = new ApiParams(Endpoints.AchievementFirsts, Secret, new AchievementBaseRequest(realm));

            return(await CommunicateAsync <AchievementFirst>(param));
        }
示例#35
0
    void UpdateRealms(object source, ElapsedEventArgs e)
    {
        PreparedStatement stmt   = DB.Login.GetPreparedStatement(LoginStatements.SEL_REALMLIST);
        SQLResult         result = DB.Login.Query(stmt);
        Dictionary <RealmHandle, string> existingRealms = new Dictionary <RealmHandle, string>();

        foreach (var p in _realms)
        {
            existingRealms[p.Key] = p.Value.Name;
        }

        _realms.Clear();

        // Circle through results and add them to the realm map
        if (!result.IsEmpty())
        {
            do
            {
                var  realm   = new Realm();
                uint realmId = result.Read <uint>(0);
                realm.Name            = result.Read <string>(1);
                realm.ExternalAddress = IPAddress.Parse(result.Read <string>(2));
                realm.LocalAddress    = IPAddress.Parse(result.Read <string>(3));
                realm.LocalSubnetMask = IPAddress.Parse(result.Read <string>(4));
                realm.Port            = result.Read <ushort>(5);
                RealmType realmType = (RealmType)result.Read <byte>(6);
                if (realmType == RealmType.FFAPVP)
                {
                    realmType = RealmType.PVP;
                }
                if (realmType >= RealmType.MaxType)
                {
                    realmType = RealmType.Normal;
                }

                realm.Type     = (byte)realmType;
                realm.Flags    = (RealmFlags)result.Read <byte>(7);
                realm.Timezone = result.Read <byte>(8);
                AccountTypes allowedSecurityLevel = (AccountTypes)result.Read <byte>(9);
                realm.AllowedSecurityLevel = (allowedSecurityLevel <= AccountTypes.Administrator ? allowedSecurityLevel : AccountTypes.Administrator);
                realm.PopulationLevel      = result.Read <float>(10);
                realm.Build = result.Read <uint>(11);
                byte region      = result.Read <byte>(12);
                byte battlegroup = result.Read <byte>(13);

                realm.Id = new RealmHandle(region, battlegroup, realmId);

                UpdateRealm(realm);

                var subRegion = new RealmHandle(region, battlegroup, 0).GetAddressString();
                if (!_subRegions.Contains(subRegion))
                {
                    _subRegions.Add(subRegion);
                }

                if (!existingRealms.ContainsKey(realm.Id))
                {
                    Log.outInfo(LogFilter.Realmlist, "Added realm \"{0}\" at {1}:{2}", realm.Name, realm.ExternalAddress.ToString(), realm.Port);
                }
                else
                {
                    Log.outDebug(LogFilter.Realmlist, "Updating realm \"{0}\" at {1}:{2}", realm.Name, realm.ExternalAddress.ToString(), realm.Port);
                }

                existingRealms.Remove(realm.Id);
            }while (result.NextRow());
        }

        foreach (var pair in existingRealms)
        {
            Log.outInfo(LogFilter.Realmlist, "Removed realm \"{0}\".", pair.Value);
        }
    }
 public RealmViewModel()
 {
     Pokemons        = new ObservableCollection <PokemonRealm>();
     _pokemonService = new PokemonService();
     _realm          = Realm.GetInstance();
 }
示例#37
0
        // Fonction de récupération et d'affichage des données de l'api
        private void ParseAndDisplay(JsonValue json, string Ville)
        {
            var config = RealmConfiguration.DefaultConfiguration;

            config.SchemaVersion = 2;
            var realm = Realm.GetInstance();

            // Get the weather reporting fields from the layout resource:
            TextView       weatherLabel  = FindViewById <TextView>(Resource.Id.weatherLabel);
            TextView       weatherDetail = FindViewById <TextView>(Resource.Id.weatherDetail);
            ImageViewAsync weatherImg    = FindViewById <ImageViewAsync>(Resource.Id.weatherImg);

            TextView temperatureAct = FindViewById <TextView>(Resource.Id.temperatureAct);
            TextView temperatureMin = FindViewById <TextView>(Resource.Id.temperatureMin);
            TextView temperatureMax = FindViewById <TextView>(Resource.Id.temperatureMax);

            TextView wind = FindViewById <TextView>(Resource.Id.windspeedText);

            // Extract the array of name/value results for the field name "weatherObservation".
            JsonValue weatherResults     = json["weather"][0];
            JsonValue temperatureResults = json["main"];
            JsonValue windResults        = json["wind"];

            // Extract the "stationName" (location string) and write it to the location TextBox:
            weatherLabel.Text  = weatherResults["main"].ToString();
            weatherDetail.Text = weatherResults["description"].ToString();

            string URL = "http://openweathermap.org/img/w/" + weatherResults["icon"] + ".png";

            ImageService.Instance.LoadUrl(URL).Into(weatherImg);
            // The temperature is expressed in Celsius:
            double temp    = Convert.ToDouble(temperatureResults["temp"].ToString()) - 273.15;
            double tempMin = Convert.ToDouble(temperatureResults["temp_min"].ToString()) - 273.15;
            double tempMax = Convert.ToDouble(temperatureResults["temp_max"].ToString()) - 273.15;

            // Write the temperature (one decimal place) to the temperature TextBox:
            temperatureAct.Text = String.Format("{0:F1}", temp) + "°C";
            temperatureMin.Text = "Min: " + String.Format("{0:F1}", tempMin) + "°C";
            temperatureMax.Text = "Max: " + String.Format("{0:F1}", tempMax) + "°C";

            // Get the "clouds" and "weatherConditions" strings and
            // combine them. Ignore strings that are reported as "n/a":
            string cloudy = windResults["speed"].ToString();

            wind.Text = cloudy + " km/h ";

            var key = realm.All <Ville>();
            int id  = key.AsRealmCollection().Count + 1;

            realm.Write(() =>
            {
                realm.Add(new Ville {
                    Id            = id,
                    nom           = Ville,
                    weather       = weatherResults["main"].ToString(),
                    weatherDetail = weatherResults["description"].ToString(),
                    image         = URL,
                    temp          = String.Format("{0:F1}", temp),
                    tmpMin        = String.Format("{0:F1}", tempMin),
                    tmpMax        = String.Format("{0:F1}", tempMax),
                    windspeed     = windResults["speed"].ToString()
                });
            });
        }
示例#38
0
        private void SetView(Context context, int appWidgetId, RemoteViews widgetView, WidgetLargeParams widgetLargeParams)
        {
            if (!widgetLargeParams.IsRefreshing)
            {
                Realm realm = Realm.GetInstance(DB.RealmConfiguration);

                // Bind the RemoteViewsService (adapter) for the Chapters list
                Intent intent = new Intent(context, typeof(RemoteChapterAdapter));
                intent.PutExtra(AppWidgetManager.ExtraAppwidgetId, appWidgetId);
                intent.PutExtra(RemoteChapterAdapter.ExtraBookId, widgetLargeParams.Book);
                intent.PutExtra(RemoteChapterAdapter.ExtraSortOrder, widgetLargeParams.Descending);
                intent.SetData(Uri.Parse(intent.ToUri(IntentUriType.Scheme)));
                widgetView.SetRemoteAdapter(Resource.Id.list_chapters, intent);

                // Set Chapter list click intent template
                Intent        chapterClickIntentTemplate        = new Intent(Intent.ActionView);
                PendingIntent chapterClickPendingIntentTemplate = TaskStackBuilder.Create(context)
                                                                  .AddNextIntentWithParentStack(chapterClickIntentTemplate)
                                                                  .GetPendingIntent(appWidgetId, PendingIntentFlags.UpdateCurrent);
                widgetView.SetPendingIntentTemplate(Resource.Id.list_chapters, chapterClickPendingIntentTemplate);

                // Set list header to Book title
                string title = realm.Find <Book>(widgetLargeParams.Book).Title;
                widgetView.SetTextViewText(Resource.Id.book_title, title);

                Intent bookIntent = new Intent(context, typeof(WidgetLarge));
                bookIntent.SetAction(BookClick);
                bookIntent.PutExtra(AppWidgetManager.ExtraAppwidgetId, appWidgetId);
                PendingIntent bookPendingIntent = PendingIntent.GetBroadcast(context, appWidgetId, bookIntent, PendingIntentFlags.OneShot);
                widgetView.SetOnClickPendingIntent(Resource.Id.book_title, bookPendingIntent);

                // Bind the click intent for the refresh button on the widget
                Intent refreshIntent = new Intent(context, typeof(WidgetLarge));
                refreshIntent.SetAction(RefreshClick);
                refreshIntent.PutExtra(AppWidgetManager.ExtraAppwidgetId, appWidgetId);
                PendingIntent refreshPendingIntent = PendingIntent.GetBroadcast(context, appWidgetId, refreshIntent, PendingIntentFlags.UpdateCurrent);
                widgetView.SetOnClickPendingIntent(Resource.Id.btn_refresh, refreshPendingIntent);

                realm.Dispose();
            }

            // Bind the click intent for the previous button on the widget
            Intent previousIntent = new Intent(context, typeof(WidgetLarge));

            previousIntent.SetAction(PreviousClick);
            previousIntent.PutExtra(AppWidgetManager.ExtraAppwidgetId, appWidgetId);
            PendingIntent previousPendingIntent = PendingIntent.GetBroadcast(context, appWidgetId, previousIntent, PendingIntentFlags.UpdateCurrent);

            widgetView.SetOnClickPendingIntent(Resource.Id.btn_previous, previousPendingIntent);

            // Bind the click intent for the next button on the widget
            Intent nextIntent = new Intent(context, typeof(WidgetLarge));

            nextIntent.SetAction(NextClick);
            nextIntent.PutExtra(AppWidgetManager.ExtraAppwidgetId, appWidgetId);
            PendingIntent nextPendingIntent = PendingIntent.GetBroadcast(context, appWidgetId, nextIntent, PendingIntentFlags.UpdateCurrent);

            widgetView.SetOnClickPendingIntent(Resource.Id.btn_next, nextPendingIntent);

            // Bind the click intent for the reverse button on the widget
            Intent reverseIntent = new Intent(context, typeof(WidgetLarge));

            reverseIntent.SetAction(ReverseClick);
            reverseIntent.PutExtra(AppWidgetManager.ExtraAppwidgetId, appWidgetId);
            PendingIntent reversePendingIntent = PendingIntent.GetBroadcast(context, appWidgetId, reverseIntent, PendingIntentFlags.UpdateCurrent);

            widgetView.SetOnClickPendingIntent(Resource.Id.btn_reverse, reversePendingIntent);
        }
示例#39
0
        public async Task EnterBuilding(CommandContext c, Building building)
        {
            var log = Serilog.Log.ForContext <SkillTrainer>();

            using (var session = Db.DocStore.OpenAsyncSession())
            {
                var player = await session.LoadAsync <Player>(c.User.Id.ToString());

                if (player == null)
                {
                    await c.RejectMessage(Realm.GetMessage("not_registered"));

                    return;
                }

                var skillMenuBuilder = new DiscordEmbedBuilder()
                                       .WithTitle(building.Name);

                var description = new System.Text.StringBuilder();
                description.AppendLine($"*\"{building.WelcomeMessage}\"*");

                // Get skills
                var skillsDict = await session.LoadAsync <Skill>(building.Parameters.Where(p => p.Value.StartsWith("skills/")).Select(p => p.Value));

                var skills = skillsDict.Where(kv => kv.Value != null).Select(s => s.Value).ToList();

                foreach (var skill in skills)
                {
                    if (skill.TrainingCosts == null)
                    {
                        log.Error("No trainingcosts defined for {skillname} ({skillid}).", skill.DisplayName, skill.Id);
                        return;
                    }

                    var    descriptionLines = skill.Description.Split('\n');
                    string descriptionText  = descriptionLines[0];
                    if (descriptionLines.Length > 0)
                    {
                        descriptionText += "...";
                    }

                    // Get the  player rank
                    int playerSkillRank = 0;
                    var playerSkill     = player.Skills.FirstOrDefault(ps => ps.Id == skill.Id);
                    if (playerSkill != null)
                    {
                        playerSkillRank = playerSkill.Rank;
                    }

                    // Check if max rank
                    if (skill.TrainingCosts.Count == playerSkillRank)
                    {
                        description.AppendLine($"{skill.ReactionIcon} {skill.DisplayName} (Max skill) - *{descriptionText}*");
                        continue;
                    }

                    // Get next cost
                    int rankCost = skill.TrainingCosts[playerSkillRank];
                    description.AppendLine($"{skill.ReactionIcon} {skill.DisplayName} (Cost: {rankCost}) - *{descriptionText}*");
                }

                skillMenuBuilder.WithDescription(description.ToString());

                if (player.SkillPoints < 1)
                {
                    skillMenuBuilder.WithFooter("You do not have any skillpoints");
                }

                var msg = await c.RespondAsync(embed : skillMenuBuilder.Build());

                if (player.SkillPoints < 1)
                {
                    return;
                }

                foreach (var skill in skills)
                {
                    if (skill.TrainingCosts == null)
                    {
                        continue;
                    }

                    // Get the  player rank
                    int playerSkillRank = 0;
                    var playerSkill     = player.Skills.FirstOrDefault(ps => ps.Id == skill.Id);
                    if (playerSkill != null)
                    {
                        playerSkillRank = playerSkill.Rank;
                    }

                    // Check if max rank
                    if (skill.TrainingCosts.Count != playerSkillRank)
                    {
                        await msg.CreateReactionAsync(DiscordEmoji.FromName(c.Client, skill.ReactionIcon));
                    }
                }

                var interact = c.Client.GetInteractivity();
                var response = await interact.WaitForMessageReactionAsync(msg, c.User, System.TimeSpan.FromSeconds(10));

                if (response == null)
                {
                    await c.RejectMessage();

                    await msg.DeleteAsync();

                    return;
                }

                await msg.DeleteAllReactionsAsync();

                var responseName  = response.Emoji.GetDiscordName().ToLower();
                var selectedSkill = skills.FirstOrDefault(s => s.ReactionIcon.Equals(responseName));
                var skillEntry    = player.Skills.FirstOrDefault(ls => ls.Id.Equals(selectedSkill?.Id));

                var currentPlayerSkill = player.Skills.FirstOrDefault(ps => ps.Id == selectedSkill.Id);
                int nextRankCost       = currentPlayerSkill != null
                                        ? selectedSkill.TrainingCosts[currentPlayerSkill.Rank]
                                        : selectedSkill.TrainingCosts[0];

                if (nextRankCost > player.SkillPoints)
                {
                    await c.RejectMessage(string.Format(Realm.GetMessage("next_skill_not_enough_skillpts"), selectedSkill.DisplayName));

                    return;
                }

                if (skillEntry == null)
                {
                    player.AddSkill(new TrainedSkill(selectedSkill.Id, 1));
                    await c.RespondAsync($"{c.User.Mention} learned {selectedSkill.DisplayName}");
                }
                else
                {
                    skillEntry.Rank += 1;
                    await c.RespondAsync($"{c.User.Mention} {selectedSkill.DisplayName} has increased to {skillEntry.Rank}");
                }

                player.SkillPoints -= nextRankCost;

                if (session.Advanced.HasChanged(player))
                {
                    await session.SaveChangesAsync();
                }

                await msg.DeleteAsync();

                await c.ConfirmMessage();
            }
        }
示例#40
0
        private async void Login()
        {
            // varivel de autenticaçao
            Authenticated authenticated = null;

            email = "*****@*****.**";
            senha = "integra2016";

            try
            {
                BtnEntrar = false;

                Load = true;

                email = string.IsNullOrEmpty(email) ? "" : email;
                senha = string.IsNullOrEmpty(senha) ? "" : senha;

                //verifica se preencheu os campos corretamente
                if (email.Length < 5 && senha.Length < 3)
                {
                    await App._alertService.ShowAsync("Erro!", "Email ou Senha incorretos!", "Ok");

                    Load      = false;
                    BtnEntrar = true;
                    return;
                }

                // monto o objeto a ser eviado
                Usuario user = new Usuario();
                user.email = email;
                user.senha = senha;

                // vamos verificar
                HttpResponseMessage response = await HttpService.Logar(user);


                switch ((int)response.StatusCode)
                {
                case 200:
                    authenticated = JsonConvert.DeserializeObject <Authenticated>(response.Content.ReadAsStringAsync().Result);
                    break;

                case 500:
                    await App._alertService.ShowAsync("Erro de conexão", "Ocorreu um erro ao se conectar com o servidor, tente novamente!", "Ok");

                    break;

                case 400:
                    await App._alertService.ShowAsync("CPF ou Placa incorretos!", "Verifique o Email e Senha digitados e tente novamente.", "Ok");

                    break;

                case 401:
                    await App._alertService.ShowAsync("Usuário não autorizado", "Verifique o Email e Senha digitados e tente novamente.", "Ok");

                    break;

                default:
                    await App._alertService.ShowAsync("Opss...", "Erro ao se comunicar com o servidor, tente novamente.", "Ok");

                    break;
                }

                // autenticando
                if (authenticated != null)
                {
                    // instancio o realm
                    var realm = Realm.GetInstance();

                    var myAuths = realm.All <AuthenticatedDAO>();

                    if (myAuths.Count() > 0)
                    {                     // vamos atualizar
                        var myAuth = realm.All <AuthenticatedDAO>().First();
                        realm.Write(() =>
                        {
                            myAuth.idUsuario          = authenticated.IdUsuario.ToString();
                            myAuth.login              = authenticated.Login;
                            myAuth.AuthorizationToken = authenticated.AuthorizationToken;
                        });

                        Debug.WriteLine("Token Atualizado: " + myAuth.AuthorizationToken);
                    }
                    else
                    {
                        realm.Write(() =>
                        {
                            realm.Add(new AuthenticatedDAO {
                                idUsuario = authenticated.IdUsuario.ToString(), login = authenticated.Login, AuthorizationToken = authenticated.AuthorizationToken
                            });
                        });

                        Debug.WriteLine("Adicionado um novo token: " + authenticated.AuthorizationToken);
                    }

                    await App._navigationService.NavigateToMenuSlider();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Erro ao logar: " + ex.Message);
            }
            finally {
                Load      = true;
                BtnEntrar = true;
            }
        }
        private async void SaveDraftCommandRecieverAsync()
        {
            try
            {
                Loader.StartLoading();
                var location = await _geolocationService.GetLastLocationAsync();

                ManifestModel manifestModel = null;
                try
                {
                    manifestModel = GenerateManifest(location ?? new Xamarin.Essentials.Location(0, 0));
                    if (manifestModel != null)
                    {
                        manifestModel.IsDraft = true;
                        var isNew = Realm.GetInstance(RealmDbManager.GetRealmDbConfig()).Find <ManifestModel>(manifestModel.ManifestId);
                        if (isNew != null)
                        {
                            try
                            {
                                var RealmDb = Realm.GetInstance(RealmDbManager.GetRealmDbConfig());
                                RealmDb.Write(() =>
                                {
                                    RealmDb.Add(manifestModel, update: true);
                                });
                            }
                            catch (Exception ex)
                            {
                                Crashes.TrackError(ex);
                            }
                        }
                        else
                        {
                            try
                            {
                                var RealmDb = Realm.GetInstance(RealmDbManager.GetRealmDbConfig());
                                RealmDb.Write(() =>
                                {
                                    RealmDb.Add(manifestModel);
                                });
                            }
                            catch (Exception ex)
                            {
                                Crashes.TrackError(ex);
                            }
                        }

                        Loader.StopLoading();
                        await _navigationService.NavigateAsync("ManifestsView",
                                                               new NavigationParameters
                        {
                            { "LoadDraftManifestAsync", "LoadDraftManifestAsync" }
                        }, animated : false);
                    }
                    else
                    {
                        await _dialogService.DisplayAlertAsync("Error", "Could not save manifest.", "Ok");
                    }
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }
                finally
                {
                    manifestModel = null;
                    Cleanup();
                }
            }
            catch (Exception ex)
            {
                Crashes.TrackError(ex);
            }
            finally
            {
                Loader.StopLoading();
            }
        }
        private async Task GetPostedManifestDetail()
        {
            var    RealmDb  = Realm.GetInstance(RealmDbManager.GetRealmDbConfig());
            string sizeName = string.Empty;
            ManifestResponseModel manifest = new ManifestResponseModel();

            try
            {
                sizeName = ConstantManager.Tags.LastOrDefault().Value;
            }
            catch (Exception ex)
            {
                Crashes.TrackError(ex);
            }
            try
            {
                manifest.ManifestItems = new List <CreatedManifestItem>();
                foreach (var item in Barcodes)
                {
                    manifest.ManifestItems.Add(new CreatedManifestItem
                    {
                        Barcode  = item.Barcode,
                        Contents = Contents,
                        Keg      = new CreatedManifestKeg
                        {
                            Barcode    = item.Barcode,
                            Contents   = Contents,
                            VolumeName = "Jitendra",
                            OwnerName  = ConstantManager.Partner.FullName,
                            SizeName   = sizeName,
                        }
                    });
                }

                manifest.TrackingNumber = ManifestId;
                manifest.ShipDate       = DateTimeOffset.UtcNow.Date.ToShortDateString();
                manifest.CreatorCompany = new CreatorCompany {
                    Address = ConstantManager.Partner.Address, State = ConstantManager.Partner.State, PostalCode = ConstantManager.Partner.PostalCode, Lon = ConstantManager.Partner.Lon, Address1 = ConstantManager.Partner.Address1, City = ConstantManager.Partner.City, CompanyNo = ConstantManager.Partner.CompanyNo.HasValue ? ConstantManager.Partner.CompanyNo.Value.ToString() : string.Empty, Country = ConstantManager.Partner.Country, FullName = ConstantManager.Partner.FullName, IsActive = ConstantManager.Partner.IsActive, IsInternal = ConstantManager.Partner.IsInternal, IsShared = ConstantManager.Partner.IsShared, Lat = ConstantManager.Partner.Lat, LocationCode = ConstantManager.Partner.LocationCode, LocationStatus = ConstantManager.Partner.LocationStatus, MasterCompanyId = ConstantManager.Partner.MasterCompanyId, ParentPartnerId = ConstantManager.Partner.ParentPartnerId, ParentPartnerName = ConstantManager.Partner.ParentPartnerName, PartnerId = ConstantManager.Partner.PartnerId, PartnershipIsActive = ConstantManager.Partner.PartnershipIsActive, PartnerTypeCode = ConstantManager.Partner.PartnerTypeCode, PartnerTypeName = ConstantManager.Partner.PartnerTypeName, PhoneNumber = ConstantManager.Partner.PhoneNumber, SourceKey = ConstantManager.Partner.SourceKey
                };
                manifest.SenderPartner = new CreatorCompany {
                    Address = ConstantManager.Partner.Address                                          /*, State = ConstantManager.Partner.State, PostalCode = ConstantManager.Partner.PostalCode, Lon = ConstantManager.Partner.Lon, Address1 = ConstantManager.Partner.Address1, City = ConstantManager.Partner.City, CompanyNo = ConstantManager.Partner.CompanyNo.HasValue ? ConstantManager.Partner.CompanyNo.Value.ToString() : string.Empty, Country = ConstantManager.Partner.Country, FullName = ConstantManager.Partner.FullName, IsActive = ConstantManager.Partner.IsActive, IsInternal = ConstantManager.Partner.IsInternal, IsShared = ConstantManager.Partner.IsShared, Lat = ConstantManager.Partner.Lat, LocationCode = ConstantManager.Partner.LocationCode, LocationStatus = ConstantManager.Partner.LocationStatus, MasterCompanyId = ConstantManager.Partner.MasterCompanyId, ParentPartnerId = ConstantManager.Partner.ParentPartnerId, ParentPartnerName = ConstantManager.Partner.ParentPartnerName, PartnerId = ConstantManager.Partner.PartnerId, PartnershipIsActive = ConstantManager.Partner.PartnershipIsActive, PartnerTypeCode = ConstantManager.Partner.PartnerTypeCode, PartnerTypeName = ConstantManager.Partner.PartnerTypeName, PhoneNumber = ConstantManager.Partner.PhoneNumber, SourceKey = ConstantManager.Partner.SourceKey */
                };
                manifest.ReceiverPartner = new CreatorCompany {
                    Address = ConstantManager.Partner.Address, State = ConstantManager.Partner.State, PostalCode = ConstantManager.Partner.PostalCode, Lon = ConstantManager.Partner.Lon, Address1 = ConstantManager.Partner.Address1, City = ConstantManager.Partner.City, CompanyNo = ConstantManager.Partner.CompanyNo.HasValue ? ConstantManager.Partner.CompanyNo.Value.ToString() : string.Empty, Country = ConstantManager.Partner.Country, FullName = ConstantManager.Partner.FullName, IsActive = ConstantManager.Partner.IsActive, IsInternal = ConstantManager.Partner.IsInternal, IsShared = ConstantManager.Partner.IsShared, Lat = ConstantManager.Partner.Lat, LocationCode = ConstantManager.Partner.LocationCode, LocationStatus = ConstantManager.Partner.LocationStatus, MasterCompanyId = ConstantManager.Partner.MasterCompanyId, ParentPartnerId = ConstantManager.Partner.ParentPartnerId, ParentPartnerName = ConstantManager.Partner.ParentPartnerName, PartnerId = ConstantManager.Partner.PartnerId, PartnershipIsActive = ConstantManager.Partner.PartnershipIsActive, PartnerTypeCode = ConstantManager.Partner.PartnerTypeCode, PartnerTypeName = ConstantManager.Partner.PartnerTypeName, PhoneNumber = ConstantManager.Partner.PhoneNumber, SourceKey = ConstantManager.Partner.SourceKey
                };
                manifest.SenderShipAddress = new Address {
                    City = ConstantManager.Partner.City, Country = ConstantManager.Partner.Country, Geocoded = false, Latitude = (long)ConstantManager.Partner.Lat, Line1 = ConstantManager.Partner.Address, Line2 = ConstantManager.Partner.Address1, Longitude = (long)ConstantManager.Partner.Lon, PostalCode = ConstantManager.Partner.PostalCode, State = ConstantManager.Partner.State
                };
                manifest.ReceiverShipAddress = new Address {
                    City = ConstantManager.Partner.City, Country = ConstantManager.Partner.Country, Geocoded = false, Latitude = (long)ConstantManager.Partner.Lat, Line1 = ConstantManager.Partner.Address, Line2 = ConstantManager.Partner.Address1, Longitude = (long)ConstantManager.Partner.Lon, PostalCode = ConstantManager.Partner.PostalCode, State = ConstantManager.Partner.State
                };
            }
            catch (Exception ex)
            {
                Crashes.TrackError(ex);
            }

            await _navigationService.NavigateAsync("ManifestDetailView", new NavigationParameters
            {
                { "manifest", manifest }, { "Contents", Contents }
            }, animated : false);
        }
示例#43
0
 public DataStore()
 {
     realm     = Realm.GetInstance();
     AllPhotos = realm.All <PhotoUrl>();
 }
示例#44
0
 public void GetInstanceWithJustFilenameTest()
 {
     // Arrange, act and "assert" that no exception is thrown, using default location + unique name
     Realm.GetInstance(SpecialRealmName).Dispose();
 }
示例#45
0
        protected override void CustomTearDown()
        {
            base.CustomTearDown();

            Realm.DeleteRealm(_configuration);
        }
示例#46
0
        public static void CreateRealm(string[] args)
        {
            var realmName = Command.Read <string>(args, 0);
            var realmIP   = Command.Read <string>(args, 1);
            var realmPort = Command.Read <ushort>(args, 2);

            if (realmName != "" && realmIP != "" && realmPort != 0)
            {
                var exists = DB.Auth.Any <Realm>(r => r.Name == realmName);

                if (!exists)
                {
                    var realm = new Realm
                    {
                        Id    = DB.Auth.GetAutoIncrementValue <Realm, uint>(),
                        Name  = realmName,
                        IP    = realmIP,
                        Port  = realmPort,
                        Type  = 1,
                        State = 0,
                        Flags = 0
                    };

                    if (DB.Auth.Add(realm))
                    {
                        // Default class/expansion data (sent in AuthResponse)
                        var defaultAllowedClasses = new byte[, ] {
                            { 1, 0 }, { 2, 0 }, { 3, 0 }, { 4, 0 }, { 5, 0 }, { 6, 2 },
                            { 7, 0 }, { 8, 0 }, { 9, 0 }, { 10, 4 }, { 11, 0 }
                        };

                        // Default race/expansion data (sent in AuthResponse)
                        var defaultAllowedRaces = new byte[, ] {
                            { 1, 0 }, { 2, 0 }, { 3, 0 }, { 4, 0 }, { 5, 0 }, { 6, 0 },
                            { 7, 0 }, { 8, 0 }, { 9, 3 }, { 10, 1 }, { 11, 1 }, { 22, 3 },
                            { 24, 4 }, { 25, 4 }, { 26, 4 }
                        };

                        for (int i = 0; i < defaultAllowedClasses.Length / 2; i++)
                        {
                            DB.Auth.Add(new RealmClass
                            {
                                RealmId   = realm.Id,
                                Class     = defaultAllowedClasses[i, 0],
                                Expansion = defaultAllowedClasses[i, 1]
                            });
                        }

                        for (int i = 0; i < defaultAllowedRaces.Length / 2; i++)
                        {
                            DB.Auth.Add(new RealmRace
                            {
                                RealmId   = realm.Id,
                                Race      = defaultAllowedRaces[i, 0],
                                Expansion = defaultAllowedRaces[i, 1]
                            });
                        }

                        Log.Normal($"Realm '{realmName}' successfully created.");
                    }
                }
                else
                {
                    Log.Error($"Realm '{realmName}' already exists.");
                }
            }
        }
示例#47
0
 /// <summary>
 /// Gets the Identifier to use for the Claimed Identifier and Local Identifier of
 /// an outgoing positive assertion.
 /// </summary>
 /// <param name="localIdentifier">The OP local identifier for the authenticating user.</param>
 /// <param name="relyingPartyRealm">The realm of the relying party receiving the assertion.</param>
 /// <returns>
 /// A valid, discoverable OpenID Identifier that should be used as the value for the
 /// openid.claimed_id and openid.local_id parameters.  Must not be null.
 /// </returns>
 Uri IDirectedIdentityIdentifierProvider.GetIdentifier(Identifier localIdentifier, Realm relyingPartyRealm)
 {
     Contract.Requires <ArgumentNullException>(localIdentifier != null);
     Contract.Requires <ArgumentNullException>(relyingPartyRealm != null);
     Contract.Requires <ArgumentException>(((IDirectedIdentityIdentifierProvider)this).IsUserLocalIdentifier(localIdentifier), OpenIdStrings.ArgumentIsPpidIdentifier);
     throw new NotImplementedException();
 }
示例#48
0
 private static Realm GetRealm()
 {
     return(Realm.GetInstance());
 }
示例#49
0
 internal ModuleRecord(Engine engine, Realm realm, string location) : base(InternalTypes.Module)
 {
     _engine  = engine;
     _realm   = realm;
     Location = location;
 }
示例#50
0
        public async Task <ApiResponse <CharacterAchievementsLoader> > GetCharacterAchievementsLoaderAsync(string characterName, int categoryId, Realm realm)
        {
            ApiParams param = new ApiParams(Endpoints.AchievementsLoader, Secret, new AchievementsLoaderRequest(characterName, categoryId, realm));

            return(await CommunicateAsync <CharacterAchievementsLoader>(param));
        }
示例#51
0
 protected void CleanupOnTearDown(Realm realm)
 {
     _realms.Add(realm);
 }
示例#52
0
 public void Compact_OnWindows_ThrowsRealmException()
 {
     Assert.That(() => Realm.Compact(RealmConfiguration.DefaultConfiguration), Throws.TypeOf <RealmException>());
 }
示例#53
0
        public ApiResponse <CharacterAchievements> GetCharacterAchievements(string characterName, Realm realm)
        {
            ApiParams param = new ApiParams(Endpoints.CharacterAchievements, Secret, new CharacterAchievementsRequest(characterName, realm));

            return(Communicate <CharacterAchievements>(param));
        }
示例#54
0
 // This method was extracted to ensure that the actual realm instance
 // isn't preserved in the scope of the test, even when the debugger is running.
 private WeakReference GetWeakRealm()
 {
     return(new WeakReference(Realm.GetInstance("LifetimeTests.realm")));
 }
示例#55
0
        public ApiResponse <AchievementFirst> GetAchievementFirsts(Realm realm)
        {
            ApiParams param = new ApiParams(Endpoints.AchievementFirsts, Secret, new AchievementBaseRequest(realm));

            return(Communicate <AchievementFirst>(param));
        }
示例#56
0
 public void GetInstanceShouldThrowWithBadPath()
 {
     // Arrange
     Assert.Throws <RealmPermissionDeniedException>(() => Realm.GetInstance("/"));
 }
示例#57
0
 internal StringIteratorPrototype(
     Engine engine,
     Realm realm,
     Prototype objectPrototype) : base(engine, realm, "String Iterator", objectPrototype)
 {
 }
示例#58
0
        public async Task <ApiResponse <CharacterAchievements> > GetCharacterAchievementsAsync(string characterName, Realm realm)
        {
            ApiParams param = new ApiParams(Endpoints.CharacterAchievements, Secret, new CharacterAchievementsRequest(characterName, realm));

            return(await CommunicateAsync <CharacterAchievements>(param));
        }
示例#59
0
 public IQueryable <ProfileRealm> ToRealmResults(Realm realm)
 {
     return(((IQueryable <ProfileRealm>)realm.All <ProfileRealm>()).Where <ProfileRealm>((Expression <Func <ProfileRealm, bool> >)(x => x.Id.StartsWith(this._rolelessId))));
 }
示例#60
0
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            // Register the Popup Plugin Navigation Service
            containerRegistry.RegisterPopupNavigationService();
            containerRegistry.RegisterInstance(CreateLogger());

#if (UseRealm)
            //var serverURL = new Uri(Secrets.RealmServer);
            //var config = new SyncConfiguration(User.Current, serverURL);
            var config = RealmConfiguration.DefaultConfiguration;
    #if (AutofacContainer)
            containerRegistry.GetBuilder().Register(ctx => Realm.GetInstance(config)).As<Realm>().InstancePerDependency();
    #elseif (DryIocContainer)
            containerRegistry.GetContainer().Register(reuse: Reuse.Transient,
                               made: Made.Of(() => Realm.GetInstance(config)),
                               setup: Setup.With(allowDisposableTransient: true));
    #else
            containerRegistry.GetContainer().RegisterType<Realm>(new InjectionFactory(c => Realm.GetInstance(config)));
    #endif

#endif
#if (UseAzureMobileClient)
            containerRegistry.RegisterSingleton(typeof(ICloudTable<>), typeof(AzureCloudTable<>));
            containerRegistry.RegisterSingleton(typeof(ICloudSyncTable<>), typeof(AzureCloudSyncTable<>));
    #if (NoAuth)
            containerRegistry.RegisterInstance<IMobileServiceClient>(new MobileServiceClient(Secrets.AppServiceEndpoint));
    #else
    #if (AADAuth || AADB2CAuth)
            containerRegistry.RegisterInstance<IPublicClientApplication>(
                new PublicClientApplication(Secrets.AuthClientId, AppConstants.Authority)
                {
                    RedirectUri = AppConstants.RedirectUri
                });

        #if (AutofacContainer)
            containerRegistry.GetBuilder().RegisterType<AppDataContext>().As<IAppDataContext>().As<ICloudAppContext>().SingleInstance();
        #elseif (DryIocContainer)
            containerRegistry.GetContainer().RegisterMany<AppDataContext>(reuse: Reuse.Singleton,
                                                   serviceTypeCondition: type => 
                                                        type == typeof(IAppDataContext) ||
                                                        type == typeof(ICloudAppContext));
        #elseif (NinjectContainer)
            containerRegistry.GetContainer().Bind<IAppDataContext, ICloudAppContext>().To<AppDataContext>().InSingletonScope();
        #elseif (UnityContainer)
            containerRegistry.GetContainer().RegisterType<AppDataContext>(new ContainerControlledLifetimeManager());
            containerRegistry.GetContainer().RegisterType<IAppDataContext>(new InjectionFactory(c => c.Resolve<AppDataContext>()));
            containerRegistry.GetContainer().RegisterType<ICloudAppContext>(new InjectionFactory(c => c.Resolve<AppDataContext>()));
        #endif
    #endif
            containerRegistry.RegisterSingleton<IAzureCloudServiceOptions, AppServiceContextOptions>();
        #if (AutofacContainer)
            containerRegistry.GetBuilder().RegisterType<AppDataContext>().As<IAppDataContext>().As<ICloudService>().SingleInstance();
            containerRegistry.GetBuilder().Register(ctx => ctx.Resolve<ICloudService>().Client).As<IMobileServiceClient>().SingleInstance();
        #elseif (DryIocContainer)
            containerRegistry.GetContainer().RegisterMany<AppDataContext>(reuse: Reuse.Singleton,
                                                   serviceTypeCondition: type => 
                                                        type == typeof(IAppDataContext) ||
                                                        type == typeof(ICloudService));
            containerRegistry.GetContainer().RegisterDelegate<IMobileServiceClient>(factoryDelegate: r => r.Resolve<ICloudService>().Client,
                                                             reuse: Reuse.Singleton,
                                                             setup: Setup.With(allowDisposableTransient: true));
        #elseif (NinjectContainer)
            containerRegistry.Bind<IAppDataContext, ICloudService>().To<AppDataContext>().InSingletonScope();
            containerRegistry.Bind<IMobileServiceClient>().ToMethod(c => containerRegistry.Get<ICloudService>().Client).InSingletonScope();
        #elseif (UnityContainer)
            containerRegistry.GetContainer().RegisterType<IAppDataContext>(new InjectionFactory(c => c.Resolve<AppDataContext>()));
            containerRegistry.GetContainer().RegisterType<ICloudService>(new InjectionFactory(c => c.Resolve<AppDataContext>()));
            containerRegistry.GetContainer().RegisterType<IMobileServiceClient>(new InjectionFactory(c => c.Resolve<ICloudService>().Client));
        #endif

            containerRegistry.RegisterSingleton<ILoginProvider<AADAccount>, LoginProvider>();

#endif
#if (IncludeBarcodeService)
            // NOTE: Uses a Popup Page to contain the Scanner. You can optionally register 
            // the ContentPageBarcodeScannerService if you prefer a full screen approach.
            containerRegistry.RegisterSingleton<IBarcodeScannerService, PopupBarcodeScannerService>();
#endif
#if (UseAcrDialogs)
            containerRegistry.RegisterInstance<IUserDialogs>(UserDialogs.Instance);
#endif

            // Navigating to "TabbedPage?createTab=ViewA&createTab=ViewB&createTab=ViewC will generate a TabbedPage
            // with three tabs for ViewA, ViewB, & ViewC
            // Adding `selectedTab=ViewB` will set the current tab to ViewB
            containerRegistry.RegisterForNavigation<TabbedPage>();
            containerRegistry.RegisterForNavigation<NavigationPage>();
            containerRegistry.RegisterForNavigation<MainPage>();
#if (!Empty)
            containerRegistry.RegisterForNavigation<SplashScreenPage>();
            containerRegistry.RegisterForNavigation<TodoItemDetail>();
#endif
        }