private IList<ValueTuple<Checksum, object>> ReadAssets(
                Stream stream, int sessionId, ISet<Checksum> checksums, CancellationToken cancellationToken)
            {
                var results = new List<ValueTuple<Checksum, object>>();

                using (var reader = StreamObjectReader.TryGetReader(stream))
                {
                    Debug.Assert(reader != null,
@"We only ge a reader for data transmitted between live processes.
This data should always be correct as we're never persisting the data between sessions.");

                    var responseSessionId = reader.ReadInt32();
                    Contract.ThrowIfFalse(sessionId == responseSessionId);

                    var count = reader.ReadInt32();
                    Contract.ThrowIfFalse(count == checksums.Count);

                    for (var i = 0; i < count; i++)
                    {
                        var responseChecksum = new Checksum(reader.ReadArray<byte>());
                        Contract.ThrowIfFalse(checksums.Contains(responseChecksum));

                        var kind = reader.ReadString();

                        // in service hub, cancellation means simply closed stream
                        var @object = _owner.RoslynServices.AssetService.Deserialize<object>(kind, reader, cancellationToken);

                        results.Add(ValueTuple.Create(responseChecksum, @object));
                    }

                    return results;
                }
            }
Beispiel #2
0
        public async Task<Solution> GetSolutionAsync(Checksum solutionChecksum, CancellationToken cancellationToken)
        {
            var currentSolution = s_primaryWorkspace.CurrentSolution;

            var primarySolutionChecksum = await currentSolution.State.GetChecksumAsync(cancellationToken).ConfigureAwait(false);
            if (primarySolutionChecksum == solutionChecksum)
            {
                // nothing changed
                return currentSolution;
            }

            var lastSolution = s_lastSolution;
            if (lastSolution?.Item1 == solutionChecksum)
            {
                return lastSolution.Item2;
            }

            // make sure there is always only one that creates a new solution
            using (await s_gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
            {
                if (s_lastSolution?.Item1 == solutionChecksum)
                {
                    return s_lastSolution.Item2;
                }

                var solution = await CreateSolution_NoLockAsync(solutionChecksum, currentSolution, cancellationToken).ConfigureAwait(false);
                s_lastSolution = Tuple.Create(solutionChecksum, solution);

                return solution;
            }
        }
Beispiel #3
0
        public async Task UpdatePrimaryWorkspaceAsync(Checksum solutionChecksum, CancellationToken cancellationToken)
        {
            var currentSolution = s_primaryWorkspace.CurrentSolution;

            var primarySolutionChecksum = await currentSolution.State.GetChecksumAsync(cancellationToken).ConfigureAwait(false);
            if (primarySolutionChecksum == solutionChecksum)
            {
                // nothing changed
                return;
            }

            using (await s_gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
            {
                var updater = new SolutionCreator(_assetService, currentSolution, cancellationToken);

                if (await updater.IsIncrementalUpdateAsync(solutionChecksum).ConfigureAwait(false))
                {
                    // solution has updated
                    s_primaryWorkspace.UpdateSolution(await updater.CreateSolutionAsync(solutionChecksum).ConfigureAwait(false));
                    return;
                }

                // new solution. bulk sync all asset for the solution
                await _assetService.SynchronizeSolutionAssetsAsync(solutionChecksum, cancellationToken).ConfigureAwait(false);

                s_primaryWorkspace.ClearSolution();
                s_primaryWorkspace.AddSolution(await updater.CreateSolutionInfoAsync(solutionChecksum).ConfigureAwait(false));
            }
        }
 public ChecksumObject GetChecksumObject(Checksum checksum, CancellationToken cancellationToken)
 {
     using (Logger.LogBlock(FunctionId.SolutionChecksumServiceFactory_GetChecksumObject, GetChecksumLogInfo, checksum, cancellationToken))
     {
         return _caches.GetChecksumObject(checksum, cancellationToken);
     }
 }
            private IList<ValueTuple<Checksum, object>> ReadAssets(
                Stream stream, int sessionId, ISet<Checksum> checksums, CancellationToken cancellationToken)
            {
                var results = new List<ValueTuple<Checksum, object>>();

                using (var reader = new ObjectReader(stream))
                {
                    var responseSessionId = reader.ReadInt32();
                    Contract.ThrowIfFalse(sessionId == responseSessionId);

                    var count = reader.ReadInt32();
                    Contract.ThrowIfFalse(count == checksums.Count);

                    for (var i = 0; i < count; i++)
                    {
                        var responseChecksum = new Checksum(reader.ReadArray<byte>());
                        Contract.ThrowIfFalse(checksums.Contains(responseChecksum));

                        var kind = reader.ReadString();

                        // in service hub, cancellation means simply closed stream
                        var @object = _owner.RoslynServices.AssetService.Deserialize<object>(kind, reader, cancellationToken);

                        results.Add(ValueTuple.Create(responseChecksum, @object));
                    }

                    return results;
                }
            }
Beispiel #6
0
        public async Task<Compilation> GetCompilationAsync(Checksum solutionChecksum, ProjectId projectId, CancellationToken cancellationToken)
        {
            var solution = await RoslynServices.SolutionService.GetSolutionAsync(solutionChecksum, cancellationToken).ConfigureAwait(false);

            // TODO: need to figure out how to deal with exceptions in service hub
            return await solution.GetProject(projectId).GetCompilationAsync(cancellationToken).ConfigureAwait(false);
        }
 public RemotableData GetRemotableData(Checksum checksum, CancellationToken cancellationToken)
 {
     using (Logger.LogBlock(FunctionId.PinnedRemotableDataScope_GetRemotableData, Checksum.GetChecksumLogInfo, checksum, cancellationToken))
     {
         return _storages.GetRemotableData(this, checksum, cancellationToken);
     }
 }
 public RemotableData GetRemotableData(Checksum checksum, CancellationToken cancellationToken)
 {
     using (Logger.LogBlock(FunctionId.SolutionSynchronizationService_GetRemotableData, Checksum.GetChecksumLogInfo, checksum, cancellationToken))
     {
         return _assetStorages.GetRemotableData(scope: null, checksum: checksum, cancellationToken: cancellationToken);
     }
 }
        public async Task SynchronizeProjectAssetsAsync(Checksum projectChecksum, CancellationToken cancellationToken)
        {
            using (await s_gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
            using (var pooledObject = SharedPools.Default<HashSet<Checksum>>().GetPooledObject())
            {
                var checksums = pooledObject.Object;

                var projectChecksumObject = await _assetService.GetAssetAsync<ProjectStateChecksums>(projectChecksum, cancellationToken).ConfigureAwait(false);
                AddIfNeeded(checksums, projectChecksumObject.Children);

                foreach (var checksum in projectChecksumObject.Documents)
                {
                    var documentChecksumObject = await _assetService.GetAssetAsync<DocumentStateChecksums>(checksum, cancellationToken).ConfigureAwait(false);
                    AddIfNeeded(checksums, documentChecksumObject.Children);
                }

                foreach (var checksum in projectChecksumObject.AdditionalDocuments)
                {
                    var documentChecksumObject = await _assetService.GetAssetAsync<DocumentStateChecksums>(checksum, cancellationToken).ConfigureAwait(false);
                    AddIfNeeded(checksums, documentChecksumObject.Children);
                }

                await _assetService.SynchronizeAssetsAsync(checksums, cancellationToken).ConfigureAwait(false);
            }
        }
        public ChecksumObject GetChecksumObject(Checksum checksum, CancellationToken cancellationToken)
        {
            // search snapshots we have
            foreach (var cache in _rootTreeNodes.Values)
            {
                var checksumObject = cache.TryGetChecksumObject(checksum, cancellationToken);
                if (checksumObject != null)
                {
                    return checksumObject;
                }
            }

            // search global assets
            foreach (var asset in _globalAssets.Values)
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (asset.Checksum == checksum)
                {
                    return asset;
                }
            }

            // as long as solution snapshot is pinned. it must exist in one of the trees.
            throw ExceptionUtilities.UnexpectedValue(checksum);
        }
Beispiel #11
0
    public void ChecksumTestUnsupportedAlg()
    {
      Checksum task = new Checksum();
      task.BuildEngine = new MockBuild();

      task.Files = TaskUtility.StringArrayToItemArray( inputFiles );
      task.Algorithm = "foo";
      Assert.IsFalse( task.Execute(), "Execute Failed" );
    }
Beispiel #12
0
        public async Task<Compilation> GetCompilationAsync(Checksum solutionChecksum, ProjectId projectId, CancellationToken cancellationToken)
        {
            using (Logger.LogBlock(FunctionId.CompilationService_GetCompilationAsync, GetLogInfo, solutionChecksum, projectId, cancellationToken))
            {
                var solution = await RoslynServices.SolutionService.GetSolutionAsync(solutionChecksum, cancellationToken).ConfigureAwait(false);

                return await solution.GetProject(projectId).GetCompilationAsync(cancellationToken).ConfigureAwait(false);
            }
        }
Beispiel #13
0
    public void ChecksumTestSHA1()
    {
      Checksum task = new Checksum();
      task.BuildEngine = new MockBuild();

      task.Files = TaskUtility.StringArrayToItemArray( inputFiles );
      task.Algorithm = "SHA1";
      Assert.IsTrue( task.Execute(), "Execute Failed" );
    }
Beispiel #14
0
        public virtual void Initialize(int sessionId, byte[] solutionChecksum)
        {
            // set session related information
            _sessionId = sessionId;

            if (solutionChecksum != null)
            {
                _solutionChecksumOpt = new Checksum(solutionChecksum);
            }
        }
        public PinnedRemotableDataScope(
            AssetStorages storages,
            AssetStorages.Storage storage,
            Checksum solutionChecksum)
        {
            _storages = storages;
            _storage = storage;

            SolutionChecksum = solutionChecksum;

            _storages.RegisterSnapshot(this, storage);
        }
Beispiel #16
0
        public void TestGetAssets()
        {
            var storage = new AssetStorage();

            var checksum = new Checksum(Guid.NewGuid().ToByteArray());
            var data = new object();

            Assert.True(storage.TryAddAsset(checksum, data));

            object stored;
            Assert.True(storage.TryGetAsset(checksum, out stored));
        }
        private static Exception ReadFileHeader(Stream stream, long mStreamLength, out byte mMajorVersion, out byte mMinorVersion, out long mMetadataOffset, out long mMetadataLength, out Checksum mMetadataChecksum)
        {
            mMajorVersion = 0;
            mMinorVersion = 0;
            mMetadataOffset = 0;
            mMetadataLength = 0;
            mMetadataChecksum = default(Checksum);

            var header = new byte[ArchiveMetadataFormat.kHeaderLength];

            int offset = 0;
            do
            {
                int result = stream.Read(header, offset, ArchiveMetadataFormat.kHeaderLength - offset);
                if (result <= 0)
                    return new EndOfStreamException();

                offset += result;
            }
            while (offset < ArchiveMetadataFormat.kHeaderLength);

            for (int i = 0; i < 6; i++)
                if (header[i] != ArchiveMetadataFormat.kFileSignature[i])
                    return new InvalidDataException("File is not a 7z archive.");

            mMajorVersion = header[6];
            mMinorVersion = header[7];

            if (mMajorVersion != 0)
                return new InvalidDataException("Invalid header version.");

            mMetadataOffset = GetInt64(header, 12);
            mMetadataLength = GetInt64(header, 20);
            mMetadataChecksum = new Checksum(GetInt32(header, 28));

            uint crc = CRC.kInitCRC;
            crc = CRC.Update(crc, mMetadataOffset);
            crc = CRC.Update(crc, mMetadataLength);
            crc = CRC.Update(crc, mMetadataChecksum.Value);
            crc = CRC.Finish(crc);

            if ((int)crc != GetInt32(header, 8))
                return new InvalidDataException("Invalid header checksum.");

            if (mMetadataOffset < header.Length || mMetadataOffset > mStreamLength - ArchiveMetadataFormat.kHeaderLength)
                return new InvalidDataException("Invalid metadata offset.");

            if (mMetadataLength < 0 || mMetadataLength > mStreamLength - ArchiveMetadataFormat.kHeaderLength - mMetadataOffset)
                return new InvalidDataException("Invalid metadata length.");

            return null;
        }
Beispiel #18
0
        public async Task<Solution> GetSolutionAsync(Checksum solutionChecksum, OptionSet optionSet, CancellationToken cancellationToken)
        {
            // since option belong to workspace, we can't share solution

            // create new solution
            var solution = await CreateSolutionAsync(solutionChecksum, cancellationToken).ConfigureAwait(false);

            // set merged options
            solution.Workspace.Options = MergeOptions(solution.Workspace.Options, optionSet);

            // return new solution
            return solution;
        }
Beispiel #19
0
        public async Task<Solution> GetSolutionAsync(Checksum solutionChecksum, CancellationToken cancellationToken)
        {
            if (s_lastSolution.Item1 == solutionChecksum)
            {
                return s_lastSolution.Item2;
            }

            // create new solution
            var solution = await CreateSolutionAsync(solutionChecksum, cancellationToken).ConfigureAwait(false);

            // save it
            s_lastSolution = ValueTuple.Create(solutionChecksum, solution);

            return solution;
        }
Beispiel #20
0
        public void TestGetAssets()
        {
            var sessionId = 0;

            var storage = new AssetStorage(enableCleanup: false);
            var source = new MyAssetSource(storage, sessionId);

            var checksum = new Checksum(Guid.NewGuid().ToByteArray());
            var data = new object();

            Assert.True(storage.TryAddAsset(checksum, data));

            object stored;
            Assert.True(storage.TryGetAsset(checksum, out stored));
        }
Beispiel #21
0
        public static RemotableData Create(Checksum checksum, object value, Serializer serializer)
        {
            // treat SourceText specially since we get TextDocumentState rather than SourceText when searching the checksum
            // from solution due to it requiring async-ness when retrieving SourceText.
            //
            // right now, SourceText is the only one that requires async-ness and making all calls async just for this
            // one makes us to have a lot of unnecessary allocations due to Task and overall slow down of several seconds.
            //
            // all calls used to be all async and converted back to synchronous due to all those unnecessary overhead of tasks.
            if (value is TextDocumentState)
            {
                return new SourceTextAsset(checksum, (TextDocumentState)value, serializer);
            }

            return new SimpleSolutionAsset(checksum, value, serializer);
        }
        public DiagnosticArguments(
            bool reportSuppressedDiagnostics,
            bool logAnalyzerExecutionTime,
            ProjectId projectId,
            Checksum optionSetChecksum,
            ImmutableArray<Checksum> hostAnalyzerChecksums,
            string[] analyzerIds)
        {
            ReportSuppressedDiagnostics = reportSuppressedDiagnostics;
            LogAnalyzerExecutionTime = logAnalyzerExecutionTime;

            ProjectId = projectId;

            OptionSetChecksum = optionSetChecksum;
            HostAnalyzerChecksums = hostAnalyzerChecksums.ToArray();
            AnalyzerIds = analyzerIds;
        }
            public override async Task<object> RequestAssetAsync(int serviceId, Checksum checksum, CancellationToken callerCancellationToken)
            {
                // it should succeed as long as matching VS is alive
                // TODO: add logging mechanism using Logger

                // this can be called in two ways. 
                // 1. Connection to get asset is closed (the asset source we were using is disconnected - _assetChannelCancellationToken)
                //    if this asset source's channel is closed, service will move to next asset source to get the asset as long as callerCancellationToken
                //    is not cancelled
                //
                // 2. Request to required this asset has cancelled. (callerCancellationToken)
                using (var mergedCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(_assetChannelCancellationToken, callerCancellationToken))
                {
                    return await _rpc.InvokeAsync(WellKnownServiceHubServices.AssetService_RequestAssetAsync,
                        new object[] { serviceId, checksum.ToArray() },
                        (s, c) => ReadAssetAsync(s, _logger, serviceId, checksum, c), mergedCancellationToken.Token).ConfigureAwait(false);
                }
            }
        public async Task SynchronizeSolutionAssetsAsync(Checksum solutionChecksum, CancellationToken cancellationToken)
        {
            using (await s_gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
            {
                // this will make 4 round trip to data source (VS) to get all assets that belong to the given solution checksum

                // first, get solution checksum object for the given solution checksum
                var solutionChecksumObject = await _assetService.GetAssetAsync<SolutionStateChecksums>(solutionChecksum, cancellationToken).ConfigureAwait(false);

                // second, get direct children of the solution
                await SynchronizeSolutionAsync(solutionChecksumObject, cancellationToken).ConfigureAwait(false);

                // third, get direct children for all projects in the solution
                await SynchronizeProjectsAsync(solutionChecksumObject, cancellationToken).ConfigureAwait(false);

                // last, get direct children for all documents in the solution
                await SynchronizeDocumentsAsync(solutionChecksumObject, cancellationToken).ConfigureAwait(false);
            }
        }
Beispiel #25
0
        public async Task TestAssets()
        {
            var sessionId = 0;
            var checksum = new Checksum(Guid.NewGuid().ToByteArray());
            var data = new object();

            var storage = new AssetStorage();
            var source = new TestAssetSource(storage, sessionId, checksum, data);

            var service = new AssetService(sessionId, storage);
            var stored = await service.GetAssetAsync<object>(checksum, CancellationToken.None);
            Assert.Equal(data, stored);

            var stored2 = await service.GetAssetsAsync<object>(new[] { checksum }, CancellationToken.None);
            Assert.Equal(1, stored2.Count);

            Assert.Equal(checksum, stored2[0].Item1);
            Assert.Equal(data, stored2[0].Item2);
        }
            private static Task<object> ReadAssetAsync(
                Stream stream, TraceSource logger, int serviceId, Checksum checksum, CancellationToken cancellationToken)
            {
                using (var reader = new ObjectReader(stream))
                {
                    var responseServiceId = reader.ReadInt32();
                    Contract.ThrowIfFalse(serviceId == responseServiceId);

                    var responseChecksum = new Checksum(reader.ReadArray<byte>());
                    Contract.ThrowIfFalse(checksum == responseChecksum);

                    var kind = reader.ReadString();

                    // in service hub, cancellation means simply closed stream
                    var @object = RoslynServices.AssetService.Deserialize<object>(kind, reader, cancellationToken);

                    return Task.FromResult(@object);
                }
            }
Beispiel #27
0
        public async Task<Solution> GetSolutionAsync(Checksum solutionChecksum, OptionSet optionSet, CancellationToken cancellationToken)
        {
            if (optionSet == null)
            {
                return await GetSolutionAsync(solutionChecksum, cancellationToken).ConfigureAwait(false);
            }

            // get solution
            var baseSolution = await GetSolutionAsync(solutionChecksum, cancellationToken).ConfigureAwait(false);

            // since options belong to workspace, we can't share solution
            // create temporary workspace
            var tempWorkspace = new TemporaryWorkspace(baseSolution);

            // set merged options
            tempWorkspace.Options = MergeOptions(tempWorkspace.Options, optionSet);

            // return new solution
            return tempWorkspace.CurrentSolution;
        }
Beispiel #28
0
        public async Task<Solution> GetSolutionAsync(Checksum solutionChecksum, CancellationToken cancellationToken)
        {
            if (s_lastSolution.Item1 == solutionChecksum)
            {
                return s_lastSolution.Item2;
            }

            // make sure there is always only one that creates a new solution
            using (await s_gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
            {
                if (s_lastSolution.Item1 == solutionChecksum)
                {
                    return s_lastSolution.Item2;
                }

                var solution = await CreateSolutionAsync(solutionChecksum, cancellationToken).ConfigureAwait(false);
                s_lastSolution = ValueTuple.Create(solutionChecksum, solution);

                return solution;
            }
        }
Beispiel #29
0
        public RemotableData GetRemotableData(PinnedRemotableDataScope scope, Checksum checksum, CancellationToken cancellationToken)
        {
            if (checksum == Checksum.Null)
            {
                // check nil case
                return RemotableData.Null;
            }

            // search snapshots we have
            foreach (var storage in GetStorages(scope))
            {
                var syncObject = storage.TryGetRemotableData(checksum, cancellationToken);
                if (syncObject != null)
                {
                    return syncObject;
                }
            }

            // search global assets
            foreach (var kv in _globalAssets)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var asset = kv.Value;
                if (asset.Checksum == checksum)
                {
                    return asset;
                }
            }

            // if it reached here, it means things get cancelled. due to involving 2 processes,
            // current design can make slightly staled requests to running even when things cancelled.
            // if it is other case, remote host side will throw and close connection which will cause
            // vs to crash.
            // this should be changed once I address this design issue
            cancellationToken.ThrowIfCancellationRequested();

            return null;
        }
Beispiel #30
0
        public async Task SynchronizePrimaryWorkspaceAsync(byte[] solutionChecksum)
        {
            var checksum = new Checksum(solutionChecksum);

            using (RoslynLogger.LogBlock(FunctionId.RemoteHostService_Synchronize, c => c.ToString(), checksum, CancellationToken))
            {
                try
                {
                    await RoslynServices.SolutionService.UpdatePrimaryWorkspaceAsync(checksum, CancellationToken).ConfigureAwait(false);
                }
                catch (IOException)
                {
                    // stream to send over assets has closed before we
                    // had chance to check cancellation
                }
                catch (OperationCanceledException)
                {
                    // rpc connection has closed.
                    // this can happen if client side cancelled the
                    // operation
                }
            }
        }
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //create common query parameters for the request
            var queryParameters = new Dictionary <string, string>();// CreateQueryParameters(postProcessPaymentRequest); //mayank

            //whether to include order items in a transaction

            /*if (_PaytmPaymentSettings.PassProductNamesAndTotals) //mayank
             * {
             *  //add order items query parameters to the request
             *  var parameters = new Dictionary<string, string>(queryParameters);
             *  AddItemsParameters(parameters, postProcessPaymentRequest);
             *
             *  //remove null values from parameters
             *  parameters = parameters.Where(parameter => !string.IsNullOrEmpty(parameter.Value))
             *      .ToDictionary(parameter => parameter.Key, parameter => parameter.Value);
             *
             *  //ensure redirect URL doesn't exceed 2K chars to avoid "too long URL" exception
             *  var redirectUrl = QueryHelpers.AddQueryString(GetPaytmUrl(), parameters);
             *  if (redirectUrl.Length <= 2048)
             *  {
             *      _httpContextAccessor.HttpContext.Response.Redirect(redirectUrl);
             *      return;
             *  }
             * }*/

            //or add only an order total query parameters to the request
            string mid, mkey, amount, orderid;

            mid     = _paytmPaymentSettings.MerchantId.Trim().ToString();
            mkey    = _paytmPaymentSettings.MerchantKey.Trim().ToString();
            amount  = postProcessPaymentRequest.Order.OrderTotal.ToString("0.00");
            orderid = postProcessPaymentRequest.Order.Id.ToString();
            queryParameters.Add("MID", _paytmPaymentSettings.MerchantId.Trim().ToString());
            queryParameters.Add("WEBSITE", _paytmPaymentSettings.Website.Trim().ToString());
            queryParameters.Add("CHANNEL_ID", "WEB");
            queryParameters.Add("INDUSTRY_TYPE_ID", _paytmPaymentSettings.IndustryTypeId.Trim().ToString());
            queryParameters.Add("TXN_AMOUNT", postProcessPaymentRequest.Order.OrderTotal.ToString("0.00"));
            queryParameters.Add("ORDER_ID", postProcessPaymentRequest.Order.Id.ToString());
            queryParameters.Add("EMAIL", postProcessPaymentRequest.Order.BillingAddress.Email);
            queryParameters.Add("MOBILE_NO", postProcessPaymentRequest.Order.BillingAddress.PhoneNumber);
            queryParameters.Add("CUST_ID", postProcessPaymentRequest.Order.BillingAddress.Email);
            if (_paytmPaymentSettings.UseDefaultCallBack)
            {
                queryParameters.Add("CALLBACK_URL", _webHelper.GetStoreLocation(false) + "Plugins/PaymentPaytm/Return");
            }
            else
            {
                queryParameters.Add("CALLBACK_URL", _paytmPaymentSettings.CallBackUrl.Trim());
            }
            //queryParameters.Add("CHECKSUMHASH",
            //             paytm.CheckSum.generateCheckSum(_paytmPaymentSettings.MerchantKey, queryParameters));
            queryParameters.Add("CHECKSUMHASH",
                                Checksum.generateSignature(queryParameters, _paytmPaymentSettings.MerchantKey));
            string txntoken = GetTxnToken(amount, mid, orderid, mkey);

            //AddOrderTotalParameters(queryParameters, postProcessPaymentRequest);

            //remove null values from parameters
            queryParameters = queryParameters.Where(parameter => !string.IsNullOrEmpty(parameter.Value))
                              .ToDictionary(parameter => parameter.Key, parameter => parameter.Value);
            string scheme = _httpContextAccessor.HttpContext.Request.Scheme;
            string host   = _httpContextAccessor.HttpContext.Request.Host.ToString();

            _httpContextAccessor.HttpContext.Response.Cookies.Append("token", txntoken);
            _httpContextAccessor.HttpContext.Response.Cookies.Append("orderid", orderid);
            _httpContextAccessor.HttpContext.Response.Cookies.Append("amount", amount);
            _httpContextAccessor.HttpContext.Response.Cookies.Append("mid", mid);
            var url = QueryHelpers.AddQueryString(GetPaytmUrl(), queryParameters);
            //  _httpContextAccessor.HttpContext.Response.Redirect(url);
            var absoluteUri = string.Concat(scheme, "://", host, "/Plugins/PaymentPaytm/JSCheckoutView");

            _httpContextAccessor.HttpContext.Response.Redirect(absoluteUri);
        }
Beispiel #32
0
 void AddChecksum(byte[] bytes)
 {
     checksum = Checksum.GetChecksum(bytes, checksum);
 }
 public UnitTestingChecksumWrapper(Checksum underlyingObject) =>
Beispiel #34
0
        public Task SynchronizeTextAsync(DocumentId documentId, Checksum baseTextChecksum, IEnumerable <TextChange> textChanges, CancellationToken cancellationToken)
        {
            return(RunServiceAsync(async() =>
            {
                using (RoslynLogger.LogBlock(FunctionId.RemoteHostService_SynchronizeTextAsync, Checksum.GetChecksumLogInfo, baseTextChecksum, cancellationToken))
                {
                    var service = SolutionService.PrimaryWorkspace.Services.GetService <ISerializerService>();
                    if (service == null)
                    {
                        return;
                    }

                    var text = await TryGetSourceTextAsync().ConfigureAwait(false);
                    if (text == null)
                    {
                        // it won't bring in base text if it is not there already.
                        // text needed will be pulled in when there is request
                        return;
                    }

                    var newText = new WrappedText(text.WithChanges(textChanges));
                    var newChecksum = service.CreateChecksum(newText, cancellationToken);

                    // save new text in the cache so that when asked, the data is most likely already there
                    //
                    // this cache is very short live. and new text created above is ChangedText which share
                    // text data with original text except the changes.
                    // so memory wise, this doesn't put too much pressure on the cache. it will not duplicates
                    // same text multiple times.
                    //
                    // also, once the changes are picked up and put into Workspace, normal Workspace
                    // caching logic will take care of the text
                    AssetStorage.TryAddAsset(newChecksum, newText);
                }

                async Task <SourceText> TryGetSourceTextAsync()
                {
                    // check the cheap and fast one first.
                    // see if the cache has the source text
                    if (AssetStorage.TryGetAsset <SourceText>(baseTextChecksum, out var sourceText))
                    {
                        return sourceText;
                    }

                    // do slower one
                    // check whether existing solution has it
                    var document = SolutionService.PrimaryWorkspace.CurrentSolution.GetDocument(documentId);
                    if (document == null)
                    {
                        return null;
                    }

                    // check checksum whether it is there.
                    // since we lazily synchronize whole solution (SynchronizePrimaryWorkspaceAsync) when things are idle,
                    // soon or later this will get hit even if text changes got out of sync due to issues in VS side
                    // such as file is first opened and there is no SourceText in memory yet.
                    if (!document.State.TryGetStateChecksums(out var state) ||
                        !state.Text.Equals(baseTextChecksum))
                    {
                        return null;
                    }

                    return await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
                }
            }, cancellationToken));
        }
        private string GetTxnToken(string amount, string mid, string orderid, string mkey)
        {
            APIResponse apiresponse                 = new APIResponse();
            Dictionary <string, object> body        = new Dictionary <string, object>();
            Dictionary <string, string> head        = new Dictionary <string, string>();
            Dictionary <string, object> requestBody = new Dictionary <string, object>();

            Dictionary <string, string> txnAmount = new Dictionary <string, string>();
            string scheme       = _httpContextAccessor.HttpContext.Request.Scheme;
            string host         = _httpContextAccessor.HttpContext.Request.Host.ToString();
            string displayToken = string.Empty;

            txnAmount.Add("value", amount);
            txnAmount.Add("currency", "INR");
            Dictionary <string, string> userInfo = new Dictionary <string, string>();

            userInfo.Add("custId", "cust_001");
            body.Add("requestType", "Payment");
            body.Add("mid", mid);
            body.Add("websiteName", _paytmPaymentSettings.Website.Trim().ToString());
            body.Add("orderId", orderid);
            body.Add("txnAmount", txnAmount);
            body.Add("userInfo", userInfo);
            body.Add("callbackUrl", string.Concat(scheme, "://", host, "/Plugins/PaymentPaytm/Return"));

            /*
             * Generate checksum by parameters we have in body
             * Find your Merchant Key in your Paytm Dashboard at https://dashboard.paytm.com/next/apikeys 
             */

            string paytmChecksum = Checksum.generateSignature(JsonConvert.SerializeObject(body), mkey);

            head.Add("signature", paytmChecksum);

            requestBody.Add("body", body);
            requestBody.Add("head", head);

            string post_data = JsonConvert.SerializeObject(requestBody);
            string url       = string.Empty;

            if (_paytmPaymentSettings.env == "Stage")
            {
                //For  Staging
                url = "https://securegw-stage.paytm.in/theia/api/v1/initiateTransaction?mid=" + mid + "&orderId=" + orderid + " ";
            }
            if (_paytmPaymentSettings.env == "Prod")
            {
                //For  Production 
                url = "https://securegw.paytm.in/theia/api/v1/initiateTransaction?mid=" + mid + "&orderId=" + orderid + "";
            }
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

            webRequest.Method        = "POST";
            webRequest.ContentType   = "application/json";
            webRequest.ContentLength = post_data.Length;

            using (StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream()))
            {
                requestWriter.Write(post_data);
            }

            string responseData = string.Empty;

            using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
            {
                responseData = responseReader.ReadToEnd();
                apiresponse  = JsonConvert.DeserializeObject <APIResponse>(responseData);
                JObject jObject = JObject.Parse(responseData);
                displayToken = jObject.SelectToken("body.txnToken").Value <string>();
                //  Console.WriteLine(responseData);
            }

            return(displayToken);
        }