System net webexception the remote server returned an error 404 not found

Documentation for IIS. Contribute to MicrosoftDocs/iis-docs development by creating an account on GitHub.
title author description ms.date ms.assetid msc.legacyurl msc.type

Troubleshooting Common Problems with Web Deploy

ehamai

This walkthrough shows how to diagnose and fix common problems with Web Deploy, including common errors seen while publishing from Visual Studio 2010. Loggin…

04/20/2012

582eff55-c99e-4eeb-8642-d8334a94c3c2

/learn/publish/troubleshooting-web-deploy/troubleshooting-common-problems-with-web-deploy

authoredcontent

Troubleshooting Common Problems with Web Deploy

by Elliott Hamai

This walkthrough shows how to diagnose and fix common problems with Web Deploy, including common errors seen while publishing from Visual Studio 2010.

Logging

When you run into issues with Web Deploy, there are several logging options depending on where the problem occurred. By default, Web Deploy logs to the Event Log under Applications > Microsoft Web Deploy. This is great place to start looking for errors on the destination server.

In the unlikely case that you cannot diagnose the problem using the Event Log, here are some other options:

  1. To diagnose installation problems, Web Deploy MSI logs are placed under %programfiles%IISMicrosoft Web Deploy v3.
  2. If Web Management Service or Remote Agent Service fail to start at all, look at the event Event Log > System for Service Control Manager errors.
  3. You can further configure tracing for Web Management Service

Error Codes

For certain common error cases, Web Deploy will show a message and an error code which may be useful in getting more information to troubleshoot an issue. For a full list of error codes, see https://go.microsoft.com/fwlink/?LinkId=221672 .

Note that the error message may be different depending on how Web Deploy is invoked. For example, Microsoft WebMatrix chooses to show custom error messages instead of error codes whereas the command line will always show error codes if they are logged.

Installation

1. Could not install Web Deploy on a valid OS

Symptoms The OS is correct, the version and bitness of Web Deploy are correct, but the installation does not succeed.
Root Cause Unknown
Fix/Workaround Look in the install log, located in %programfiles%IISMicrosoft Web Deploy V2.

2. Web Deploy does not function after upgrade

Symptoms Web Deploy does not work after a version upgrade.
Root Cause Web Deploy does not restart services after an upgrade.
Fix/Workaround If you are upgrading an existing installation of Web Deploy, make sure to restart the handler and agent services by running the following commands at an administrative command prompt: · net stop msdepsvc & net start msdepsvc · net stop wmsvc & net start wmsvc

3. Could not install Web Deploy 32-bit version on 64-bit hardware

Symptoms Screenshot of the Microsoft Web Deployment Tool Setup dialog box. The text says that the thirty two bit version of Microsoft Web Deployment Tool cannot be installed on a sixty four bit edition of Microsoft Windows.
Root Cause Trying to install 32-bit on 64-bit OS is a check inside the Web Deploy MSI that will fail because it doesn’t support WoW64 mode.
Fix/Workaround Install the same version that matches the architecture of your OS.

4. Could not install Web Deploy 64-bit version on 32-bit hardware

Symptoms Screenshot of the Windows Installer dialog box. The text says that This installation package is not supported by this processor type. Contact your product vendor.
Root Cause Trying to install 64-bit on 32-bit OS is a check inside Web Deploy’s MSI that will fail.
Fix/Workaround Install the same version that matches the architecture of your OS.

5. Could not register the URL namespace due to pre-existing namespace

Symptoms Unable to install Web Deploy
Root Cause The URL namespace that Web Deploy tries to create during installation is already registered
Fix/Workaround · Remove the conflicting registration · Change Web Deploy URL during installation msiexec /i wdeploy.msi /passive ADDLOCAL=ALL LISTENURL=http://+:8080/MSDEPLOY2/. For more information about URL customization, see Customizing and Securing the Remote Service.

Remote Agent Service

1. Could not initialize Microsoft.Web.Deployment.Dll during start-up

Symptoms Remote Agent Service fails to start
Root Cause msdepsvc.exe or other files are missing from %programfiles%IISMicrosoft Web Deploy v2.
Fix/Workaround Re-install the product

2. Remote Agent Service is not started

Symptoms Microsoft.Web.Deployment.DeploymentAgentUnavailableException: Remote agent (URL http://DestinationServer /msdeployagentservice) could not be contacted. Make sure the remote agent service is installed and started on the target computer. —> System.Net.WebException: The remote server returned an error: (404) Not Found.
Root Cause Remote Agent Service is not started
Fix/Workaround Start the service — ex: net start msdepsvc

3. Trying to connect to server where HTTP is not listening or allowed

Symptoms Microsoft.Web.Deployment.DeploymentAgentUnavailableException: Remote agent (URL http://DestinationServer/msdeployagentservice) could not be contacted. Make sure the remote agent service is installed and started on the target computer. —> System.Net.WebException: Unable to connect to the remote server —> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it DestinationServer:80
Root Cause HTTP not listening
Fix/Workaround Make sure HTTP traffic is allowed to the Remote Agent Service

4. Trying to connect to server with Method Not Allowed error

Symptoms Microsoft.Web.Deployment.DeploymentException: Could not complete the request to remote agent URL ‘http://DestinationServer/‘. —> System.Net.WebException: The remote server returned an error: (405) Method Not Allowed.
Root Cause Request was picked up by IIS itself instead of MS Deploy, because the path to msdepsvc.exe is missing.
Fix/Workaround Change the URL to include to /MSDeployAgentService

5. Trying to access Remote Agent Service as a non-administrator

Symptoms Microsoft.Web.Deployment.DeploymentException: Could not complete the request to remote agent URL ‘http://DestinationServer/msdeployAgentService‘. —> System.Net.WebException: The remote server returned an error: (401) Unauthorized.
Root Cause Remote Agent Service requires that the caller is a member of the Administrators group or from a domain account that has been added to the Administrators group. A local administrator which is not the built-in account will not work with the Remote Agent Service because of a bug in Web Deploy 2.0.
Fix/Workaround Provide administrative credentials

6. Remote Agent Service hangs during operation

Symptoms Service may stop responding for a long time, up to several hours
Root Cause Unknown
Fix/Workaround Stop the operation and attempt to repeat it

7. Client and server are not compatible (version mismatch)

Symptoms Timestamp=24638007621418 MsDepSvc.exe Error: 0 : An error occurred. The exception details are as follows: Microsoft.Web.Deployment.DeploymentClientServerException: The client and server are not compatible. The lowest version supported by the client is ‘7.1.538.0’. The highest version supported by the server is ‘7.1.537.0’.
Root Cause Some versions do not work together, so Web Deploy blocks them from working together. This is typically done to block pre-release versions from operating with released versions.
Fix/Workaround Match the versions

8. Remote Agent Service could not start listening on URL

Symptoms The Remote Agent Service could not start listening on the URL ‘{0}’. Make sure that the URL is not in use.
Root Cause Usually indicates a URL conflict.
Fix/Workaround Try reinstalling if you want the default URL or setting a custom URL as specified in the documentation. For more information about URL customization, see Customizing and Securing the Remote Service

Web Management Service

1. Web Management Service not started

Symptoms Web Management Service is not started.
Root Cause Unknown. The service should be started by default.
Fix/Workaround Start the Web Management Service service: Net Start WMSVC

2. Not Authorized: User not authorized by deployment handler rules

Symptoms Could not complete an operation with the specified provider <provider name> when connecting using the Web Management Service. This can occur if the server administrator has not authorized the user for this operation.
Root Cause A non-administrator user tried to perform a restricted action with a provider. This usually indicates that a matching delegation rule was not found. Either the username, provider, operation or provider path is wrong.
Fix/Workaround The workaround is to fix the delegation rule or create one. For more information about delegation rules, see Configure the Web Deployment Handler.

Case Study: Diagnosing Publishing Errors in Visual Studio 2010

This case study shows how to diagnose common errors encountered in Visual Studio 2010. The steps below walk through the series of errors you are likely to encounter when trying to publish from Visual Studio to a server that has not been correctly configured.

To collect the screenshots and errors below, we used a new ASP.NET MVC3 project. The destination server was a clean install of Windows Server 2008 R2 SP1 with IIS. No additional configuration was done.

The first error you are likely to encounter will look something like this in Visual Studio’s output window. To make it easier to read, the full text of the message is reproduced below the screenshot.

Screenshot of the Error List page. An error description is shown.

Web deployment task failed.(Could not connect to the destination computer («deployserver»). On the destination computer, make sure that Web Deploy is installed and that the required process («The Web Management Service») is started.)

This error indicates that you cannot connect to the server. Make sure the service URL is correct, firewall and network settings on this computer and on the server computer are configured properly, and the appropriate services have been started on the server.

Error details:

Could not connect to the destination computer («deployserver»). On the destination computer, make sure that Web Deploy is installed and that the required process («The Web Management Service») is started.

Unable to connect to the remote server

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 192.168.0.211:8172

Is the web management service installed? On the destination server, open IIS Manager and select the machine name node. In the Features view, scroll down to the Management section and look for these Icons:

Screenshot of the I I S Manager Permissions icon, the I I S Manager Users icon, and the Management Service icon.

If they are not there, you need to install the Web Management Service.

· Through the «Add Role Services» dialog in Server Manager.

· Through the Web Platform Installer from the Products tab. Select «Server» in the left column and choose «IIS: Management Service».

Note that after you install the Management Service, you will need to start it, as it is not started automatically.

Once the Web Management Service is installed, Visual studio may show this error:

Screenshot of an error page in Visual Studio. An error description is shown.

Web deployment task failed.(Could not connect to the destination computer («deployserver») using the specified process («The Web Management Service») because the server did not respond. Make sure that the process («The Web Management Service») is started on the destination computer.)

Could not connect to the destination computer («deployserver») using the specified process («The Web Management Service») because the server did not respond. Make sure that the process («The Web Management Service») is started on the destination computer.

The remote server returned an error: (403) Forbidden.

Is the Web Management Service configured to allow remote connections? Start IIS Manager and double-click the Management Service icon, and verify that «Enable Remote Connections» is checked. You must stop the service to make changes, so be sure to restart it.

Screenshot of the Management Service page. The Enable remote connections checkbox is checked.

Is Windows Firewall blocking the request? The Web Management Service creates an Inbound rule named «Web Management Service (HTTP Traffic-In)», and enables it. Verify this rule is enabled by going to Start->Administrative tools-> «Windows Firewall with Advanced Security». Click «Inbound Rules» and find the Web Management rule in the list. It should be enabled for all profiles.

If you are using a 3rd party firewall, make sure inbound TCP connections on port 8172 are allowed.

If Visual Studio is able to contact the Management Service, the error message changes:

Screenshot of the Visual Studio Error List page. A description of an error is shown.

Web deployment task failed.(Could not connect to the destination computer («deployserver»). On the destination computer, make sure that Web Deploy is installed and that the required process («The Web Management Service») is started.)

The requested resource does not exist, or the requested URL is incorrect.

Error details:

Could not connect to the destination computer («deployserver»). On the destination computer, make sure that Web Deploy is installed and that the required process («The Web Management Service») is started.

The remote server returned an error: (404) Not Found.

If you look in the Web Management Service log under %SystemDrive%InetpublogsWMSvc on the destination server, you will see an entry that looks like

[!code-consoleMain]

Is Web Deploy installed? You can verify web deploy is installed by going to the «Programs and Features» control panel and looking for «Microsoft Web Deploy 2.0» in the list of installed programs. If it is not there, you can install it via the Web Platform Installer by going to the «Products» tab. It is listed as «Web Deployment Tool 2.1».

Is the Web Deployment IIS7 Deployment Handler installed? If Web Deploy is installed and you still get this error, make sure the «IIS 7 Deployment Handler» feature in Web Deploy is installed. In «Add Remove Programs», find «Microsoft Web Deploy 2.0», right click and choose «Change». In the Wizard that comes up, click next on the first page, and then choose «Change» on the second page. Add «IIS 7 Deployment Handler» and everything under it.

SCreenshot of the Microsoft Web Deploy two dot zero Setup wizard. The Web Development Framework option is selected.

Click Next to complete the Wizard.

Once Web Deploy and the Web Management Service are correctly configured, you will need to set up Web Management Service delegation rules to allow users to update content. For permissions issues, there are several different errors you may see in Visual Studio. For example:

Screenshot of the Visual Studio Error List page. An error appears along with a description of the error.

Web deployment task failed.(Connected to the destination computer («deployserver») using the Web Management Service, but could not authorize. Make sure that you are using the correct user name and password, that the site you are connecting to exists, and that the credentials represent a user who has permissions to access the site.)

Make sure the site name, user name, and password are correct. If the issue is not resolved, please contact your local or server administrator.

Error details:

Connected to the destination computer («deployserver») using the Web Management Service, but could not authorize. Make sure that you are using the correct user name and password, that the site you are connecting to exists, and that the credentials represent a user who has permissions to access the site.

The remote server returned an error: (401) Unauthorized.

In the Web Management Service log, you will see:

[!code-consoleMain]

[!code-consoleMain]

The highlighted HTTP status in the Visual Studio output is an Access Denied error. The highlighted Win32 status in the error log maps to «Logon failure: unknown user name or bad password». This is a simple logon failure. If the user is authenticated, but does not have the rights needed to publish, the log entry will look like

[!code-consoleMain]

You will need to setup delegation for this user per the instructions at https://www.iis.net/learn/publish/using-web-deploy/configure-the-web-deployment-handler

If the account is able to log in, but has not been granted the rights needed to publish the content, you will see

Screenshot of the Visual Studio Error List page with an error description. The web deployment task has failed.

Web deployment task failed. (Unable to perform the operation («Create Directory») for the specified directory («bin»). This can occur if the server administrator has not authorized this operation for the user credentials you are using.

The WMSvc log will show HTTP 200 responses for these requests. The most likely cause is file system permissions. Web Deploy will also write events to the «Microsoft Web Deploy» service log. To view it, open the event viewer and go to «Applications and Services Logs» ->»Microsoft Web Deploy».

Screenshot of the Visual Studio Error List page. A description of an error says that the Web deployment task failed.

For this particular error, the event log contains extra detail (truncated for brevity):

[!code-consoleMain]

This message tells you where permissions need to be granted for this particular error. Another permissions error you may see in Visual Studio is

Screenshot of the Event Viewer navigation tree. The Microsoft Web Deploy option is selected.

Web deployment task failed.((5/12/2011 11:31:41 AM) An error occurred when the request was processed on the remote computer.)

(5/12/2011 11:31:41 AM) An error occurred when the request was processed on the remote computer.
The server experienced an issue processing the request. Contact the server administrator for more information.

This particular error does not give you much to go on, but the picture becomes much clearer if you look at the Web Deploy error log in Event Viewer.

[!code-consoleMain]

From this, we can see that User1 does not have rights to set security information. In this case, the user does not have Modify permissions on the content. Granting «Change Permissions» to the content resolves the problem.

If you cannot browse a .NET 4.0 application after it has been successfully published, it could be that .NET 4.0 has not been registered correctly with IIS. Other symptoms are that .NET 4.0 is installed, but there are no .NET 4.0 application pools or handler mappings in IIS. This happens when .NET 4.0 is installed before IIS was installed. To fix this problem, start an elevated command prompt and run this command:

[!code-consoleMain]

Sep 29, 2017 3:00:51 PM |
.NET Exceptions — System.ServiceModel.EndpointNotFoundException

A deep dive into the EndpointNotFoundException in .NET, including C# code illustrating how to create and connect to a simple WCF service.

Making our way through our detailed .NET Exception Handling series, today we’ll dive into the System.ServiceModel.EndpointNotFoundException. The EndpointNotFoundException is thrown when something goes awry while trying to connect to a Windows Communication Foundation (WCF) service-oriented application.

In this article we’ll examine the EndpointNotFoundException in more detail by looking at where it sits in the larger .NET exception hierarchy. We’ll also look at some functional C# code samples that illustrate how a basic service can be setup, and how invalid connections to such a WCF service might lead to EndpointNotFoundExceptions, so let’s get crackin’!

The Technical Rundown

All .NET exceptions are derived classes of the System.Exception base class, or derived from another inherited class therein. The full exception hierarchy of this error is:

  • System.Object
    • System.Exception
      • System.CommunicationException
        • EndpointNotFoundException

Full Code Sample

Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.

// Program.cs
using System;
using AIrbrake.ServiceModel.EndpointNotFoundException.MyServiceReference;
using Utility;

namespace AIrbrake.ServiceModel.EndpointNotFoundException
{
internal class Program
{
internal static void Main(string[] args)
{
Logging.LineSeparator("GetDataTest(0)");
GetDataTest(0);

Logging.LineSeparator("GetDataAsyncTest(0)");
GetDataAsyncTest(0);
}

internal static void GetDataTest(int value)
{
try
{
var client = new MyServiceClient();
client.Open();
var result = client.GetData(value);
Logging.Log(result);
}
catch (System.ServiceModel.EndpointNotFoundException exception)
{
// Output expected EndpointNotFoundExceptions.
Logging.Log(exception);
}
catch (Exception exception)
{
// Output unexpected Exceptions.
Logging.Log(exception, false);
}
}

internal static void GetDataAsyncTest(int value)
{
try
{
var client = new MyServiceClient();
client.Open();
var result = client.GetDataAsync(value);
Logging.Log(result);
}
catch (System.ServiceModel.EndpointNotFoundException exception)
{
// Output expected EndpointNotFoundExceptions.
Logging.Log(exception);
}
catch (Exception exception)
{
// Output unexpected Exceptions.
Logging.Log(exception, false);
}
}
}
}

<?xml version="1.0" encoding="utf-8" ?>
<!-- App.config -->
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7" />
</startup>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IMyService" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:62792/MyService.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IMyService" contract="MyServiceReference.IMyService"
name="BasicHttpBinding_IMyService" />
</client>
</system.serviceModel>
</configuration>
// IMyService.cs
using System.Runtime.Serialization;
using System.ServiceModel;

namespace MyService
{
[ServiceContract]
public interface IMyService
{
[OperationContract]
string GetData(int value);

[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
}

[DataContract]
public class CompositeType
{
[DataMember]
public bool BoolValue { get; set; } = true;

[DataMember]
public string StringValue { get; set; } = "Hello ";
}
}

// MyService.svc
using System;

namespace MyService
{
public class MyService : IMyService
{
public string GetData(int value)
{
return $"You entered: {value}";
}

public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException(nameof(composite));
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
}

// <Utility/>Logging.cs
using System;
using System.Diagnostics;
using System.Xml.Serialization;

namespace Utility
{
/// <summary>
/// Houses all logging methods for various debug outputs.
/// </summary>
public static class Logging
{
private const char SeparatorCharacterDefault = '-';
private const int SeparatorLengthDefault = 40;

/// <summary>
/// Determines type of output to be generated.
/// </summary>
public enum OutputType
{
/// <summary>
/// Default output.
/// </summary>
Default,
/// <summary>
/// Output includes timestamp prefix.
/// </summary>
Timestamp
}

/// <summary>
/// Outputs to <see cref="Debug.WriteLine(String)"/>.
/// </summary>
/// <param name="value">Value to be output to log.</param>
/// <param name="outputType">Output type.</param>
public static void Log(string value, OutputType outputType = OutputType.Default)
{
Output(value, outputType);
}

/// <summary>
/// Outputs to <see cref="Debug.WriteLine(String)"/>.
/// </summary>
/// <param name="value">Value to be output to log.</param>
/// <param name="arg0"></param>
public static void Log(string value, object arg0)
{
Debug.WriteLine(value, arg0);
}

/// <summary>
/// Outputs to <see cref="Debug.WriteLine(String)"/>.
/// </summary>
/// <param name="value">Value to be output to log.</param>
/// <param name="arg0"></param>
/// <param name="arg1"></param>
public static void Log(string value, object arg0, object arg1)
{
Debug.WriteLine(value, arg0, arg1);
}

/// <summary>
/// Outputs to <see cref="Debug.WriteLine(String)"/>.
/// </summary>
/// <param name="value">Value to be output to log.</param>
/// <param name="arg0"></param>
/// <param name="arg1"></param>
/// <param name="arg2"></param>
public static void Log(string value, object arg0, object arg1, object arg2)
{
Debug.WriteLine(value, arg0, arg1, arg2);
}

/// <summary>
/// When <see cref="Exception"/> parameter is passed, modifies the output to indicate
/// if <see cref="Exception"/> was expected, based on passed in `expected` parameter.
/// <para>Outputs the full <see cref="Exception"/> type and message.</para>
/// </summary>
/// <param name="exception">The <see cref="Exception"/> to output.</param>
/// <param name="expected">Boolean indicating if <see cref="Exception"/> was expected.</param>
/// <param name="outputType">Output type.</param>
public static void Log(Exception exception, bool expected = true, OutputType outputType = OutputType.Default)
{
var value = $"[{(expected ? "EXPECTED" : "UNEXPECTED")}] {exception}: {exception.Message}";

Output(value, outputType);
}

private static void Output(string value, OutputType outputType = OutputType.Default)
{
Debug.WriteLine(outputType == OutputType.Timestamp
? $"[{StopwatchProxy.Instance.Stopwatch.Elapsed}] {value}"
: value);
}

/// <summary>
/// Outputs to <see cref="Debug.WriteLine(Object)"/>.
///
/// ObjectDumper: http://stackoverflow.com/questions/852181/c-printing-all-properties-of-an-object&amp;lt;/cref
/// </summary>
/// <param name="value">Value to be output to log.</param>
/// <param name="outputType">Output type.</param>
public static void Log(object value, OutputType outputType = OutputType.Default)
{
if (value is IXmlSerializable)
{
Debug.WriteLine(value);
}
else
{
Debug.WriteLine(outputType == OutputType.Timestamp
? $"[{StopwatchProxy.Instance.Stopwatch.Elapsed}] {ObjectDumper.Dump(value)}"
: ObjectDumper.Dump(value));
}
}

/// <summary>
/// Outputs a dashed line separator to <see cref="Debug.WriteLine(String)"/>.
/// </summary>
/// <param name="length">Total separator length.</param>
/// <param name="char">Separator character.</param>
public static void LineSeparator(int length = SeparatorLengthDefault, char @char = SeparatorCharacterDefault)
{
Debug.WriteLine(new string(@char, length));
}

/// <summary>
/// Outputs a dashed line separator to <see cref="Debug.WriteLine(String)"/>,
/// with inserted text centered in the middle.
/// </summary>
/// <param name="insert">Inserted text to be centered.</param>
/// <param name="length">Total separator length.</param>
/// <param name="char">Separator character.</param>
public static void LineSeparator(string insert, int length = SeparatorLengthDefault, char @char = SeparatorCharacterDefault)
{
// Default output to insert.
var output = insert;

if (insert.Length < length)
{
// Update length based on insert length, less a space for margin.
length -= insert.Length + 2;
// Halve the length and floor left side.
var left = (int) Math.Floor((decimal) (length / 2));
var right = left;
// If odd number, add dropped remainder to right side.
if (length % 2 != 0) right += 1;

// Surround insert with separators.
output = $"{new string(@char, left)} {insert} {new string(@char, right)}";
}

// Output.
Debug.WriteLine(output);
}
}
}

When Should You Use It?

As mentioned in the introduction, the EndpointNotFoundException is tightly correlated with the Windows Communication Foundation (WCF), which is a .NET framework for easily creating service-oriented applications. Essentially, a WCF application provides at least one service endpoint (URI), which can be connected to and utilized via the service’s API. Plus, such API method calls can even be made asynchronously.

For the code sample today we’ve created a default WCF service application named MyService. It starts with the IMyService interface, which defines the basic service and data contracts the service will provide:

// IMyService.cs
using System.Runtime.Serialization;
using System.ServiceModel;

namespace MyService
{
[ServiceContract]
public interface IMyService
{
[OperationContract]
string GetData(int value);

[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
}

[DataContract]
public class CompositeType
{
[DataMember]
public bool BoolValue { get; set; } = true;

[DataMember]
public string StringValue { get; set; } = "Hello ";
}
}

From there, the MyService service implements the IMyService interface, providing the GetData(int value) method to «retrieve» some data. Alternatively, a data contract can also be used to retrieve data, but for our simple example we’ll stick with directly invoking GetData(int value):

// MyService.svc
using System;

namespace MyService
{
public class MyService : IMyService
{
public string GetData(int value)
{
return $"You entered: {value}";
}

public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException(nameof(composite));
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
}

Now, to access the MyServiceClient() class we need to specifically reference the MyService service in our Visual Studio project. This can be done by right-clicking the project name and selecting Add > Service Reference. On this screen, click Discover to automatically detect available services from other projects that are active/in the same solution. In our case, MyService.svc is listed, so we select that, then we change the Namespace to MyServiceReference and click OK.

Going through this process will automatically add a reference to the MyService service in our App.config file, as seen below:

<?xml version="1.0" encoding="utf-8" ?>
<!-- App.config -->
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7" />
</startup>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IMyService" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:62792/MyService.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IMyService" contract="MyServiceReference.IMyService"
name="BasicHttpBinding_IMyService" />
</client>
</system.serviceModel>
</configuration>

We’ve defined a few test methods to verify our connection to the MyService service, one which is a synchronous call (GetDataTest(int value)), and the other that is asynchronous (GetDataAsyncTest(int value)):

// Program.cs
using System;
using AIrbrake.ServiceModel.EndpointNotFoundException.MyServiceReference;
using Utility;

namespace AIrbrake.ServiceModel.EndpointNotFoundException
{
internal class Program
{
internal static void Main(string[] args)
{
Logging.LineSeparator("GetDataTest(0)");
GetDataTest(0);

Logging.LineSeparator("GetDataAsyncTest(0)");
GetDataAsyncTest(0);
}

internal static void GetDataTest(int value)
{
try
{
var client = new MyServiceClient();
client.Open();
var result = client.GetData(value);
Logging.Log(result);
}
catch (System.ServiceModel.EndpointNotFoundException exception)
{
// Output expected EndpointNotFoundExceptions.
Logging.Log(exception);
}
catch (Exception exception)
{
// Output unexpected Exceptions.
Logging.Log(exception, false);
}
}

internal static void GetDataAsyncTest(int value)
{
try
{
var client = new MyServiceClient();
client.Open();
var result = client.GetDataAsync(value);
Logging.Log(result);
}
catch (System.ServiceModel.EndpointNotFoundException exception)
{
// Output expected EndpointNotFoundExceptions.
Logging.Log(exception);
}
catch (Exception exception)
{
// Output unexpected Exceptions.
Logging.Log(exception, false);
}
}
}
}

Running the above test code attempts to connect to MyService and passes the int value of 0, before returning the results, which we’ve output to the console log:

------------ GetDataTest(0) ------------
You entered: 0

--------- GetDataAsyncTest(0) ----------
{System.Threading.Tasks.Task`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](HashCode:64554036)}
Result: "You entered: 0"
Id: 1
Exception: { }
null
Status: RanToCompletion
IsCanceled: False
IsCompleted: True
CreationOptions: None
AsyncState: { }
null
IsFaulted: False

Cool, everything seems to be working as expected. The async call returns a System.Thread.Tasks.Task object, which is why the result is much more complicated than the direct method call, but we can see that the Result property is the same for both method calls.

Now, that’s all well and good, but we can also manually add services to our App.config file. Let’s see what happens if we change the endpoint.address value in App.config to the name of an invalid service, such as InvalidService.svc:

<!-- App.config -->
<!-- ... -->
<client>
<endpoint address="http://localhost:62792/InvalidService.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IMyService" contract="MyServiceReference.IMyService"
name="BasicHttpBinding_IMyService" />
</client>
<!-- ... -->

Executing the same two test methods with this change to the endpoint.address property produces the following output:

------------ GetDataTest(0) ------------
[EXPECTED] System.ServiceModel.EndpointNotFoundException: There was no endpoint listening at http://localhost:62792/InvalidService.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details. ---> System.Net.WebException: The remote server returned an error: (404) Not Found.

--------- GetDataAsyncTest(0) ----------
Exception thrown: 'System.Reflection.TargetInvocationException' in mscorlib.dll
{System.Threading.Tasks.Task`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](HashCode:64554036)}
Result failed with:The remote server returned an error: (404) Not Found.
Id: 1
Exception: { }
{System.AggregateException(HashCode:61494432)}
InnerExceptions: ...
{System.ServiceModel.EndpointNotFoundException(HashCode:16578980)}
Message: "There was no endpoint listening at http://localhost:62792/InvalidService.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details."
Data: ...
InnerException: { }
TargetSite: { }
StackTrace: ...
HelpLink: null
Source: "System.ServiceModel.Internals"
HResult: -2146233087
Message: "One or more errors occurred."
Data: ...
InnerException: { }
{System.ServiceModel.EndpointNotFoundException(HashCode:16578980)}
(reference already dumped - line:7)
TargetSite: { }
null
StackTrace: null
HelpLink: null
Source: null
HResult: -2146233088
Status: Faulted
IsCanceled: False
IsCompleted: True
CreationOptions: None
AsyncState: { }
null
IsFaulted: True

Ah hah! Here we see our good friend the EndpointNotFoundException popup. As the error message indicates, the specific reason for a thrown EndpointNotFoundException could be any of a variety of reasons, but typically it’s is because the provided endpoint.address value in App.config is incorrect.

To get the most out of your own applications and to fully manage any and all .NET Exceptions, check out the Airbrake .NET Bug Handler, offering real-time alerts and instantaneous insight into what went wrong with your .NET code, along with built-in support for a variety of popular development integrations including: JIRA, GitHub, Bitbucket, and much more.

Ошибка: Контактная форма не найдена.

  • Register
  • Sign in
  • Help

Go To

  • Forums
  • Get Help with Power BI
  • Desktop
  • Service
  • Report Server
  • Power Query
  • Mobile Apps
  • Developer
  • DAX Commands and Tips
  • Custom Visuals Development Discussion
  • Health and Life Sciences


  • All forum topics


  • Previous Topic

  • Next Topic

tsozgen

  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Subscribe to RSS Feed
  • Permalink
  • Print
  • Report Inappropriate Content

‎02-20-2017

05:26 AM

Hi There;
I try to impement the power bi solution located there; https://powerbi.microsoft.com/en-us/documentation/powerbi-developer-walkthrough-push-data-register-a… My data resides at the power BI database (or cloud I am not sure about the location). Dataset is created successfully, however, there is a problem in addRowsToDataset function. What am I missing? Thanks in advance.

class Program
{
    private static string token = string.Empty;

    static void Main(string[] args)
    {
        string datasetId = string.Empty;

        try
        {
            token = getAuthenticationToken();

            datasetId = getDatasetId();

            createDataset();

            addRowsToDataset(datasetId, "CorporationProduct");

            Console.ReadKey();
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occured in main function. ");
            Console.WriteLine(ex.Message);
        }

    }

    private static string getAuthenticationToken()
    {
        string token = null;


        // TODO: Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.21.301221612
        // and add using Microsoft.IdentityModel.Clients.ActiveDirectory
        try
        {

            //The client id that Azure AD created when you registered your client app.
            string clientID = "myclientid";

            //RedirectUri you used when you register your app.
            //For a client app, a redirect uri gives Azure AD more details on the application that it will authenticate.
            // You can use this redirect uri for your client app
            string redirectUri = "https://login.live.com/oauth20_desktop.srf";

            //Resource Uri for Power BI API
            string resourceUri = "https://analysis.windows.net/powerbi/api";

            //OAuth2 authority Uri
            string authorityUri = "https://login.windows.net/common/oauth2/authorize";

            //Get access token:
            // To call a Power BI REST operation, create an instance of AuthenticationContext and call AcquireToken
            // AuthenticationContext is part of the Active Directory Authentication Library NuGet package
            // To install the Active Directory Authentication Library NuGet package in Visual Studio,
            //  run "Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory" from the nuget Package Manager Console.

            // AcquireToken will acquire an Azure access token
            // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
            AuthenticationContext authContext = new AuthenticationContext(authorityUri);

            token = authContext.AcquireToken(resourceUri, clientID, new Uri(redirectUri)).AccessToken;

            Console.WriteLine(token);
            Console.WriteLine("getAuthenticationToken operation is successfull.");
            Console.WriteLine("***");

        }
        catch (Exception ex)
        {
            Console.WriteLine("getAuthenticationToken encounters an error: ");
            Console.WriteLine(ex.Message);
        }


        return token;
    }

    /// <summary>
    /// Azure'de veri kümesi oluşturan yordam. 
    /// </summary>
    /// <remarks> System.Net ve using System.IO eklenmeli. </remarks>
    private static void createDataset()
    {

        HttpWebRequest request = null;
        string datasetJson = null;
        //Push data into a Power BI dashboard
        try
        {

            string powerBIDatasetsApiUrl = "https://api.powerbi.com/v1.0/myorg/datasets";
            //POST web request to create a dataset.
            //To create a Dataset in a group, use the Groups uri: https://api.PowerBI.com/v1.0/myorg/groups/{group_id}/datasets

            request = System.Net.WebRequest.Create(powerBIDatasetsApiUrl) as System.Net.HttpWebRequest;
            request.KeepAlive = true;
            request.Method = "POST";

            request.ContentType = "application/json";

            if(String.IsNullOrEmpty(token))
            {
                Console.WriteLine("token is null. ");
                return;
            }

            //Add token to the request header
            request.Headers.Add("Authorization", String.Format("Bearer {0}", token));

            //Create dataset JSON for POST request
            datasetJson = "{"name": "CorporationProduct", "tables": " +
                "[{"name": "Product", "columns": " +
                "[{ "name": "ProductID", "dataType": "Int64"}, " +
                "{ "name": "Name", "dataType": "string"}, " +
                "{ "name": "Category", "dataType": "string"}," +
                "{ "name": "IsCompete", "dataType": "bool"}," +
                "{ "name": "ManufacturedOn", "dataType": "DateTime"}" +
                "]}]}";

            request.ContentLength = datasetJson.Length;
            //POST web request
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(datasetJson);
            request.ContentLength = byteArray.Length;

            //Write JSON byte[] into a Stream
            using (Stream writer = request.GetRequestStream())
            {
                writer.Write(byteArray, 0, byteArray.Length);
                writer.Close();
                var response = (HttpWebResponse)request.GetResponse();

                Console.WriteLine(string.Format("Dataset {0}", response.StatusCode.ToString()));

                Console.WriteLine("createDataset operation is successfull.");
                Console.WriteLine("***");

            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("createDataset encounters an error: ");
            Console.WriteLine(ex.Message);
        }
    }

    private static string getDatasetId()
    {
        string datasetId = string.Empty;
        string powerBIDatasetsApiUrl = "https://api.powerbi.com/v1.0/myorg/datasets";

        try
        {

            //POST web request to create a dataset.
            //To create a Dataset in a group, use the Groups uri: https://api.PowerBI.com/v1.0/myorg/groups/{group_id}/datasets
            HttpWebRequest request = System.Net.WebRequest.Create(powerBIDatasetsApiUrl) as System.Net.HttpWebRequest;
            request.KeepAlive = true;
            request.Method = "GET";
            request.ContentLength = 0;
            request.ContentType = "application/json";

            if(String.IsNullOrEmpty(token))
            {
                Console.WriteLine("token is empty.");
                return null;
            }

            //Add token to the request header
            request.Headers.Add("Authorization", String.Format("Bearer {0}", token));


            //Get HttpWebResponse from GET request
            using (HttpWebResponse httpResponse = request.GetResponse() as System.Net.HttpWebResponse)
            {
                //Get StreamReader that holds the response stream
                using (StreamReader reader = new System.IO.StreamReader(httpResponse.GetResponseStream()))
                {
                    string responseContent = reader.ReadToEnd();

                    //TODO: Install NuGet Newtonsoft.Json package: Install-Package Newtonsoft.Json
                    //and add using Newtonsoft.Json
                    var results = JsonConvert.DeserializeObject<dynamic>(responseContent);

                    //Get the first id
                    datasetId = results["value"][0]["id"];

                    Console.WriteLine(String.Format("Dataset ID: {0}", datasetId));
                    Console.WriteLine("getDatasetId operation is successfull. ");
                    Console.WriteLine("***");

                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("getDatasetId encounters an error. ");
            Console.WriteLine(ex.Message);                
        }


        return datasetId;
    }

    private static void addRowsToDataset(string DatasetId, string TabloAdi)
    {
        string powerBIApiAddRowsUrl = null;
        HttpWebRequest request = null;

        try
        {

            powerBIApiAddRowsUrl = String.Format("https://api.powerbi.com/v1.0/myorg/datasets/{0}/tables/{1}/rows", DatasetId, TabloAdi);

            //POST web request to add rows.
            //To add rows to a dataset in a group, use the Groups uri: https://api.powerbi.com/v1.0/myorg/groups/{group_id}/datasets/{dataset_id}/tables/{table_name}/rows
            //Change request method to "POST"
            request = System.Net.WebRequest.Create(powerBIApiAddRowsUrl) as System.Net.HttpWebRequest;
            request.KeepAlive = true;
            request.Method = "POST";
            request.ContentLength = 0;
            request.ContentType = "application/json";

            if(String.IsNullOrEmpty(token))
            {
                Console.WriteLine("token is empty");
                return;
            }

            //Add token to the request header
            request.Headers.Add("Authorization", String.Format("Bearer {0}", token));

            //JSON content for product row
            string rowsJson = "{"rows":" +
                "[{"ProductID":1,"Name":"Adjustable Race","Category":"Components","IsCompete":true,"ManufacturedOn":"07/30/2014"}," +
                "{"ProductID":2,"Name":"LL Crankarm","Category":"Components","IsCompete":true,"ManufacturedOn":"07/30/2014"}," +
                "{"ProductID":3,"Name":"HL Mountain Frame - Silver","Category":"Bikes","IsCompete":true,"ManufacturedOn":"07/30/2014"}]}";

            //POST web request
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(rowsJson);
            request.ContentLength = byteArray.Length;

            //Write JSON byte[] into a Stream
            using (Stream writer = request.GetRequestStream())
            {
                writer.Write(byteArray, 0, byteArray.Length);

                //Here is the erroneous point: 
                var response = (HttpWebResponse)request.GetResponse();

            }

            Console.WriteLine("addRowsToDataset operation is successfull. ");
            Console.WriteLine("***");

        }
        catch (Exception ex)
        {
            Console.WriteLine("addRowsToDataset encounters an error.");
            Console.WriteLine(ex.Message);
            return;
        }


    }
}


Message 1 of 4

12,623 Views

1 ACCEPTED SOLUTION

Eric_Zhang

  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Subscribe to RSS Feed
  • Permalink
  • Print
  • Report Inappropriate Content

‎02-21-2017

05:31 AM

@tsozgen

The 404 error is because the passed table name is incorrect. CorporationProduct is the dataset name, while in your case, the table name should be product. 

addRowsToDataset(datasetId, "CorporationProduct");

You should also use a foreach loop in the getDataSetID function, otherwise when there’re already other datasets, you code would go to error as well.

using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;

class Program
{
    private static string token = string.Empty;

    static void Main(string[] args)
    {
        string datasetId = string.Empty;

        try
        {
            token = getAuthenticationToken();

            createDataset();

            datasetId = getDatasetId();

            

            addRowsToDataset(datasetId, "Product");

            Console.ReadKey();
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occured in main function. ");
            Console.WriteLine(ex.Message);
        }

    }

    private static string getAuthenticationToken()
    {
        string token = null;


        // TODO: Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.21.301221612
        // and add using Microsoft.IdentityModel.Clients.ActiveDirectory
        try
        {

            //The client id that Azure AD created when you registered your client app.
            string clientID = "myclientid";

            //RedirectUri you used when you register your app.
            //For a client app, a redirect uri gives Azure AD more details on the application that it will authenticate.
            // You can use this redirect uri for your client app
            string redirectUri = "https://login.live.com/oauth20_desktop.srf";

            //Resource Uri for Power BI API
            string resourceUri = "https://analysis.windows.net/powerbi/api";

            //OAuth2 authority Uri
            string authorityUri = "https://login.windows.net/common/oauth2/authorize";

            //Get access token:
            // To call a Power BI REST operation, create an instance of AuthenticationContext and call AcquireToken
            // AuthenticationContext is part of the Active Directory Authentication Library NuGet package
            // To install the Active Directory Authentication Library NuGet package in Visual Studio,
            //  run "Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory" from the nuget Package Manager Console.

            // AcquireToken will acquire an Azure access token
            // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
            AuthenticationContext authContext = new AuthenticationContext(authorityUri);

            token = authContext.AcquireToken(resourceUri, clientID, new Uri(redirectUri)).AccessToken;
            Console.WriteLine(token);
            Console.WriteLine("getAuthenticationToken operation is successfull.");
            Console.WriteLine("***");

        }
        catch (Exception ex)
        {
            Console.WriteLine("getAuthenticationToken encounters an error: ");
            Console.WriteLine(ex.Message);
        }


        return token;
    }

    /// <summary>
    /// Azure'de veri kümesi oluşturan yordam. 
    /// </summary>
    /// <remarks> System.Net ve using System.IO eklenmeli. </remarks>
    private static void createDataset()
    {

        HttpWebRequest request = null;
        string datasetJson = null;
        //Push data into a Power BI dashboard
        try
        {

            string powerBIDatasetsApiUrl = "https://api.powerbi.com/v1.0/myorg/datasets";
            //POST web request to create a dataset.
            //To create a Dataset in a group, use the Groups uri: https://api.PowerBI.com/v1.0/myorg/groups/{group_id}/datasets

            request = System.Net.WebRequest.Create(powerBIDatasetsApiUrl) as System.Net.HttpWebRequest;
            request.KeepAlive = true;
            request.Method = "POST";

            request.ContentType = "application/json";

            if (String.IsNullOrEmpty(token))
            {
                Console.WriteLine("token is null. ");
                return;
            }

            //Add token to the request header
            request.Headers.Add("Authorization", String.Format("Bearer {0}", token));

            //Create dataset JSON for POST request
            datasetJson = "{"name": "CorporationProduct", "tables": " +
                "[{"name": "Product", "columns": " +
                "[{ "name": "ProductID", "dataType": "Int64"}, " +
                "{ "name": "Name", "dataType": "string"}, " +
                "{ "name": "Category", "dataType": "string"}," +
                "{ "name": "IsCompete", "dataType": "bool"}," +
                "{ "name": "ManufacturedOn", "dataType": "DateTime"}" +
                "]}]}";

            request.ContentLength = datasetJson.Length;
            //POST web request
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(datasetJson);
            request.ContentLength = byteArray.Length;

            //Write JSON byte[] into a Stream
            using (Stream writer = request.GetRequestStream())
            {
                writer.Write(byteArray, 0, byteArray.Length);
                writer.Close();
                var response = (HttpWebResponse)request.GetResponse();

                Console.WriteLine(string.Format("Dataset {0}", response.StatusCode.ToString()));

                Console.WriteLine("createDataset operation is successfull.");
                Console.WriteLine("***");

            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("createDataset encounters an error: ");
            Console.WriteLine(ex.Message);
        }
    }

    private static string getDatasetId()
    {
        string datasetId = string.Empty;
        string powerBIDatasetsApiUrl = "https://api.powerbi.com/v1.0/myorg/datasets";

        try
        {

            //POST web request to create a dataset.
            //To create a Dataset in a group, use the Groups uri: https://api.PowerBI.com/v1.0/myorg/groups/{group_id}/datasets
            HttpWebRequest request = System.Net.WebRequest.Create(powerBIDatasetsApiUrl) as System.Net.HttpWebRequest;
            request.KeepAlive = true;
            request.Method = "GET";
            request.ContentLength = 0;
            request.ContentType = "application/json";

            if (String.IsNullOrEmpty(token))
            {
                Console.WriteLine("token is empty.");
                return null;
            }

            //Add token to the request header
            request.Headers.Add("Authorization", String.Format("Bearer {0}", token));


            //Get HttpWebResponse from GET request
            using (HttpWebResponse httpResponse = request.GetResponse() as System.Net.HttpWebResponse)
            {
                //Get StreamReader that holds the response stream
                using (StreamReader reader = new System.IO.StreamReader(httpResponse.GetResponseStream()))
                {
                    string responseContent = reader.ReadToEnd();

                    //TODO: Install NuGet Newtonsoft.Json package: Install-Package Newtonsoft.Json
                    //and add using Newtonsoft.Json
                    var results = JsonConvert.DeserializeObject<dynamic>(responseContent);

                    //Get the first id
                    //datasetId = results["value"][0]["id"];

                    foreach (var result in results["value"]) {
                        if (result["name"] == "CorporationProduct") {

                            datasetId = result["id"];
                        }


                    }


                    Console.WriteLine(String.Format("Dataset ID: {0}", datasetId));
                    Console.WriteLine("getDatasetId operation is successfull. ");
                    Console.WriteLine("***");

                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("getDatasetId encounters an error. ");
            Console.WriteLine(ex.Message);
        }


        return datasetId;
    }

    private static void addRowsToDataset(string DatasetId, string TabloAdi)
    {
        string powerBIApiAddRowsUrl = null;
        HttpWebRequest request = null;

        try
        {

            powerBIApiAddRowsUrl = String.Format("https://api.powerbi.com/v1.0/myorg/datasets/{0}/tables/{1}/rows", DatasetId, TabloAdi);

            //POST web request to add rows.
            //To add rows to a dataset in a group, use the Groups uri: https://api.powerbi.com/v1.0/myorg/groups/{group_id}/datasets/{dataset_id}/tables/{table_name}/rows
            //Change request method to "POST"
            request = System.Net.WebRequest.Create(powerBIApiAddRowsUrl) as System.Net.HttpWebRequest;
            request.KeepAlive = true;
            request.Method = "POST";
            request.ContentLength = 0;
            request.ContentType = "application/json";

            if (String.IsNullOrEmpty(token))
            {
                Console.WriteLine("token is empty");
                return;
            }

            //Add token to the request header
            request.Headers.Add("Authorization", String.Format("Bearer {0}", token));

            //JSON content for product row
            string rowsJson = "{"rows":" +
                "[{"ProductID":1,"Name":"Adjustable Race","Category":"Components","IsCompete":true,"ManufacturedOn":"07/30/2014"}," +
                "{"ProductID":2,"Name":"LL Crankarm","Category":"Components","IsCompete":true,"ManufacturedOn":"07/30/2014"}," +
                "{"ProductID":3,"Name":"HL Mountain Frame - Silver","Category":"Bikes","IsCompete":true,"ManufacturedOn":"07/30/2014"}]}";

            //POST web request
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(rowsJson);
            request.ContentLength = byteArray.Length;

            //Write JSON byte[] into a Stream
            using (Stream writer = request.GetRequestStream())
            {
                writer.Write(byteArray, 0, byteArray.Length);

                //Here is the erroneous point: 
                var response = (HttpWebResponse)request.GetResponse();

            }

            Console.WriteLine("addRowsToDataset operation is successfull. ");
            Console.WriteLine("***");

        }
        catch (Exception ex)
        {
            Console.WriteLine("addRowsToDataset encounters an error.");
            Console.WriteLine(ex.Message);
            return;
        }


    }
}


Message 3 of 4

17,198 Views


  • All forum topics


  • Previous Topic

  • Next Topic

3 REPLIES 3

tsozgen

  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Subscribe to RSS Feed
  • Permalink
  • Print
  • Report Inappropriate Content

‎02-20-2017

05:37 AM

Hi There;
I try to impement the power bi solution located there; https://powerbi.microsoft.com/en-us/documentation/powerbi-developer-walkthrough-push-data-register-a… My data resides at the azure cloud. Dataset is created successfully, however, there is a problem in addRowsToDataset function. What am I missing? Thanks in advance.

class Program
{
    private static string token = string.Empty;

    static void Main(string[] args)
    {
        string datasetId = string.Empty;

        try
        {
            token = getAuthenticationToken();

            datasetId = getDatasetId();

            createDataset();

            addRowsToDataset(datasetId, "CorporationProduct");

            Console.ReadKey();
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occured in main function. ");
            Console.WriteLine(ex.Message);
        }

    }

    private static string getAuthenticationToken()
    {
        string token = null;


        // TODO: Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.21.301221612
        // and add using Microsoft.IdentityModel.Clients.ActiveDirectory
        try
        {

            //The client id that Azure AD created when you registered your client app.
            string clientID = "myclientid";

            //RedirectUri you used when you register your app.
            //For a client app, a redirect uri gives Azure AD more details on the application that it will authenticate.
            // You can use this redirect uri for your client app
            string redirectUri = "https://login.live.com/oauth20_desktop.srf";

            //Resource Uri for Power BI API
            string resourceUri = "https://analysis.windows.net/powerbi/api";

            //OAuth2 authority Uri
            string authorityUri = "https://login.windows.net/common/oauth2/authorize";

            //Get access token:
            // To call a Power BI REST operation, create an instance of AuthenticationContext and call AcquireToken
            // AuthenticationContext is part of the Active Directory Authentication Library NuGet package
            // To install the Active Directory Authentication Library NuGet package in Visual Studio,
            //  run "Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory" from the nuget Package Manager Console.

            // AcquireToken will acquire an Azure access token
            // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
            AuthenticationContext authContext = new AuthenticationContext(authorityUri);

            token = authContext.AcquireToken(resourceUri, clientID, new Uri(redirectUri)).AccessToken;

            Console.WriteLine(token);
            Console.WriteLine("getAuthenticationToken operation is successfull.");
            Console.WriteLine("***");

        }
        catch (Exception ex)
        {
            Console.WriteLine("getAuthenticationToken encounters an error: ");
            Console.WriteLine(ex.Message);
        }


        return token;
    }

    /// <summary>
    /// Azure'de veri kümesi oluşturan yordam. 
    /// </summary>
    /// <remarks> System.Net ve using System.IO eklenmeli. </remarks>
    private static void createDataset()
    {

        HttpWebRequest request = null;
        string datasetJson = null;
        //Push data into a Power BI dashboard
        try
        {

            string powerBIDatasetsApiUrl = "https://api.powerbi.com/v1.0/myorg/datasets";
            //POST web request to create a dataset.
            //To create a Dataset in a group, use the Groups uri: https://api.PowerBI.com/v1.0/myorg/groups/{group_id}/datasets

            request = System.Net.WebRequest.Create(powerBIDatasetsApiUrl) as System.Net.HttpWebRequest;
            request.KeepAlive = true;
            request.Method = "POST";

            request.ContentType = "application/json";

            if(String.IsNullOrEmpty(token))
            {
                Console.WriteLine("token is null. ");
                return;
            }

            //Add token to the request header
            request.Headers.Add("Authorization", String.Format("Bearer {0}", token));

            //Create dataset JSON for POST request
            datasetJson = "{"name": "CorporationProduct", "tables": " +
                "[{"name": "Product", "columns": " +
                "[{ "name": "ProductID", "dataType": "Int64"}, " +
                "{ "name": "Name", "dataType": "string"}, " +
                "{ "name": "Category", "dataType": "string"}," +
                "{ "name": "IsCompete", "dataType": "bool"}," +
                "{ "name": "ManufacturedOn", "dataType": "DateTime"}" +
                "]}]}";

            request.ContentLength = datasetJson.Length;
            //POST web request
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(datasetJson);
            request.ContentLength = byteArray.Length;

            //Write JSON byte[] into a Stream
            using (Stream writer = request.GetRequestStream())
            {
                writer.Write(byteArray, 0, byteArray.Length);
                writer.Close();
                var response = (HttpWebResponse)request.GetResponse();

                Console.WriteLine(string.Format("Dataset {0}", response.StatusCode.ToString()));

                Console.WriteLine("createDataset operation is successfull.");
                Console.WriteLine("***");

            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("createDataset encounters an error: ");
            Console.WriteLine(ex.Message);
        }
    }

    private static string getDatasetId()
    {
        string datasetId = string.Empty;
        string powerBIDatasetsApiUrl = "https://api.powerbi.com/v1.0/myorg/datasets";

        try
        {

            //POST web request to create a dataset.
            //To create a Dataset in a group, use the Groups uri: https://api.PowerBI.com/v1.0/myorg/groups/{group_id}/datasets
            HttpWebRequest request = System.Net.WebRequest.Create(powerBIDatasetsApiUrl) as System.Net.HttpWebRequest;
            request.KeepAlive = true;
            request.Method = "GET";
            request.ContentLength = 0;
            request.ContentType = "application/json";

            if(String.IsNullOrEmpty(token))
            {
                Console.WriteLine("token is empty.");
                return null;
            }

            //Add token to the request header
            request.Headers.Add("Authorization", String.Format("Bearer {0}", token));


            //Get HttpWebResponse from GET request
            using (HttpWebResponse httpResponse = request.GetResponse() as System.Net.HttpWebResponse)
            {
                //Get StreamReader that holds the response stream
                using (StreamReader reader = new System.IO.StreamReader(httpResponse.GetResponseStream()))
                {
                    string responseContent = reader.ReadToEnd();

                    //TODO: Install NuGet Newtonsoft.Json package: Install-Package Newtonsoft.Json
                    //and add using Newtonsoft.Json
                    var results = JsonConvert.DeserializeObject<dynamic>(responseContent);

                    //Get the first id
                    datasetId = results["value"][0]["id"];

                    Console.WriteLine(String.Format("Dataset ID: {0}", datasetId));
                    Console.WriteLine("getDatasetId operation is successfull. ");
                    Console.WriteLine("***");

                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("getDatasetId encounters an error. ");
            Console.WriteLine(ex.Message);                
        }


        return datasetId;
    }

    private static void addRowsToDataset(string DatasetId, string TabloAdi)
    {
        string powerBIApiAddRowsUrl = null;
        HttpWebRequest request = null;

        try
        {

            powerBIApiAddRowsUrl = String.Format("https://api.powerbi.com/v1.0/myorg/datasets/{0}/tables/{1}/rows", DatasetId, TabloAdi);

            //POST web request to add rows.
            //To add rows to a dataset in a group, use the Groups uri: https://api.powerbi.com/v1.0/myorg/groups/{group_id}/datasets/{dataset_id}/tables/{table_name}/rows
            //Change request method to "POST"
            request = System.Net.WebRequest.Create(powerBIApiAddRowsUrl) as System.Net.HttpWebRequest;
            request.KeepAlive = true;
            request.Method = "POST";
            request.ContentLength = 0;
            request.ContentType = "application/json";

            if(String.IsNullOrEmpty(token))
            {
                Console.WriteLine("token is empty");
                return;
            }

            //Add token to the request header
            request.Headers.Add("Authorization", String.Format("Bearer {0}", token));

            //JSON content for product row
            string rowsJson = "{"rows":" +
                "[{"ProductID":1,"Name":"Adjustable Race","Category":"Components","IsCompete":true,"ManufacturedOn":"07/30/2014"}," +
                "{"ProductID":2,"Name":"LL Crankarm","Category":"Components","IsCompete":true,"ManufacturedOn":"07/30/2014"}," +
                "{"ProductID":3,"Name":"HL Mountain Frame - Silver","Category":"Bikes","IsCompete":true,"ManufacturedOn":"07/30/2014"}]}";

            //POST web request
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(rowsJson);
            request.ContentLength = byteArray.Length;

            //Write JSON byte[] into a Stream
            using (Stream writer = request.GetRequestStream())
            {
                writer.Write(byteArray, 0, byteArray.Length);

                //Here is the erroneous point: 
                var response = (HttpWebResponse)request.GetResponse();

            }

            Console.WriteLine("addRowsToDataset operation is successfull. ");
            Console.WriteLine("***");

        }
        catch (Exception ex)
        {
            Console.WriteLine("addRowsToDataset encounters an error.");
            Console.WriteLine(ex.Message);
            return;
        }


    }
}


Message 2 of 4

12,612 Views

Eric_Zhang

  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Subscribe to RSS Feed
  • Permalink
  • Print
  • Report Inappropriate Content

‎02-21-2017

05:31 AM

@tsozgen

The 404 error is because the passed table name is incorrect. CorporationProduct is the dataset name, while in your case, the table name should be product. 

addRowsToDataset(datasetId, "CorporationProduct");

You should also use a foreach loop in the getDataSetID function, otherwise when there’re already other datasets, you code would go to error as well.

using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;

class Program
{
    private static string token = string.Empty;

    static void Main(string[] args)
    {
        string datasetId = string.Empty;

        try
        {
            token = getAuthenticationToken();

            createDataset();

            datasetId = getDatasetId();

            

            addRowsToDataset(datasetId, "Product");

            Console.ReadKey();
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occured in main function. ");
            Console.WriteLine(ex.Message);
        }

    }

    private static string getAuthenticationToken()
    {
        string token = null;


        // TODO: Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.21.301221612
        // and add using Microsoft.IdentityModel.Clients.ActiveDirectory
        try
        {

            //The client id that Azure AD created when you registered your client app.
            string clientID = "myclientid";

            //RedirectUri you used when you register your app.
            //For a client app, a redirect uri gives Azure AD more details on the application that it will authenticate.
            // You can use this redirect uri for your client app
            string redirectUri = "https://login.live.com/oauth20_desktop.srf";

            //Resource Uri for Power BI API
            string resourceUri = "https://analysis.windows.net/powerbi/api";

            //OAuth2 authority Uri
            string authorityUri = "https://login.windows.net/common/oauth2/authorize";

            //Get access token:
            // To call a Power BI REST operation, create an instance of AuthenticationContext and call AcquireToken
            // AuthenticationContext is part of the Active Directory Authentication Library NuGet package
            // To install the Active Directory Authentication Library NuGet package in Visual Studio,
            //  run "Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory" from the nuget Package Manager Console.

            // AcquireToken will acquire an Azure access token
            // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
            AuthenticationContext authContext = new AuthenticationContext(authorityUri);

            token = authContext.AcquireToken(resourceUri, clientID, new Uri(redirectUri)).AccessToken;
            Console.WriteLine(token);
            Console.WriteLine("getAuthenticationToken operation is successfull.");
            Console.WriteLine("***");

        }
        catch (Exception ex)
        {
            Console.WriteLine("getAuthenticationToken encounters an error: ");
            Console.WriteLine(ex.Message);
        }


        return token;
    }

    /// <summary>
    /// Azure'de veri kümesi oluşturan yordam. 
    /// </summary>
    /// <remarks> System.Net ve using System.IO eklenmeli. </remarks>
    private static void createDataset()
    {

        HttpWebRequest request = null;
        string datasetJson = null;
        //Push data into a Power BI dashboard
        try
        {

            string powerBIDatasetsApiUrl = "https://api.powerbi.com/v1.0/myorg/datasets";
            //POST web request to create a dataset.
            //To create a Dataset in a group, use the Groups uri: https://api.PowerBI.com/v1.0/myorg/groups/{group_id}/datasets

            request = System.Net.WebRequest.Create(powerBIDatasetsApiUrl) as System.Net.HttpWebRequest;
            request.KeepAlive = true;
            request.Method = "POST";

            request.ContentType = "application/json";

            if (String.IsNullOrEmpty(token))
            {
                Console.WriteLine("token is null. ");
                return;
            }

            //Add token to the request header
            request.Headers.Add("Authorization", String.Format("Bearer {0}", token));

            //Create dataset JSON for POST request
            datasetJson = "{"name": "CorporationProduct", "tables": " +
                "[{"name": "Product", "columns": " +
                "[{ "name": "ProductID", "dataType": "Int64"}, " +
                "{ "name": "Name", "dataType": "string"}, " +
                "{ "name": "Category", "dataType": "string"}," +
                "{ "name": "IsCompete", "dataType": "bool"}," +
                "{ "name": "ManufacturedOn", "dataType": "DateTime"}" +
                "]}]}";

            request.ContentLength = datasetJson.Length;
            //POST web request
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(datasetJson);
            request.ContentLength = byteArray.Length;

            //Write JSON byte[] into a Stream
            using (Stream writer = request.GetRequestStream())
            {
                writer.Write(byteArray, 0, byteArray.Length);
                writer.Close();
                var response = (HttpWebResponse)request.GetResponse();

                Console.WriteLine(string.Format("Dataset {0}", response.StatusCode.ToString()));

                Console.WriteLine("createDataset operation is successfull.");
                Console.WriteLine("***");

            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("createDataset encounters an error: ");
            Console.WriteLine(ex.Message);
        }
    }

    private static string getDatasetId()
    {
        string datasetId = string.Empty;
        string powerBIDatasetsApiUrl = "https://api.powerbi.com/v1.0/myorg/datasets";

        try
        {

            //POST web request to create a dataset.
            //To create a Dataset in a group, use the Groups uri: https://api.PowerBI.com/v1.0/myorg/groups/{group_id}/datasets
            HttpWebRequest request = System.Net.WebRequest.Create(powerBIDatasetsApiUrl) as System.Net.HttpWebRequest;
            request.KeepAlive = true;
            request.Method = "GET";
            request.ContentLength = 0;
            request.ContentType = "application/json";

            if (String.IsNullOrEmpty(token))
            {
                Console.WriteLine("token is empty.");
                return null;
            }

            //Add token to the request header
            request.Headers.Add("Authorization", String.Format("Bearer {0}", token));


            //Get HttpWebResponse from GET request
            using (HttpWebResponse httpResponse = request.GetResponse() as System.Net.HttpWebResponse)
            {
                //Get StreamReader that holds the response stream
                using (StreamReader reader = new System.IO.StreamReader(httpResponse.GetResponseStream()))
                {
                    string responseContent = reader.ReadToEnd();

                    //TODO: Install NuGet Newtonsoft.Json package: Install-Package Newtonsoft.Json
                    //and add using Newtonsoft.Json
                    var results = JsonConvert.DeserializeObject<dynamic>(responseContent);

                    //Get the first id
                    //datasetId = results["value"][0]["id"];

                    foreach (var result in results["value"]) {
                        if (result["name"] == "CorporationProduct") {

                            datasetId = result["id"];
                        }


                    }


                    Console.WriteLine(String.Format("Dataset ID: {0}", datasetId));
                    Console.WriteLine("getDatasetId operation is successfull. ");
                    Console.WriteLine("***");

                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("getDatasetId encounters an error. ");
            Console.WriteLine(ex.Message);
        }


        return datasetId;
    }

    private static void addRowsToDataset(string DatasetId, string TabloAdi)
    {
        string powerBIApiAddRowsUrl = null;
        HttpWebRequest request = null;

        try
        {

            powerBIApiAddRowsUrl = String.Format("https://api.powerbi.com/v1.0/myorg/datasets/{0}/tables/{1}/rows", DatasetId, TabloAdi);

            //POST web request to add rows.
            //To add rows to a dataset in a group, use the Groups uri: https://api.powerbi.com/v1.0/myorg/groups/{group_id}/datasets/{dataset_id}/tables/{table_name}/rows
            //Change request method to "POST"
            request = System.Net.WebRequest.Create(powerBIApiAddRowsUrl) as System.Net.HttpWebRequest;
            request.KeepAlive = true;
            request.Method = "POST";
            request.ContentLength = 0;
            request.ContentType = "application/json";

            if (String.IsNullOrEmpty(token))
            {
                Console.WriteLine("token is empty");
                return;
            }

            //Add token to the request header
            request.Headers.Add("Authorization", String.Format("Bearer {0}", token));

            //JSON content for product row
            string rowsJson = "{"rows":" +
                "[{"ProductID":1,"Name":"Adjustable Race","Category":"Components","IsCompete":true,"ManufacturedOn":"07/30/2014"}," +
                "{"ProductID":2,"Name":"LL Crankarm","Category":"Components","IsCompete":true,"ManufacturedOn":"07/30/2014"}," +
                "{"ProductID":3,"Name":"HL Mountain Frame - Silver","Category":"Bikes","IsCompete":true,"ManufacturedOn":"07/30/2014"}]}";

            //POST web request
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(rowsJson);
            request.ContentLength = byteArray.Length;

            //Write JSON byte[] into a Stream
            using (Stream writer = request.GetRequestStream())
            {
                writer.Write(byteArray, 0, byteArray.Length);

                //Here is the erroneous point: 
                var response = (HttpWebResponse)request.GetResponse();

            }

            Console.WriteLine("addRowsToDataset operation is successfull. ");
            Console.WriteLine("***");

        }
        catch (Exception ex)
        {
            Console.WriteLine("addRowsToDataset encounters an error.");
            Console.WriteLine(ex.Message);
            return;
        }


    }
}


Message 3 of 4

17,199 Views

tondeli

  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Subscribe to RSS Feed
  • Permalink
  • Print
  • Report Inappropriate Content

‎05-09-2017

01:20 AM

I have almost the same code and I’m trying to follow this guide: https://powerbi.microsoft.com/en-us/documentation/powerbi-developer-walkthrough-push-data-register-a…

I get error on line 186

var response = (HttpWebResponse)request.GetResponse();

Error message: System.Net.WebException (404)

My code seem to be a bit different than yours from the Add rows to a Power BI table part:

using System;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Net;
using System.IO;
using Newtonsoft.Json;

namespace walkthrough_push_data
{
    class Program
    {
        private static string token = string.Empty;

        static void Main(string[] args)
        {

            //Get an authentication access token
            token = GetToken();

            //Create a dataset in Power BI
            CreateDataset();

            //Get a dataset to add rows into a Power BI table
            string datasetId = GetDataset();

            //Add rows to a Power BI table
            AddRows(datasetId, "Product");

        }

        #region Get an authentication access token
        private static string GetToken()
        {
            // TODO: Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.21.301221612
            // and add using Microsoft.IdentityModel.Clients.ActiveDirectory

            //The client id that Azure AD created when you registered your client app.
            string clientID = "mycliendID";

            //RedirectUri you used when you register your app.
            //For a client app, a redirect uri gives Azure AD more details on the application that it will authenticate.
            // You can use this redirect uri for your client app
            string redirectUri = "https://login.live.com/oauth20_desktop.srf";

            //Resource Uri for Power BI API
            string resourceUri = "https://analysis.windows.net/powerbi/api";

            //OAuth2 authority Uri
            string authorityUri = "https://login.windows.net/common/oauth2/authorize";

            //Get access token:
            // To call a Power BI REST operation, create an instance of AuthenticationContext and call AcquireToken
            // AuthenticationContext is part of the Active Directory Authentication Library NuGet package
            // To install the Active Directory Authentication Library NuGet package in Visual Studio,
            //  run "Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory" from the nuget Package Manager Console.

            // AcquireToken will acquire an Azure access token
            // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
            AuthenticationContext authContext = new AuthenticationContext(authorityUri);
            string token = authContext.AcquireToken(resourceUri, clientID, new Uri(redirectUri)).AccessToken;

            Console.WriteLine(token);
            Console.ReadLine();

            return token;
        }

        #endregion

        #region Create a dataset in a Power BI
        private static void CreateDataset()
        {
            //TODO: Add using System.Net and using System.IO

            string powerBIDatasetsApiUrl = "https://api.powerbi.com/v1.0/myorg/datasets";
            //POST web request to create a dataset.
            //To create a Dataset in a group, use the Groups uri: https://api.PowerBI.com/v1.0/myorg/groups/{group_id}/datasets
            HttpWebRequest request = System.Net.WebRequest.Create(powerBIDatasetsApiUrl) as System.Net.HttpWebRequest;
            request.KeepAlive = true;
            request.Method = "POST";
            request.ContentLength = 0;
            request.ContentType = "application/json";

            //Add token to the request header
            request.Headers.Add("Authorization", String.Format("Bearer {0}", token));

            //Create dataset JSON for POST request
            string datasetJson = "{"name": "SalesMarketing", "tables": " +
                "[{"name": "Product", "columns": " +
                "[{ "name": "ProductID", "dataType": "Int64"}, " +
                "{ "name": "Name", "dataType": "string"}, " +
                "{ "name": "Category", "dataType": "string"}," +
                "{ "name": "IsCompete", "dataType": "bool"}," +
                "{ "name": "ManufacturedOn", "dataType": "DateTime"}" +
                "]}]}";

            //POST web request
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(datasetJson);
            request.ContentLength = byteArray.Length;

            //Write JSON byte[] into a Stream
            using (Stream writer = request.GetRequestStream())
            {
                writer.Write(byteArray, 0, byteArray.Length);

                var response = (HttpWebResponse)request.GetResponse();

                Console.WriteLine(string.Format("Dataset {0}", response.StatusCode.ToString()));

                Console.ReadLine();
            }
        }
        #endregion

        #region Get a dataset to add rows into a Power BI table
        private static string GetDataset()
        {
            string powerBIDatasetsApiUrl = "https://api.powerbi.com/v1.0/myorg/datasets";
            //POST web request to create a dataset.
            //To create a Dataset in a group, use the Groups uri: https://api.PowerBI.com/v1.0/myorg/groups/{group_id}/datasets
            HttpWebRequest request = System.Net.WebRequest.Create(powerBIDatasetsApiUrl) as System.Net.HttpWebRequest;
            request.KeepAlive = true;
            request.Method = "GET";
            request.ContentLength = 0;
            request.ContentType = "application/json";

            //Add token to the request header
            request.Headers.Add("Authorization", String.Format("Bearer {0}", token));

            string datasetId = string.Empty;
            //Get HttpWebResponse from GET request
            using (HttpWebResponse httpResponse = request.GetResponse() as System.Net.HttpWebResponse)
            {
                //Get StreamReader that holds the response stream
                using (StreamReader reader = new System.IO.StreamReader(httpResponse.GetResponseStream()))
                {
                    string responseContent = reader.ReadToEnd();

                    //TODO: Install NuGet Newtonsoft.Json package: Install-Package Newtonsoft.Json
                    //and add using Newtonsoft.Json
                    var results = JsonConvert.DeserializeObject<dynamic>(responseContent);

                    //Get the first id
                    datasetId = results["value"][0]["id"];

                    Console.WriteLine(String.Format("Dataset ID: {0}", datasetId));
                    Console.ReadLine();

                    return datasetId;
                }
            }
        }
        #endregion

        #region Add rows to a Power BI table
        private static void AddRows(string datasetId, string tableName)
        {
            string powerBIApiAddRowsUrl = String.Format("https://api.powerbi.com/v1.0/myorg/datasets/{0}/tables/{1}/rows", datasetId, tableName);

            //POST web request to add rows.
            //To add rows to a dataset in a group, use the Groups uri: https://api.powerbi.com/v1.0/myorg/groups/{group_id}/datasets/{dataset_id}/tables/{table_name}/rows
            //Change request method to "POST"
            HttpWebRequest request = System.Net.WebRequest.Create(powerBIApiAddRowsUrl) as System.Net.HttpWebRequest;
            request.KeepAlive = true;
            request.Method = "POST";
            request.ContentLength = 0;
            request.ContentType = "application/json";

            //Add token to the request header
            request.Headers.Add("Authorization", String.Format("Bearer {0}", token));

            //JSON content for product row
            string rowsJson = "{"rows":" +
                "[{"ProductID":1,"Name":"Adjustable Race","Category":"Components","IsCompete":true,"ManufacturedOn":"07/30/2014"}," +
                "{"ProductID":2,"Name":"LL Crankarm","Category":"Components","IsCompete":true,"ManufacturedOn":"07/30/2014"}," +
                "{"ProductID":3,"Name":"HL Mountain Frame - Silver","Category":"Bikes","IsCompete":true,"ManufacturedOn":"07/30/2014"}]}";

            //POST web request
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(rowsJson);
            request.ContentLength = byteArray.Length;

            //Write JSON byte[] into a Stream
            using (Stream writer = request.GetRequestStream())
            {
                writer.Write(byteArray, 0, byteArray.Length);

                var response = (HttpWebResponse)request.GetResponse();

                Console.WriteLine("Rows Added");

                Console.ReadLine();
            }
        }

        #endregion
    }
}

I have copied this code from step5 page. Everything seems to be working correctly until this step.

Any advice?


Message 4 of 4

12,365 Views

Helpful resources

Carousel_PBI_Wave1

2023 Release Wave 1 Plans

Power BI release plans for 2023 release wave 1 describes all new features releasing from April 2023 through September 2023.

Power BI Summit Carousel 2

Global Power BI Training

Make sure you register today for the Power BI Summit 2023. Don’t miss all of the great sessions and speakers!

BizApps LATAM 2023

Business Application LATAM Summit 2023

Join the biggest FREE Business Applications Event in LATAM this February.

Power Platform Bootcamp

Global Power Platform Bootcamp

In this bootcamp we will deep-dive into Microsoft’s Power Platform stack with hands-on sessions and labs, delivered to you by experts and community leaders.

Понравилась статья? Поделить с друзьями:
  • System net webexception the remote server returned an error 403 forbidden
  • System net webexception the remote server returned an error 401 unauthorized
  • System net webexception error trustfailure authentication failed see inner exception
  • System net http httprequestexception an error occurred while sending the request
  • System launcher ошибка загрузки xiaomi