Пример #1
0
        private async Task <ITaskResult> TryWaitForResultAsync(
            ServiceId serviceId, MethodId routineMethodId, string intentId, TimeSpan?waitTime)
        {
            var cts            = new CancellationTokenSource();
            var completionSink = new TaskCompletionSource <ITaskResult>();

            var trackingToken = _routineCompletionNotifier.NotifyOnCompletion(
                serviceId, routineMethodId, intentId, completionSink, cts.Token);

            ITaskResult result;

            try
            {
                result = await completionSink.WithTimeout(waitTime).Task
                         .ContinueWith(t => t.IsCanceled ? null : t.Result);
            }
            catch (TaskCanceledException)
            {
                result = null;
            }
            finally
            {
                cts.Cancel();
                _routineCompletionNotifier.StopTracking(trackingToken);
            }

            return(result);
        }
Пример #2
0
 public CallerDescriptor(ServiceId service, MethodId method, EventId @event, string intentId)
 {
     Service  = service;
     Method   = method;
     Event    = @event;
     IntentId = intentId;
 }
Пример #3
0
        private async Task HandleResultPoll(HttpContext context, ServiceId serviceId, MethodId methodId, string intentId)
        {
            var rfc7240Preferences = context.Request.Headers.GetRFC7240Preferences();

            ITaskResult taskResult = null;

            var waitTime = rfc7240Preferences.Wait;

            if (waitTime > MaxLongPollTime)
            {
                waitTime = MaxLongPollTime;
            }

            if (waitTime <= TimeSpan.Zero)
            {
                taskResult = await _routineCompletionNotifier.TryPollCompletionAsync(serviceId, methodId, intentId, default);
            }
            else
            {
                taskResult = await TryWaitForResultAsync(serviceId, methodId, intentId, waitTime);
            }

            if (taskResult == null)
            {
                context.Response.Headers.Add("Date", DateTimeOffset.Now.ToString("u"));
                context.Response.StatusCode = DasyncHttpCodes.Running;
            }
            else
            {
                var compress    = context.Request.Headers.ContainsValue("Accept-Encoding", "gzip");
                var useEnvelope = context.Request.Headers.TryGetValue(DasyncHttpHeaders.Envelope, out _);
                var serializer  = GetSerializer(context.Request.GetContentType(), isQueryRequest: true);
                await RespondWithMethodResult(context.Response, taskResult, serializer, useEnvelope, compress);
            }
        }
Пример #4
0
 private void CheckIfServiceAlreadyExists(ServiceId serviceId)
 {
     if (_services.ContainsKey(serviceId))
     {
         throw new ServiceAlreadyExistsException(serviceId);
     }
 }
        public long NotifyOnCompletion(ServiceId serviceId, MethodId methodId, string intentId, TaskCompletionSource <ITaskResult> completionSink, CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                return(-1);
            }

            var trackedInvocation = new TrackedInvocation
            {
                Token             = Interlocked.Increment(ref _tokenCounter),
                ServiceId         = serviceId,
                MethodId          = methodId,
                IntentId          = intentId,
                CompletionSink    = completionSink,
                CancellationToken = ct
            };

            SetPollingMethod(trackedInvocation);

            LinkedListNode <TrackedInvocation> listNode;

            lock (_trackedInvocations)
            {
                listNode = _trackedInvocations.AddLast(trackedInvocation);
            }

            trackedInvocation.PollTimer = new Timer(_onTimerTick, listNode, Timeout.Infinite, Timeout.Infinite);
            ScheduleNextPoll(trackedInvocation);

            return(trackedInvocation.Token);
        }
Пример #6
0
        public void GetServiceIdTest()
        {
            var testJObject = new JObject()
            {
                new JProperty("LoginUser", new JObject()
                {
                    new JProperty("AccessId", "abc123")
                }),
                new JProperty("AuthorizeUser", new JObject()
                {
                    new JProperty("ServiceId", "abc123")
                })
            };

            var messageHandler = new FakeHttpMessageHandler(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(JsonConvert.SerializeObject(testJObject), Encoding.UTF8, "application/json")
            });

            var mockServiceClient   = new MockServiceClient(messageHandler);
            var mockGraphService    = new MockGraphService();
            var mockB2CGraphService = new MockB2CGraphService();

            var serviceId = new ServiceId(mockGraphService, mockB2CGraphService, mockServiceClient);

            const string expectedOutput = "abc123";
            var          result         = serviceId.GetServiceId(ServiceUrl.Url, "fakeToken").Result;

            Assert.Equal(expectedOutput, result);
        }
Пример #7
0
 public override string ToString()
 {
     return($"{{{nameof(MsgId)}={MsgId}, " +
            $"{nameof(PkTotal)}={PkTotal}, " +
            $"{nameof(PkNumber)}={PkNumber}, " +
            $"{nameof(RegisteredDelivery)}={RegisteredDelivery}, " +
            $"{nameof(MsgLevel)}={MsgLevel}, " +
            $"{nameof(ServiceId)}={ServiceId?.TrimEnd('\0')}, " +
            $"{nameof(FeeUserType)}={FeeUserType}, " +
            $"{nameof(FeeTerminalId)}={FeeTerminalId.TrimEnd('\0')}, " +
            $"{nameof(FeeTerminalType)}={FeeTerminalType}, " +
            $"{nameof(TPPId)}={TPPId}, {nameof(TPUdhi)}={TPUdhi}, " +
            $"{nameof(MsgFmt)}={MsgFmt}, {nameof(MsgSrc)}={MsgSrc}, " +
            $"{nameof(FeeType)}={FeeType.TrimEnd('\0')}, " +
            $"{nameof(FeeCode)}={FeeCode.TrimEnd('\0')}, " +
            $"{nameof(ValidTime)}={ValidTime.TrimEnd('\0')}, " +
            $"{nameof(AtTime)}={AtTime.TrimEnd('\0')}, " +
            $"{nameof(SrcId)}={SrcId.TrimEnd('\0')}, " +
            $"{nameof(DestUsrTl)}={DestUsrTl}, " +
            $"{nameof(DestTerminalId)}={(DestTerminalId.Length>0?DestTerminalId[0].TrimEnd('\0'):"")}, " +
            $"{nameof(DestTerminalType)}={DestTerminalType}, " +
            $"{nameof(MsgLength)}={MsgLength}, " +
            $"{nameof(MsgContent)}={MsgContent}, " +
            //$"{nameof(LinkId)}={LinkId?.TrimEnd('\0')}, " +
            $"{nameof(Reserve)}={Reserve?.TrimEnd('\0')}}}");
 }
Пример #8
0
        private async Task <RowSet> ExecuteQueryAsync(ServiceId serviceId, MethodId methodId, string query)
        {
            var session = await Session();

@TryExecute:
            try
            {
                return(await session.ExecuteAsync(new SimpleStatement(query.ToString())));
            }
            catch (InvalidQueryException ex)
            {
                if (ex.Message.StartsWith("Keyspace ")) // asumme "Keyspace {name} does not exist"
                {
                    session.CreateKeyspaceIfNotExists(GetKeyspaceName(serviceId));
                    await CreateTableIfNotExistsAsync(session, GetKeyspaceName(serviceId), GetTableName(serviceId, methodId));

                    goto TryExecute;
                }
                else if (ex.Message.StartsWith("unconfigured table ")) // assume "unconfigured table {name}"
                {
                    await CreateTableIfNotExistsAsync(session, GetKeyspaceName(serviceId), GetTableName(serviceId, methodId));

                    goto TryExecute;
                }
                else
                {
                    throw;
                }
            }
        }
 public ExternalServiceDefinition(
     IExternalCommunicationModel model,
     ServiceId serviceId)
 {
     Model = model;
     Id    = serviceId.Clone();
 }
Пример #10
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (ServiceId.Length != 0)
            {
                hash ^= ServiceId.GetHashCode();
            }
            if (ServiceAliasId.Length != 0)
            {
                hash ^= ServiceAliasId.GetHashCode();
            }
            if (MethodId.Length != 0)
            {
                hash ^= MethodId.GetHashCode();
            }
            if (source_ != null)
            {
                hash ^= Source.GetHashCode();
            }
            if (target_ != null)
            {
                hash ^= Target.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Пример #11
0
        private ServiceAndMethodDefinitions Resolve(ServiceId serviceId, MethodId methodId, bool assumeExternal = false)
        {
            var result = new ServiceAndMethodDefinitions();

            if (_serviceResolver.TryResolve(serviceId, out var serviceRef))
            {
                result.Service = serviceRef.Definition;

                // NOTE: system services are not unique within a multi-service ecosystem, thus must
                // use the configuration of the calling (proxy) service without any specific method.
                // Otherwise, a continuation can be sent to a wrong instance of a system service.
                if (result.Service.Type == ServiceType.System && !string.IsNullOrEmpty(serviceId.Proxy))
                {
                    return(Resolve(new ServiceId {
                        Name = serviceId.Proxy
                    }, null, assumeExternal));
                }

                result.Method = methodId == null ? null : _methodResolver.Resolve(result.Service, methodId).Definition;
            }
            else if (assumeExternal)
            {
                var externalServiceDefinition = _externalCommunicationModel.GetOrAddService(serviceId);
                var externalMethodDefinition  = methodId == null ? null : externalServiceDefinition.GetOrAddMethod(methodId);
                result.Service = externalServiceDefinition;
                result.Method  = externalMethodDefinition;
            }
            else
            {
                throw new ServiceResolveException(serviceId);
            }

            return(result);
        }
Пример #12
0
        public async Task <MethodExecutionState> ReadStateAsync(ServiceId serviceId, PersistedMethodId methodId, CancellationToken ct)
        {
            var fileName = GetStateFileName(serviceId, methodId);
            var filePath = Path.Combine(_stateDirectory, fileName);

            string etag;

            byte[] data;

            try
            {
                using (var fileStream = new FileStream(
                           filePath, FileMode.Open, FileAccess.Read, FileShare.Read,
                           FileBufferSize, FileOptions.Asynchronous))
                {
                    etag = TryGetETag(filePath);
                    data = new byte[fileStream.Length];
                    await fileStream.ReadAsync(data, 0, data.Length);
                }
            }
            catch (IOException)
            {
                throw new StateNotFoundException(serviceId, methodId);
            }

            // TODO: select serializer
            var executionState = _serializer.Deserialize <MethodExecutionState>(data);

            return(executionState);
        }
Пример #13
0
        private void Receive(IAsyncResult asyncResult)
        {
            try
            {
                var    remote = new IPEndPoint(IPAddress.Any, 0);
                byte[] buffer = _udp.EndReceive(asyncResult, ref remote);

                if (buffer != null && buffer.Length > 0 &&
                    Protocol.TryDecodeBeaconMessage(buffer, out BeaconMessage message) &&
                    ServiceId.Equals(message.ServiceId))
                {
                    AddLocation(message, remote);
                }

                _udp.BeginReceive(Receive, null);
            }
            catch (ObjectDisposedException)
            {
                // Normal behavior of UdpClient/Socket to throw when closed.
            }
            catch (SocketException e)
            {
                // Interrupted is a possible exception when closing the Probe, let it go.
                if (e.SocketErrorCode != SocketError.Interrupted)
                {
                    throw;
                }
            }
        }
Пример #14
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("----------- ECM INFO -----------");
            sb.Append("Service ID: 0x");
            sb.AppendLine(ServiceId.ToString("x4"));
            sb.Append("PID:        0x");
            sb.AppendLine(Pid.ToString("x4"));
            sb.Append("Caid:       0x");
            sb.AppendLine(CaId.ToString("x4"));
            sb.Append("ProvId:     0x");
            sb.AppendLine(ProviderId.ToString("x6"));
            sb.Append("Cardsystem: ");
            sb.AppendLine(CardSystem);
            sb.Append("Reader:     ");
            sb.AppendLine(ReaderName);
            sb.Append("Source:     ");
            sb.AppendLine(SourceName);
            sb.Append("Protocol:   ");
            sb.AppendLine(ProtocolName);
            sb.Append("Hops:       ");
            sb.AppendLine(HopsCount.ToString());
            sb.Append("Time:       ");
            sb.Append(EcmTime.ToString());
            sb.AppendLine("ms");
            sb.AppendLine("----------- ECM INFO -----------");

            return(sb.ToString());
        }
Пример #15
0
 public RemoveService(
     DomainName domainName,
     ServiceId serviceId)
 {
     DomainName = domainName;
     ServiceId  = serviceId;
 }
Пример #16
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (JobId.Length != 0)
            {
                hash ^= JobId.GetHashCode();
            }
            if (ServiceId != 0)
            {
                hash ^= ServiceId.GetHashCode();
            }
            if (MessageId != 0)
            {
                hash ^= MessageId.GetHashCode();
            }
            if (Data.Length != 0)
            {
                hash ^= Data.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Пример #17
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (ClientIp.Length != 0)
            {
                hash ^= ClientIp.GetHashCode();
            }
            if (XRequestId.Length != 0)
            {
                hash ^= XRequestId.GetHashCode();
            }
            if (ServiceId != 0)
            {
                hash ^= ServiceId.GetHashCode();
            }
            if (MessageId != 0)
            {
                hash ^= MessageId.GetHashCode();
            }
            if (Delay != 0)
            {
                hash ^= Delay.GetHashCode();
            }
            if (Data.Length != 0)
            {
                hash ^= Data.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Пример #18
0
        public async Task <InvokeRoutineResult> GetInvocationResultAsync(
            ServiceId serviceId,
            MethodId methodId,
            string intentId,
            Type resultValueType,
            CancellationToken ct)
        {
            var storage = _methodStateStorageProvider.GetStorage(serviceId, methodId, returnNullIfNotFound: true);

            if (storage == null)
            {
                return(new InvokeRoutineResult
                {
                    Outcome = InvocationOutcome.Unknown
                });
            }

            var taskResult = await storage.TryReadResultAsync(serviceId, methodId, intentId, resultValueType, ct);

            return(new InvokeRoutineResult
            {
                Result = taskResult,
                Outcome = taskResult != null
                    ? InvocationOutcome.Complete
                    : InvocationOutcome.Scheduled
            });
        }
Пример #19
0
        private EventingHttpClient CreateEventingClient(ServiceId serviceId)
        {
            var serviceRef = _serviceResolver.Resolve(serviceId);

            var configuration = _communicationModelConfiguration.GetCommandsConfiguration(serviceRef.Definition, "communication");
            var settings      = new HttpCommunicatorSettings();

            configuration.Bind(settings);

            var serializer = string.IsNullOrEmpty(settings.Serializer)
                ? _defaultSerializerProvider.DefaultSerializer
                : _serializerProvider.GetSerializer(settings.Serializer);
            var compressPayload = settings.Compress ?? false;
            var urlTemplate     = HttpCommunicationMethod.GetUrlTemplate(settings);

            var schemeDelimiterIndex = urlTemplate.IndexOf("://");
            var firstSegmentIndex    = urlTemplate.IndexOf('/', schemeDelimiterIndex > 0 ? schemeDelimiterIndex + 3 : 0);
            var address = firstSegmentIndex > 0 ? urlTemplate.Substring(0, firstSegmentIndex) : urlTemplate;

            address = address.Replace("{serviceName}", serviceRef.Definition.Name);

            var urlBase = address + "/dev/events";

            return(new EventingHttpClient(serializer, urlBase));
        }
Пример #20
0
 public ServiceReference(IDomainServiceProvider domainServiceProvider,
                         ServiceId serviceId, IServiceDefinition serviceDefinition)
 {
     _domainServiceProvider = domainServiceProvider;
     Id         = serviceId;
     Definition = serviceDefinition;
 }
Пример #21
0
        public Task WriteResultAsync(ServiceId serviceId, MethodId methodId, string intentId, ITaskResult result)
        {
            var serializedTaskResult = _serializer.SerializeToString(result);

            var expectedETag = (methodId as PersistedMethodId)?.ETag;

            lock (_entryMap)
            {
                if (!_entryMap.TryGetValue(intentId, out var entry))
                {
                    entry = new StorageEntry();
                    _entryMap.Add(intentId, entry);
                }
                else if (!string.IsNullOrEmpty(expectedETag) && entry.ETag != expectedETag)
                {
                    throw new ETagMismatchException(expectedETag, entry.ETag);
                }

                entry["ServiceId"] = serviceId.Clone();
                entry["MethodId"]  = methodId.Clone();
                entry["Result"]    = serializedTaskResult;
                entry.ETag         = DateTimeOffset.UtcNow.Ticks.ToString();
            }

            return(Task.CompletedTask);
        }
Пример #22
0
 public override int GetHashCode()
 {
     unchecked
     {
         return(((ServiceId?.GetHashCode() ?? 0) * 397) ^ (PlanId?.GetHashCode() ?? 0));
     }
 }
Пример #23
0
        public IFabricConnector GetConnector(ServiceId serviceId)
        {
            if (!_serviceToQueueMap.TryGetValue(serviceId.ServiceName, out var transitionsQueue))
            {
                // Fall back to the queue of a function currently being executed.
                // This is needed for the Intrinsic Routines.
                // Such code is not needed for the gateway, and you are not allowed to call
                // Intrinsic Routines directly from the gateway.
                transitionsQueue = _currentFunction.Value.Queue;
            }

            if (transitionsQueue == null)
            {
                throw new InvalidOperationException(
                          $"Cannot find queue for the service '{serviceId.ServiceName}'.");
            }

            var configuration = new AzureStorageFabricConnectorConfiguration
            {
                SerializerFormat     = "dasyncjson",
                TransitionsQueueName = transitionsQueue.Name,
                RoutinesTableName    = _routinesTable.Name,
                ServicesTableName    = _servicesTable.Name,
                StorageAccountName   = ConnectionStringParser.GetAccountName(_storageAccountConnectionString)
            };

            return(new AzureStorageFabricConnectorWithConfiguration(
                       serviceId,
                       _idGenerator,
                       transitionsQueue,
                       _routinesTable,
                       _defaultSerializer,
                       configuration));
        }
Пример #24
0
 public override int GetHashCode()
 {
     unchecked
     {
         return(((ServiceId != null ? ServiceId.GetHashCode() : 0) * 397) ^ ServiceAlias.GetHashCode());
     }
 }
Пример #25
0
        internal async Task DeleteTableEntries()
        {
            if (ServiceId.Equals(Guid.Empty) && DeploymentId == null)
            {
                await DeleteTableAsync();
            }
            else
            {
                List <Tuple <ReminderTableEntry, string> > entries = await FindAllReminderEntries();

                // return manager.DeleteTableEntries(entries); // this doesnt work as entries can be across partitions, which is not allowed
                // group by grain hashcode so each query goes to different partition
                var tasks         = new List <Task>();
                var groupedByHash = entries
                                    .Where(tuple => tuple.Item1.ServiceId.Equals(ReminderTableEntry.ConstructServiceIdStr(ServiceId)))
                                    .Where(tuple => tuple.Item1.DeploymentId.Equals(DeploymentId)) // delete only entries that belong to our DeploymentId.
                                    .GroupBy(x => x.Item1.GrainRefConsistentHash).ToDictionary(g => g.Key, g => g.ToList());

                foreach (var entriesPerPartition in groupedByHash.Values)
                {
                    foreach (var batch in entriesPerPartition.BatchIEnumerable(AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS))
                    {
                        tasks.Add(DeleteTableEntriesAsync(batch));
                    }
                }

                await Task.WhenAll(tasks);
            }
        }
Пример #26
0
 private string GetTableName(ServiceId serviceId, MethodId methodId)
 {
     return(_settings.TableName
            .Replace("{serviceName}", serviceId.Name)
            .Replace("{methodName}", methodId.Name)
            .ToLowerInvariant());
 }
Пример #27
0
        public void IsRequestAuthorized_rawUrlIsExcludedButIncludedBeforeThat_shouldDisallowRequest()
        {
            // Arrange
            var pathCollection = new PathCollection
            {
                new PathConfig {
                    Name = "included", Path = ".*", Type = PathConfig.PathType.Include
                },
                new PathConfig {
                    Name = "excluded", Path = "/public/.*", Type = PathConfig.PathType.Exclude
                }
            };
            var service = new HmacHttpService(ServiceId.ToString(), pathCollection, "signature")
            {
                UserRepository = new Mock <IUserRepository>().Object,
                AppRepository  = new Mock <IAppRepository>().Object,
                HmacService    = new HmacSha256Service()
            };

            // Act
            var actual = service.IsRequestAuthorized(GetValidRawUrl(false), CreateInvalidQueryString());

            // Assert
            Assert.AreEqual(StatusCode.ParameterMissing, actual);
        }
Пример #28
0
        public object Build(ServiceId serviceId, string[] additionalInterfaces)
        {
            var registration = _serviceRegistry.AllRegistrations
                               .SingleOrDefault(r => r.ServiceName == serviceId.ServiceName);

            Type proxyType;

            if (registration?.ImplementationType != null)
            {
                proxyType = _proxyTypeBuilder.Build(registration.ImplementationType);
            }
            else
            {
                var interfacesTypes = new List <Type>(additionalInterfaces?.Length ?? 1);

                if (registration?.ServiceType != null)
                {
                    interfacesTypes.Add(registration.ServiceType);
                }

                if (additionalInterfaces != null)
                {
                    foreach (var typeFullName in additionalInterfaces)
                    {
#warning Use better type resolver?
                        var type = Type.GetType(typeFullName, throwOnError: false);
                        if (type != null)
                        {
                            interfacesTypes.Add(type);
                        }
                    }
                }

                proxyType = _proxyTypeBuilder.Build(interfacesTypes);
            }

            var allInterfaces = proxyType
                                .GetInterfaces()
                                .Where(i => i != typeof(IProxy))
                                .Select(i => i.AssemblyQualifiedName);

            if (additionalInterfaces != null)
            {
                allInterfaces = allInterfaces.Union(additionalInterfaces).Distinct();
            }

#warning Needs ability to inject services with different Service IDs (parent Service ID?) as a part of service mesh framework.
            var proxy = (IProxy)_appServiceIocContainer.Resolve(proxyType);
            proxy.Executor = _proxyMethodExecutor;
            proxy.Context  = new ServiceProxyContext
            {
                Service = new ServiceDescriptor
                {
                    Id         = serviceId,
                    Interfaces = allInterfaces.ToArray()
                }
            };
            return(proxy);
        }
Пример #29
0
        public GoogleSuiteService(
            ServiceId serviceId,
            GoogleVerificationToken verificationToken)
        {
            ServiceId = serviceId;

            _verificationToken = verificationToken;
        }
Пример #30
0
 public object Build(ServiceId serviceId, string[] additionalInterfaces)
 {
     if (Builder == null)
     {
         throw new InvalidOperationException();
     }
     return(Builder.Build(serviceId, additionalInterfaces));
 }
        public static Task<Service> GetServiceAsync(this IContentDeliveryService service, ServiceId serviceId, CancellationToken cancellationToken)
        {
            if (service == null)
                throw new ArgumentNullException("service");

            return TaskBlocks.Using(
                () => service.PrepareGetServiceAsync(serviceId, cancellationToken),
                task => task.Result.SendAsync(cancellationToken).Select(innerTask => innerTask.Result.Item2));
        }
Пример #32
0
        public IndieCityManager(string gameId, string serviceId, string serviceSecret, bool hasAchievements, bool hasLeaderboards, IManagerServiceProvider serviceProvider, SessionEndDelegate sessionEndDelegate)
        {
            _sceneInterface = serviceProvider;
            _sessionEndDelegate = sessionEndDelegate;

            ManagerProcessOrder = 10;

            var service = new ServiceId
                              {
                                  Data1 = uint.Parse(serviceId.Substring(0, 8), NumberStyles.HexNumber),
                                  Data2 = ushort.Parse(serviceId.Substring(9, 4), NumberStyles.HexNumber),
                                  Data3 = ushort.Parse(serviceId.Substring(14, 4), NumberStyles.HexNumber),
                                  Data4 = new[]
                                              {
                                                  byte.Parse(serviceId.Substring(19, 2), NumberStyles.HexNumber),
                                                  byte.Parse(serviceId.Substring(21, 2), NumberStyles.HexNumber),
                                                  byte.Parse(serviceId.Substring(24, 2), NumberStyles.HexNumber),
                                                  byte.Parse(serviceId.Substring(26, 2), NumberStyles.HexNumber),
                                                  byte.Parse(serviceId.Substring(28, 2), NumberStyles.HexNumber),
                                                  byte.Parse(serviceId.Substring(30, 2), NumberStyles.HexNumber),
                                                  byte.Parse(serviceId.Substring(32, 2), NumberStyles.HexNumber),
                                                  byte.Parse(serviceId.Substring(34, 2), NumberStyles.HexNumber)
                                              }
                              };

            var bridge = new CoBridge2();
            bridge.Initialise(gameId);
            bridge.SetServiceCredentials(GameService.GameService_IndieCityLeaderboardsAndAchievements, service, serviceSecret);

            Session = bridge.CreateDefaultGameSession();
            _sessionCookie = Session.RegisterEventHandler(0, 0, this);
            _sessionActive = false;
            _startPhase = SessionStartPhase.NotStarted;

            _username = bridge.UserStore.GetUserFromId(Session.UserId).Name;

            _achievementsReady = !hasAchievements;
            if (hasAchievements)
            {
                AchievementsManager = new CoAchievementManager();
                AchievementsManager.SetGameSession(Session);
                AchievementsManager.InitialiseAchievements(null);
                _achievementsCookie = ((IAchievementService) AchievementsManager).RegisterAchievementEventHandler(this);
                _achievementsUnlockedAtIndieCity = new Dictionary<long, bool>();
            }

            _leaderboardsReady = !hasLeaderboards;
            if (hasLeaderboards)
            {
                _leaderboardsManager = new CoLeaderboardManager();
                _leaderboardsManager.SetGameSession(Session);
                _leaderboardsManager.InitialiseLeaderboards(null);
                _leaderboardsCookie = ((ILeaderboardService) _leaderboardsManager).RegisterLeaderboardEventHandler(this);
            }
        }
        /// <summary>
        /// Sets (or removes) the <c>marker</c> query parameter for a <see cref="ListServicesApiCall"/> HTTP API call.
        /// </summary>
        /// <param name="apiCall">The prepared HTTP API call.</param>
        /// <param name="serviceId">
        /// <para>The ID of the last <see cref="Service"/> in the previous page of results.</para>
        /// <para>-or-</para>
        /// <para><see langword="null"/> to remove the <c>marker</c> query parameter and have the resulting page start
        /// with the first item in the list.</para>
        /// </param>
        /// <returns>Returns the input argument <paramref name="apiCall"/>, which was modified according to the
        /// specified <paramref name="serviceId"/>.</returns>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="apiCall"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ObjectDisposedException">If the HTTP API call has been disposed.</exception>
        /// <exception cref="InvalidOperationException">If the HTTP API call has already been sent.</exception>
        public static ListServicesApiCall WithMarker(this ListServicesApiCall apiCall, ServiceId serviceId)
        {
            if (apiCall == null)
                throw new ArgumentNullException("apiCall");
            if (serviceId == null)
                throw new ArgumentNullException("serviceId");

            Uri uri = apiCall.RequestMessage.RequestUri;
            if (serviceId == null)
                apiCall.RequestMessage.RequestUri = UriUtility.RemoveQueryParameter(uri, "marker");
            else
                apiCall.RequestMessage.RequestUri = UriUtility.SetQueryParameter(uri, "marker", serviceId.Value);

            return apiCall;
        }
        public static Task RemoveAssetAsync(this IContentDeliveryService service, ServiceId serviceId, CancellationToken cancellationToken, string urlOfAsset = null, bool deleteAll = false)
        {
            if (service == null)
                throw new ArgumentNullException("service");

            return TaskBlocks.Using(
                () => service.PrepareRemoveAssetAsync(serviceId, cancellationToken, urlOfAsset, deleteAll),
                task => task.Result.SendAsync(cancellationToken));
        }
        public static Task UpdateServiceAsync(this IContentDeliveryService service, ServiceId serviceId, ServiceData updatedServiceData, CancellationToken cancellationToken)
        {
            if (service == null)
                throw new ArgumentNullException("service");

            return TaskBlocks.Using(
                () => service.PrepareUpdateServiceAsync(serviceId, updatedServiceData, cancellationToken),
                task => task.Result.SendAsync(cancellationToken));
        }
 /// <summary>
 /// Sets (or removes) the <c>marker</c> query parameter for a <see cref="ListServicesApiCall"/> HTTP API call.
 /// </summary>
 /// <remarks>
 /// <para>This method simplifies the use of <see cref="WithMarker(ListServicesApiCall, ServiceId)"/> in
 /// scenarios where <see langword="async/await"/> are not used for the preparation of the HTTP API call.</para>
 /// </remarks>
 /// <param name="apiCall">A <see cref="Task"/> representing the asynchronous operation to prepare the HTTP API
 /// call.</param>
 /// <param name="serviceId">
 /// <para>The ID of the last <see cref="Service"/> in the previous page of results.</para>
 /// <para>-or-</para>
 /// <para><see langword="null"/> to remove the <c>marker</c> query parameter and have the resulting page start
 /// with the first item in the list.</para>
 /// </param>
 /// <returns>A <see cref="Task"/> representing the asynchronous operation. When the task completes successfully,
 /// the <see cref="Task{TResult}.Result"/> property contains the result of the input task
 /// <paramref name="apiCall"/>, which was modified according to the specified
 /// <paramref name="serviceId"/>.</returns>
 /// <exception cref="ArgumentNullException">
 /// If <paramref name="apiCall"/> is <see langword="null"/>.
 /// </exception>
 /// <exception cref="ObjectDisposedException">If the HTTP API call has been disposed.</exception>
 /// <exception cref="InvalidOperationException">If the HTTP API call has already been sent.</exception>
 /// <seealso href="http://docs.openstack.org/api/openstack-identity-service/2.0/content/Paginated_Collections-d1e325.html">Paginated collections (OpenStack Identity API v2.0 Reference)</seealso>
 public static Task<ListServicesApiCall> WithMarker(this Task<ListServicesApiCall> apiCall, ServiceId serviceId)
 {
     return apiCall.Select(task => apiCall.Result.WithMarker(serviceId));
 }
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            #if !INTERNAL && !INDIECITY
            if(!Program.Apprehensive)
            {
                ShowMissingRequirementMessage(new Exception("An invalid operation was performed."));
                Exit();
            }

            try
            {
            #if !DEBUG
                var k = Registry.CurrentUser.OpenSubKey("inf_data_AD");
                if((int)k.GetValue("potato", 0) != 1)
                    throw new Exception();
            #endif
            }
            catch
            {
                ShowMissingRequirementMessage(new Exception("An invalid operation was performed."));
                Registry.CurrentUser.DeleteSubKeyTree("inf_data_AD", false);
                Exit();
            }
            Registry.CurrentUser.DeleteSubKeyTree("inf_data_AD", false);
            #elif INDIECITY
            //create bridge
            Bridge = new CoBridge2();

            //Set your game ids here as given from your game project page
            string myGameId = "50ff0fa6-7628-419f-bfc7-50ead82077bc";
            serviceID = new ServiceId();
            serviceID.Data1 = 0x7710ab33;
            serviceID.Data2 = 0xf822;
            serviceID.Data3 = 0x4297;
            serviceID.Data4 = new byte[] { 0xb9, 0x74, 0x05, 0x64, 0x4f, 0x2a, 0x1b, 0xd8 };
            string myICELibSecret = "bad7922a-0d9e-42c8-8445-32f99e90d323";

            //Initialise the bridge with the gameId and secret.
            //This allows the bridge to access users tokens registered on the computer
            Bridge.Initialise(myGameId);
            Bridge.SetServiceCredentials(GameService.GameService_IndieCityLeaderboardsAndAchievements, serviceID, myICELibSecret);

            UserID = Bridge.DefaultUserId;
            UserStore = Bridge.UserStore;
            UserInfo = UserStore.GetUserFromId(UserID);
            //Program.Cutter.WriteToLog(this, "here");
            string userName = UserInfo.Name;
            //Program.Cutter.WriteToLog(this, "username is: " + userName);

            //RegistryKey k1 = null, k2 = null;
            //using(k1 = Registry.CurrentUser.OpenSubKey("Software", true))
            //    using(k2 = k1.CreateSubKey("Accelerated Delivery"))
            //    {
            //        Program.Cutter.WriteToLog(this, "username is: " + userName);
            //        k2.SetValue("username", userName);
            //    }

            //create a game session for the user playing the game
            Session = Bridge.CreateDefaultGameSession();

            //Start the session
            Session.RequestStartSession();

            //block until session has started
            //This is just for simplicity. Real game would react to session start and end events. Session
            //may end for different reasons or may never start.

            bool started = false;
            int sleptFor = 0;
            do
            {
                Session.UpdateSession();
                started = Session.IsSessionStarted();
                System.Threading.Thread.Sleep(100);
                sleptFor += 100;
                if(sleptFor > 20000)
                {
                    error = true;
                    SuppressDraw();
                    new Error().Show();
                    return;
                }
            } while(!started);
            #endif

            GDM.PreferredBackBufferWidth = PreferredScreenWidth;
            GDM.PreferredBackBufferHeight = PreferredScreenHeight;

            // supported resolutions are 800x600, 1280x720, 1366x768, 1980x1020, and 1024x768
            int width = GraphicsDevice.DisplayMode.Width;
            int height = GraphicsDevice.DisplayMode.Height;
            if(width > 800) // this setup doesn't account for aspect ratios, which may be a problem
            {
                if(width > 1024)
                {
                    if(width > 1280)
                    {
                        if(width > 1366)
                        {
                            GDM.PreferredBackBufferWidth = 1366;
                            GDM.PreferredBackBufferHeight = 768;
                        }
                        else
                        {
                            GDM.PreferredBackBufferWidth = 1280;
                            GDM.PreferredBackBufferHeight = 720;
                        }
                    }
                    else
                    {
                        GDM.PreferredBackBufferWidth = 1024;
                        GDM.PreferredBackBufferHeight = 768;
                    }
                }
            }
            else if(width < 800)
            {
                ShowMissingRequirementMessage(new Exception("The game requires at least an 800x600 screen resolution."));
                Exit();
            }
            else
            {
                GDM.PreferredBackBufferWidth = 800;
                GDM.PreferredBackBufferHeight = 600;
            }

            GameManager.FirstStageInitialization(this, Program.Cutter);

            AccomplishmentManager.InitAchievements();

            try { Manager = new IOManager(); }
            catch { }

            if(Manager != null)
                if(Manager.SuccessfulLoad)
                {
                    GDM.IsFullScreen = Manager.FullScreen;
                    GDM.PreferredBackBufferHeight = Manager.CurrentSaveWindowsOptions.ScreenHeight;
                    GDM.PreferredBackBufferWidth = Manager.CurrentSaveWindowsOptions.ScreenWidth;
                    MenuHandler.SaveLoaded();
                }

            Program.Game.Manager.CurrentSaveWindowsOptions.FancyGraphics = false;
            if(GDM.GraphicsDevice.Adapter.IsProfileSupported(GraphicsProfile.HiDef))
            {
                GDM.GraphicsProfile = GraphicsProfile.HiDef;
                Program.Game.Manager.CurrentSaveWindowsOptions.FancyGraphics = true;
            }

            GDM.ApplyChanges();

            //#if DEBUG
            //            if(HiDef)
            //                drawer = new InstancedModelDrawer(this);
            //            else
            //                drawer = new BruteModelDrawer(this);
            //#endif

            base.Initialize();
        }