public async Task Test_AddOrUpdateEndpoints_RemoveEndpoints(string publishedNodesFile)
        {
            Utils.CopyContent(publishedNodesFile, _tempFile);
            InitStandaloneJobOrchestrator();

            string payload         = Utils.GetFileContent(publishedNodesFile);
            var    payloadRequests = _newtonSoftJsonSerializer.Deserialize <List <PublishedNodesEntryModel> >(payload);

            var previousDataSets = new List <PublishedNodesEntryModel>();

            int index = 0;

            foreach (var request in payloadRequests)
            {
                request.OpcNodes = index % 2 == 0
                    ? null
                    : new List <OpcNodeModel>();
                ++index;

                var sameDataSetRemoved = false;
                foreach (var dataSet in previousDataSets)
                {
                    sameDataSetRemoved = sameDataSetRemoved || request.HasSameDataSet(dataSet);
                }

                if (sameDataSetRemoved)
                {
                    await FluentActions
                    .Invoking(async() => await _standaloneJobOrchestrator
                              .AddOrUpdateEndpointsAsync(new List <PublishedNodesEntryModel> {
                        request
                    })
                              .ConfigureAwait(false))
                    .Should()
                    .ThrowAsync <MethodCallStatusException>()
                    .WithMessage($"{{\"Message\":\"Response 404 Endpoint not found: {request.EndpointUrl}\",\"Details\":{{}}}}")
                    .ConfigureAwait(false);
                }
                else
                {
                    await FluentActions
                    .Invoking(async() => await _standaloneJobOrchestrator
                              .AddOrUpdateEndpointsAsync(new List <PublishedNodesEntryModel> {
                        request
                    })
                              .ConfigureAwait(false))
                    .Should()
                    .NotThrowAsync()
                    .ConfigureAwait(false);

                    previousDataSets.Add(request);
                }
            }

            var configuredEndpoints = await _standaloneJobOrchestrator
                                      .GetConfiguredEndpointsAsync()
                                      .ConfigureAwait(false);

            Assert.Equal(0, configuredEndpoints.Count);
        }
        public async Task UnpublishNodesOnExistingConfiguration(string publishedNodesFile)
        {
            var standaloneCliModelProviderMock = new Mock <IStandaloneCliModelProvider>();
            var agentConfigProviderMock        = new Mock <IAgentConfigProvider>();
            var engineConfigMock         = new Mock <IEngineConfiguration>();
            var clientConfignMock        = new Mock <IClientServicesConfig>();
            var newtonSoftJsonSerializer = new NewtonSoftJsonSerializer();
            var jobSerializer            = new PublisherJobSerializer(newtonSoftJsonSerializer);
            var logger = TraceLogger.Create();
            var publishedNodesJobConverter = new PublishedNodesJobConverter(logger, newtonSoftJsonSerializer,
                                                                            engineConfigMock.Object, clientConfignMock.Object);

            Utils.CopyContent(publishedNodesFile, _tempFile);
            var standaloneCliModel = new StandaloneCliModel {
                PublishedNodesFile       = _tempFile,
                PublishedNodesSchemaFile = "Storage/publishednodesschema.json"
            };

            standaloneCliModelProviderMock.Setup(p => p.StandaloneCliModel).Returns(standaloneCliModel);
            agentConfigProviderMock.Setup(p => p.Config).Returns(new AgentConfigModel());

            var publishedNodesProvider = new PublishedNodesProvider(standaloneCliModelProviderMock.Object, logger);

            var orchestrator = new StandaloneJobOrchestrator(
                publishedNodesJobConverter,
                standaloneCliModelProviderMock.Object,
                agentConfigProviderMock.Object,
                jobSerializer,
                logger,
                publishedNodesProvider,
                newtonSoftJsonSerializer
                );

            string payload = Utils.GetFileContent(publishedNodesFile);
            var    unpublishNodesRequest = newtonSoftJsonSerializer.Deserialize <List <PublishedNodesEntryModel> >(payload);

            foreach (var request in unpublishNodesRequest)
            {
                await FluentActions
                .Invoking(async() => await orchestrator.UnpublishNodesAsync(request).ConfigureAwait(false))
                .Should()
                .NotThrowAsync()
                .ConfigureAwait(false);
            }

            var tasks = new List <Task <JobProcessingInstructionModel> >();

            for (var i = 0; i < 10; i++)
            {
                tasks.Add(orchestrator.GetAvailableJobAsync(i.ToString(), new JobRequestModel()));
            }

            await Task.WhenAll(tasks).ConfigureAwait(false);

            tasks.Count(t => t.Result != null)
            .Should()
            .Be(0);
        }
Esempio n. 3
0
        public void UseSecurityDeserializationTest()
        {
            var newtonSoftJsonSerializer = new NewtonSoftJsonSerializer();

            var modelJson = @"
{
    ""EndpointUrl"": ""opc.tcp://*****:*****@"
{
    ""EndpointUrl"": ""opc.tcp://*****:*****@"
{
    ""EndpointUrl"": ""opc.tcp://localhost:50002"",
    ""UseSecurity"": true,
    ""OpcNodes"": [
        { ""Identifier"": ""ns=0;i=2261"" }
    ]
}
";

            model = newtonSoftJsonSerializer.Deserialize <PublishedNodesEntryModel>(modelJson);
            Assert.True(model.UseSecurity);
        }
Esempio n. 4
0
        public void OpcAuthenticationModeDeserializationTest()
        {
            var newtonSoftJsonSerializer = new NewtonSoftJsonSerializer();

            var modelJson = @"
{
    ""EndpointUrl"": ""opc.tcp://*****:*****@"
{
    ""EndpointUrl"": ""opc.tcp://*****:*****@"
{
    ""EndpointUrl"": ""opc.tcp://localhost:50002"",
    ""OpcAuthenticationMode"": ""usernamePassword"",
    ""OpcNodes"": [
        { ""Identifier"": ""ns=0;i=2261"" }
    ]
}
";

            model = newtonSoftJsonSerializer.Deserialize <PublishedNodesEntryModel>(modelJson);
            Assert.Equal(OpcAuthenticationMode.UsernamePassword, model.OpcAuthenticationMode);
        }
Esempio n. 5
0
        /// <summary>
        /// publish nodes from publishedNodesFile
        /// </summary>
        private async Task <PublisherMethodsController> publishNodeAsync(string publishedNodesFile)
        {
            var standaloneCliModelProviderMock = new Mock <IStandaloneCliModelProvider>();
            var agentConfigProviderMock        = new Mock <IAgentConfigProvider>();
            var identityMock             = new Mock <IIdentity>();
            var newtonSoftJsonSerializer = new NewtonSoftJsonSerializer();
            var jobSerializer            = new PublisherJobSerializer(newtonSoftJsonSerializer);
            var logger            = TraceLogger.Create();
            var engineConfigMock  = new Mock <IEngineConfiguration>();
            var clientConfignMock = new Mock <IClientServicesConfig>();

            var publishedNodesJobConverter = new PublishedNodesJobConverter(logger, newtonSoftJsonSerializer,
                                                                            engineConfigMock.Object, clientConfignMock.Object);

            Utils.CopyContent("Engine/empty_pn.json", _tempFile);
            var standaloneCli = new StandaloneCliModel {
                PublishedNodesFile       = _tempFile,
                PublishedNodesSchemaFile = "Storage/publishednodesschema.json"
            };

            standaloneCliModelProviderMock.Setup(p => p.StandaloneCliModel).Returns(standaloneCli);
            agentConfigProviderMock.Setup(p => p.Config).Returns(new AgentConfigModel());
            var publishedNodesProvider = new PublishedNodesProvider(standaloneCliModelProviderMock.Object, logger);

            var orchestrator = new StandaloneJobOrchestrator(
                publishedNodesJobConverter,
                standaloneCliModelProviderMock.Object,
                agentConfigProviderMock.Object,
                jobSerializer,
                logger,
                publishedNodesProvider,
                newtonSoftJsonSerializer
                );

            var methodsController = new PublisherMethodsController(orchestrator);

            using var publishPayloads = new StreamReader(publishedNodesFile);
            var publishNodesRequest = newtonSoftJsonSerializer.Deserialize <List <PublishNodesEndpointApiModel> >(
                await publishPayloads.ReadToEndAsync().ConfigureAwait(false));

            foreach (var request in publishNodesRequest)
            {
                await FluentActions
                .Invoking(async() => await methodsController.PublishNodesAsync(request).ConfigureAwait(false))
                .Should()
                .NotThrowAsync()
                .ConfigureAwait(false);
            }
            return(methodsController);
        }
Esempio n. 6
0
        public void SetUp()
        {
            var locator         = new InMemoryServiceLocator();
            var objectConverter = new ObjectConverter(locator, new ConverterLibrary(new[] { new StatelessComplexTypeConverter() }));

            locator.Add <IObjectConverter>(objectConverter);

            var converter = new ComplexTypeConverter(objectConverter);

            theInput      = "{\"Name\":\"Test\",\"Child\":\"x:123\"}";
            theSerializer = new NewtonSoftJsonSerializer(new JsonSerializerSettings(), new[] { converter });

            theObject = theSerializer.Deserialize <ParentType>(theInput);
        }
Esempio n. 7
0
        public void round_trip_with_camel_casing()
        {
            var settings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            var serializer = new NewtonSoftJsonSerializer(settings, new JsonConverter[0]);
            var json       = serializer.Serialize(new Target {
                Name = "Jeremy"
            });

            json.ShouldBe("{\"name\":\"Jeremy\"}");

            var target2 = serializer.Deserialize <Target>(json);

            target2.Name.ShouldBe("Jeremy");
        }
        public async Task UnpublishNodesOnNonExistingConfiguration(string existingConfig, string newConfig)
        {
            var standaloneCliModelProviderMock = new Mock <IStandaloneCliModelProvider>();
            var agentConfigProviderMock        = new Mock <IAgentConfigProvider>();
            var engineConfigMock         = new Mock <IEngineConfiguration>();
            var clientConfignMock        = new Mock <IClientServicesConfig>();
            var newtonSoftJsonSerializer = new NewtonSoftJsonSerializer();
            var jobSerializer            = new PublisherJobSerializer(newtonSoftJsonSerializer);
            var logger = TraceLogger.Create();
            var publishedNodesJobConverter = new PublishedNodesJobConverter(logger, newtonSoftJsonSerializer,
                                                                            engineConfigMock.Object, clientConfignMock.Object);

            Utils.CopyContent(existingConfig, _tempFile);
            var standaloneCliModel = new StandaloneCliModel {
                PublishedNodesFile       = _tempFile,
                PublishedNodesSchemaFile = "Storage/publishednodesschema.json"
            };

            standaloneCliModelProviderMock.Setup(p => p.StandaloneCliModel).Returns(standaloneCliModel);
            agentConfigProviderMock.Setup(p => p.Config).Returns(new AgentConfigModel());

            var publishedNodesProvider = new PublishedNodesProvider(standaloneCliModelProviderMock.Object, logger);

            var orchestrator = new StandaloneJobOrchestrator(
                publishedNodesJobConverter,
                standaloneCliModelProviderMock.Object,
                agentConfigProviderMock.Object,
                jobSerializer,
                logger,
                publishedNodesProvider,
                newtonSoftJsonSerializer
                );

            string payload = Utils.GetFileContent(newConfig);
            var    unpublishNodesRequest = newtonSoftJsonSerializer.Deserialize <List <PublishedNodesEntryModel> >(payload);

            foreach (var request in unpublishNodesRequest)
            {
                await FluentActions
                .Invoking(async() => await orchestrator.UnpublishNodesAsync(request).ConfigureAwait(false))
                .Should()
                .ThrowAsync <MethodCallStatusException>()
                .WithMessage($"{{\"Message\":\"Response 404 Endpoint not found: {request.EndpointUrl}\",\"Details\":{{}}}}")
                .ConfigureAwait(false);
            }

            var tasks = new List <Task <JobProcessingInstructionModel> >();

            for (var i = 0; i < 10; i++)
            {
                tasks.Add(orchestrator.GetAvailableJobAsync(i.ToString(), new JobRequestModel()));
            }

            await Task.WhenAll(tasks).ConfigureAwait(false);

            tasks.Count(t => t.Result != null)
            .Should()
            .Be(2);

            var distinctConfigurations = tasks
                                         .Where(t => t.Result != null)
                                         .Select(t => t.Result.Job.JobConfiguration)
                                         .Distinct();

            distinctConfigurations.Count()
            .Should()
            .Be(2);
        }
Esempio n. 9
0
        public async Task DmApiGetConfiguredEndpointsTest(string publishedNodesFile)
        {
            var standaloneCliModelProviderMock = new Mock <IStandaloneCliModelProvider>();
            var agentConfigProviderMock        = new Mock <IAgentConfigProvider>();
            var identityMock             = new Mock <IIdentity>();
            var newtonSoftJsonSerializer = new NewtonSoftJsonSerializer();
            var jobSerializer            = new PublisherJobSerializer(newtonSoftJsonSerializer);
            var logger            = TraceLogger.Create();
            var engineConfigMock  = new Mock <IEngineConfiguration>();
            var clientConfignMock = new Mock <IClientServicesConfig>();

            var publishedNodesJobConverter = new PublishedNodesJobConverter(logger, newtonSoftJsonSerializer,
                                                                            engineConfigMock.Object, clientConfignMock.Object);

            Utils.CopyContent("Engine/empty_pn.json", _tempFile);
            var standaloneCli = new StandaloneCliModel {
                PublishedNodesFile       = _tempFile,
                PublishedNodesSchemaFile = "Storage/publishednodesschema.json"
            };

            standaloneCliModelProviderMock.Setup(p => p.StandaloneCliModel).Returns(standaloneCli);
            agentConfigProviderMock.Setup(p => p.Config).Returns(new AgentConfigModel());

            var publishedNodesProvider = new PublishedNodesProvider(standaloneCliModelProviderMock.Object, logger);

            var orchestrator = new StandaloneJobOrchestrator(
                publishedNodesJobConverter,
                standaloneCliModelProviderMock.Object,
                agentConfigProviderMock.Object,
                jobSerializer,
                logger,
                publishedNodesProvider,
                newtonSoftJsonSerializer
                );

            var methodsController = new PublisherMethodsController(orchestrator);

            using var publishPayloads = new StreamReader(publishedNodesFile);
            var publishNodesRequests = newtonSoftJsonSerializer.Deserialize <List <PublishNodesEndpointApiModel> >
                                           (await publishPayloads.ReadToEndAsync().ConfigureAwait(false));

            // Check that GetConfiguredEndpointsAsync returns empty list
            var endpoints = await FluentActions
                            .Invoking(async() => await methodsController
                                      .GetConfiguredEndpointsAsync().ConfigureAwait(false))
                            .Should()
                            .NotThrowAsync()
                            .ConfigureAwait(false);

            endpoints.Subject.Endpoints.Count.Should().Be(0);

            // Publish nodes
            foreach (var request in publishNodesRequests)
            {
                await FluentActions
                .Invoking(async() => await methodsController
                          .PublishNodesAsync(request).ConfigureAwait(false))
                .Should()
                .NotThrowAsync()
                .ConfigureAwait(false);
            }

            // Check configured endpoints count
            endpoints = await FluentActions
                        .Invoking(async() => await methodsController
                                  .GetConfiguredEndpointsAsync().ConfigureAwait(false))
                        .Should()
                        .NotThrowAsync()
                        .ConfigureAwait(false);

            endpoints.Subject.Endpoints.Count.Should().Be(5);
            endpoints.Subject.Endpoints[0].Tag.Should().Be("Tag_Leaf0_10000_3085991c-b85c-4311-9bfb-a916da952234");
            endpoints.Subject.Endpoints[1].Tag.Should().Be("Tag_Leaf1_10000_2e4fc28f-ffa2-4532-9f22-378d47bbee5d");
            endpoints.Subject.Endpoints[2].Tag.Should().Be("Tag_Leaf2_10000_3085991c-b85c-4311-9bfb-a916da952234");
            endpoints.Subject.Endpoints[3].Tag.Should().Be("Tag_Leaf3_10000_2e4fc28f-ffa2-4532-9f22-378d47bbee5d");
            endpoints.Subject.Endpoints[4].Tag.Should().BeNull();

            var endpointsHash = endpoints.Subject.Endpoints.Select(e => e.GetHashCode()).ToList();

            Assert.True(endpointsHash.Distinct().Count() == endpointsHash.Count());
        }
Esempio n. 10
0
        public async Task DmApiPublishUnpublishNodesTest(string publishedNodesFile)
        {
            var standaloneCliModelProviderMock = new Mock <IStandaloneCliModelProvider>();
            var agentConfigProviderMock        = new Mock <IAgentConfigProvider>();
            var identityMock             = new Mock <IIdentity>();
            var newtonSoftJsonSerializer = new NewtonSoftJsonSerializer();
            var jobSerializer            = new PublisherJobSerializer(newtonSoftJsonSerializer);
            var logger            = TraceLogger.Create();
            var engineConfigMock  = new Mock <IEngineConfiguration>();
            var clientConfignMock = new Mock <IClientServicesConfig>();

            var publishedNodesJobConverter = new PublishedNodesJobConverter(logger, newtonSoftJsonSerializer,
                                                                            engineConfigMock.Object, clientConfignMock.Object);

            Utils.CopyContent("Engine/empty_pn.json", _tempFile);
            var standaloneCli = new StandaloneCliModel {
                PublishedNodesFile       = _tempFile,
                PublishedNodesSchemaFile = "Storage/publishednodesschema.json"
            };

            standaloneCliModelProviderMock.Setup(p => p.StandaloneCliModel).Returns(standaloneCli);
            agentConfigProviderMock.Setup(p => p.Config).Returns(new AgentConfigModel());

            var publishedNodesProvider = new PublishedNodesProvider(standaloneCliModelProviderMock.Object, logger);

            var orchestrator = new StandaloneJobOrchestrator(
                publishedNodesJobConverter,
                standaloneCliModelProviderMock.Object,
                agentConfigProviderMock.Object,
                jobSerializer,
                logger,
                publishedNodesProvider,
                newtonSoftJsonSerializer
                );

            var methodsController = new PublisherMethodsController(orchestrator);

            using var publishPayloads = new StreamReader(publishedNodesFile);
            var publishNodesRequest = newtonSoftJsonSerializer.Deserialize <List <PublishNodesEndpointApiModel> >(
                await publishPayloads.ReadToEndAsync().ConfigureAwait(false));

            foreach (var request in publishNodesRequest)
            {
                var initialNode = request.OpcNodes.First();
                for (int i = 0; i < 10000; i++)
                {
                    request.OpcNodes.Add(new PublishedNodeApiModel {
                        Id                        = initialNode.Id + i.ToString(),
                        DataSetFieldId            = initialNode.DataSetFieldId,
                        DisplayName               = initialNode.DisplayName,
                        ExpandedNodeId            = initialNode.ExpandedNodeId,
                        HeartbeatIntervalTimespan = initialNode.HeartbeatIntervalTimespan,
                        OpcPublishingInterval     = initialNode.OpcPublishingInterval,
                        OpcSamplingInterval       = initialNode.OpcSamplingInterval,
                        QueueSize                 = initialNode.QueueSize,
                        // ToDo: Implement mechanism for SkipFirst.
                        SkipFirst = initialNode.SkipFirst,
                    });
                }

                await FluentActions
                .Invoking(async() => await methodsController.PublishNodesAsync(request).ConfigureAwait(false))
                .Should()
                .NotThrowAsync()
                .ConfigureAwait(false);
            }

            var tasks = new List <Task <JobProcessingInstructionModel> >();

            for (var i = 0; i < 10; i++)
            {
                tasks.Add(orchestrator.GetAvailableJobAsync(i.ToString(), new JobRequestModel()));
            }

            tasks.Where(t => t.Result != null)
            .Select(t => t.Result.Job.JobConfiguration)
            .Distinct().Count()
            .Should()
            .Be(2);

            foreach (var request in publishNodesRequest)
            {
                await FluentActions
                .Invoking(async() => await methodsController
                          .UnpublishNodesAsync(request).ConfigureAwait(false))
                .Should()
                .NotThrowAsync()
                .ConfigureAwait(false);
            }

            tasks = new List <Task <JobProcessingInstructionModel> >();
            for (var i = 0; i < 10; i++)
            {
                tasks.Add(orchestrator.GetAvailableJobAsync(i.ToString(), new JobRequestModel()));
            }

            tasks.Where(t => t.Result != null).Count()
            .Should()
            .Be(0);
        }
Esempio n. 11
0
        public async Task DmApiPublishNodesToJobTest(string publishedNodesFile)
        {
            var standaloneCliModelProviderMock = new Mock <IStandaloneCliModelProvider>();
            var agentConfigProviderMock        = new Mock <IAgentConfigProvider>();
            var identityMock             = new Mock <IIdentity>();
            var newtonSoftJsonSerializer = new NewtonSoftJsonSerializer();
            var jobSerializer            = new PublisherJobSerializer(newtonSoftJsonSerializer);
            var logger            = TraceLogger.Create();
            var engineConfigMock  = new Mock <IEngineConfiguration>();
            var clientConfignMock = new Mock <IClientServicesConfig>();

            var publishedNodesJobConverter = new PublishedNodesJobConverter(logger, newtonSoftJsonSerializer,
                                                                            engineConfigMock.Object, clientConfignMock.Object);

            Utils.CopyContent("Engine/empty_pn.json", _tempFile);
            var standaloneCli = new StandaloneCliModel {
                PublishedNodesFile       = _tempFile,
                PublishedNodesSchemaFile = "Storage/publishednodesschema.json"
            };

            standaloneCliModelProviderMock.Setup(p => p.StandaloneCliModel).Returns(standaloneCli);
            agentConfigProviderMock.Setup(p => p.Config).Returns(new AgentConfigModel());

            var publishedNodesProvider = new PublishedNodesProvider(standaloneCliModelProviderMock.Object, logger);

            var orchestrator = new StandaloneJobOrchestrator(
                publishedNodesJobConverter,
                standaloneCliModelProviderMock.Object,
                agentConfigProviderMock.Object,
                jobSerializer,
                logger,
                publishedNodesProvider,
                newtonSoftJsonSerializer
                );

            var methodsController = new PublisherMethodsController(orchestrator);

            using var publishPayloads = new StreamReader(publishedNodesFile);
            var publishNodesRequests = newtonSoftJsonSerializer.Deserialize <List <PublishNodesEndpointApiModel> >
                                           (await publishPayloads.ReadToEndAsync().ConfigureAwait(false));

            foreach (var request in publishNodesRequests)
            {
                await FluentActions
                .Invoking(async() => await methodsController
                          .PublishNodesAsync(request).ConfigureAwait(false))
                .Should()
                .NotThrowAsync()
                .ConfigureAwait(false);
            }

            var tasks = new List <Task <JobProcessingInstructionModel> >();

            for (var i = 0; i < 10; i++)
            {
                tasks.Add(orchestrator.GetAvailableJobAsync(i.ToString(), new JobRequestModel()));
            }

            var job = tasks.Where(t => t.Result != null)
                      .Select(t => t.Result.Job)
                      .Distinct();

            job.Count()
            .Should()
            .Be(2);

            var jobModel = jobSerializer.DeserializeJobConfiguration(
                job.First().JobConfiguration, job.First().JobConfigurationType) as WriterGroupJobModel;

            jobModel.WriterGroup.DataSetWriters.Count.Should().Be(4);
            foreach (var datasetWriter in jobModel.WriterGroup.DataSetWriters)
            {
                datasetWriter.DataSet.DataSetSource.Connection.Endpoint.Url
                .Should()
                .Be(publishNodesRequests.First().EndpointUrl);
                datasetWriter.DataSet.DataSetSource.Connection.Endpoint.SecurityMode
                .Should()
                .Be(publishNodesRequests.First().UseSecurity ? SecurityMode.Best : SecurityMode.None);

                datasetWriter.DataSet.DataSetSource.Connection.User.
                IsSameAs(new CredentialModel {
                    Type = publishNodesRequests.First().OpcAuthenticationMode == AuthenticationMode.Anonymous ?
                           CredentialType.None :
                           CredentialType.UserName,
                    Value = newtonSoftJsonSerializer.FromObject(
                        new {
                        user     = publishNodesRequests.First().UserName,
                        password = publishNodesRequests.First().Password,
                    })
                })
                .Should()
                .BeTrue();
            }
        }
Esempio n. 12
0
 /// <summary>
 /// Expand short Google url to original url (This method use google api)
 /// </summary>
 /// <param name="shortUrl">Short Google url</param>
 /// <returns>An orginal url</returns>
 public static string ExpandShortGoogleUrl(string shortUrl)
 {
     try
     {
         // make request
         string provider = "https://www.googleapis.com/urlshortener/v1/url?shortUrl=" + shortUrl;
         var request = WebRequest.Create(provider);
         var res = request.GetResponse();
         string responeData;
         GoogleUrlResponse result;
         // read respone data and deserialize
         using (var reader = new StreamReader(res.GetResponseStream()))
         {
             responeData = reader.ReadToEnd();
             //var deserializer = new JavaScriptSerializer();
             //result = deserializer.Deserialize<GoogleUrlResponse>(responeData);
             ISerializer serializer = new NewtonSoftJsonSerializer();
             result = serializer.Deserialize<GoogleUrlResponse>(responeData);
         }
         if (result != null)
         {
             return result.LongUrl;
         }
         return shortUrl;
     }
     catch (Exception ex)
     {
         return ex.Message;
     }
 }
Esempio n. 13
0
 private static string MakeGoogleShortenUrl(string url)
 {
     // http://gempixel.com/demo/simplephp
     // http://www.bipinjoshi.net/articles/09bf16f8-ad91-4638-8fce-f2e286f6fe1d.aspx
     // http://www.jarloo.com/google-url-shortening/
     // http://www.aspdotnet-suresh.com/2013/02/create-google-short-urls-in-javascript.html
     // http://www.fluxbytes.com/csharp/shortening-a-url-using-bit-bitly-api-in-c/
     try
     {
         // check url is existing ?
         if (UrlIsExists(url))
         {
             // Make request
             //string encondingUrl = HttpUtility.UrlEncode(url);
             var request = WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url");
             request.Method = "POST";
             request.ContentType = "application/json";
             string postData = "{\"longUrl\":\"" + url + "\"}";
             using (var writer = new StreamWriter(request.GetRequestStream()))
             {
                 writer.Write(postData);
             }
             // Get respone
             var respone = request.GetResponse();
             GoogleUrlResponse result;
             using (var reader = new StreamReader(respone.GetResponseStream()))
             {
                 // read data is returned from server and deserialize it.
                 string responeData = reader.ReadToEnd();
                 ISerializer serializer = new NewtonSoftJsonSerializer();
                 result = serializer.Deserialize<GoogleUrlResponse>(responeData);
             }
             if (result != null)
             {
                 return result.Id;
             }
         }
         return url;
     }
     catch (Exception ex)
     {
         return ex.Message;
     }
 }