/// <summary>
 /// Creates new content on **"My Workspace"** from .pbix, Excel, Rdl or file
 /// path in OneDrive for Business.
 /// </summary>
 /// <remarks>
 /// &lt;br/&gt;**Required scope**: Dataset.ReadWrite.All &lt;br/&gt;To set the
 /// permissions scope, see [Register an
 /// app](https://docs.microsoft.com/power-bi/developer/register-app).
 /// &lt;h3&gt;Notes&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;To import a file, request
 /// Headers should include **Content-Type: multipart/form-data** with the file
 /// [encoded as form data](https://www.w3.org/TR/html401/interact/forms.html)
 /// in the request body. &lt;/li&gt;&lt;li&gt;To import xlsx file from OneDrive
 /// for Business, request Headers should include **Content-Type:
 /// application/json** with
 /// [ImportInfo](/rest/api/power-bi/imports/postimport#importinfo) in the
 /// request body.&lt;/li&gt;&lt;li&gt;Import .pbix file from OneDrive is not
 /// supported.&lt;/li&gt;&lt;li&gt;To import large .pbix files between 1 GB and
 /// 10 GB, see [Create Temporary Upload
 /// Location](/rest/api/power-bi/imports/createtemporaryuploadlocation),
 /// supported only for workspaces on premium capacity.&lt;/li&gt;&lt;/ul&gt;
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='datasetDisplayName'>
 /// The display name of the dataset, should include file extension. Not
 /// supported when importing from OneDrive for Business.
 /// </param>
 /// <param name='importInfo'>
 /// The import to post
 /// </param>
 /// <param name='nameConflict'>
 /// Determines what to do if a dataset with the same name already exists.
 /// Default value is 'Ignore'.&lt;br/&gt;Only Abort and Overwrite are supported
 /// with Rdl files. Possible values include: 'Ignore', 'Abort', 'Overwrite',
 /// 'CreateOrOverwrite', 'GenerateUniqueName'
 /// </param>
 /// <param name='skipReport'>
 /// Determines whether to skip report import, if specified value must be
 /// 'true'. Only supported for PBIX files.
 /// </param>
 public static Import PostImport(this IImportsOperations operations, string datasetDisplayName, ImportInfo importInfo, ImportConflictHandlerMode?nameConflict = default(ImportConflictHandlerMode?), bool?skipReport = default(bool?))
 {
     return(operations.PostImportAsync(datasetDisplayName, importInfo, nameConflict, skipReport).GetAwaiter().GetResult());
 }
Example #2
0
        /// <summary>
        /// Uploads a PBIX file to the specified group
        /// </summary>
        /// <param name="operations">
        /// The import operations
        /// </param>

        /// <param name='groupId'>
        /// The group id
        /// </param>
        /// <param name='fileStream'>
        /// The PBIX file to import
        /// </param>
        /// <param name='datasetDisplayName'>
        /// The dataset display name
        /// </param>
        /// <param name='nameConflict'>
        /// Whether to overwrite dataset during conflicts
        /// </param>
        /// <param name='skipReport'>
        /// Determines whether to skip report import, if specified value must be 'true'. Only supported for PBIX files.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public static async Task <Import> PostImportWithFileAsync(this IImportsOperations operations, Guid groupId, Stream fileStream, string datasetDisplayName = default(string), ImportConflictHandlerMode?nameConflict = default(ImportConflictHandlerMode?), bool?skipReport = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
        {
            using (var _result = await operations.PostImportFileWithHttpMessage(groupId, fileStream, datasetDisplayName, nameConflict, skipReport, null, cancellationToken).ConfigureAwait(false))
            {
                return(_result.Body);
            }
        }
 /// <summary>
 /// Creates new content on the specified workspace from .pbix, .json, Excel,
 /// Rdl, or file path in OneDrive for Business.
 /// </summary>
 /// <remarks>
 /// &lt;br/&gt;**Required scope**: Dataset.ReadWrite.All &lt;br/&gt;To set the
 /// permissions scope, see [Register an
 /// app](https://docs.microsoft.com/power-bi/developer/register-app).
 /// &lt;h3&gt;Notes&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;To import a file, request
 /// Headers should include **Content-Type: multipart/form-data** with the file
 /// [encoded as form data](https://www.w3.org/TR/html401/interact/forms.html)
 /// in the request body &lt;/li&gt;&lt;li&gt;To import from OneDrive for
 /// Business, request Headers should include **Content-Type: application/json**
 /// with [ImportInfo](/rest/api/power-bi/imports/postimportingroup#importinfo)
 /// in the request body.&lt;/li&gt;&lt;li&gt;To import large .pbix files
 /// between 1 GB and 10 GB see [Create Temporary Upload Location In
 /// Group](/rest/api/power-bi/imports/createtemporaryuploadlocationingroup),
 /// supported only for workspaces on premium capacity.&lt;/li&gt;&lt;li&gt;To
 /// create a dataflow from a model.json, specify the parameter
 /// datasetDisplayName as described below.&lt;/li&gt;&lt;/ul&gt;
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='groupId'>
 /// The workspace id
 /// </param>
 /// <param name='datasetDisplayName'>
 /// The display name of the dataset should include file extension. Not
 /// supported when importing from OneDrive for Business. For importing or
 /// creating dataflows, this parameter should be hardcoded to model.json.
 /// </param>
 /// <param name='importInfo'>
 /// The import to post
 /// </param>
 /// <param name='nameConflict'>
 /// Determines what to do if a dataset with the same name already exists.
 /// Default value is 'Ignore'.&lt;br/&gt;Only Abort and Overwrite are supported
 /// with Rdl files.&lt;br/&gt;Only Abort and GenerateUniqueName are supported
 /// with dataflow model.json files. Possible values include: 'Ignore', 'Abort',
 /// 'Overwrite', 'CreateOrOverwrite', 'GenerateUniqueName'
 /// </param>
 /// <param name='skipReport'>
 /// Determines whether to skip report import, if specified value must be
 /// 'true'. Only supported for PBIX files.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <Import> PostImportInGroupAsync(this IImportsOperations operations, System.Guid groupId, string datasetDisplayName, ImportInfo importInfo, ImportConflictHandlerMode?nameConflict = default(ImportConflictHandlerMode?), bool?skipReport = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.PostImportInGroupWithHttpMessagesAsync(groupId, datasetDisplayName, importInfo, nameConflict, skipReport, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Example #4
0
 /// <summary>
 /// Uploads a PBIX file to the specified group
 /// </summary>
 /// <param name="operations">
 /// The import operations
 /// </param>
 /// <param name='groupId'>
 /// The group id
 /// </param>
 /// <param name='fileStream'>
 /// The PBIX file to import
 /// </param>
 /// <param name='datasetDisplayName'>
 /// The dataset display name
 /// </param>
 /// <param name='nameConflict'>
 /// Whether to overwrite dataset during conflicts
 /// </param>
 /// <param name='skipReport'>
 /// Determines whether to skip report import, if specified value must be 'true'. Only supported for PBIX files.
 /// </param>
 public static Import PostImportWithFile(this IImportsOperations operations, Guid groupId, Stream fileStream, string datasetDisplayName = default(string), ImportConflictHandlerMode?nameConflict = default(ImportConflictHandlerMode?), bool?skipReport = default(bool?))
 {
     return(Task.Factory.StartNew(s => ((IImportsOperations)s).PostImportFileWithHttpMessage(groupId, fileStream, datasetDisplayName, nameConflict, skipReport), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult().Body);
 }
        /// <summary>
        /// Uploads a PBIX file to the specified group
        /// </summary>
        /// <param name='groupId'>
        /// The group Id
        /// </param>
        /// <param name='file'>
        /// The PBIX file to import
        /// </param>
        /// <param name='datasetDisplayName'>
        /// The dataset display name
        /// </param>
        /// <param name='nameConflict'>
        /// Whether to overwrite dataset during conflicts
        /// </param>
        /// <param name='skipReport'>
        /// Determines whether to skip report import, if specified value must be 'true'. Only supported for PBIX files.
        /// </param>
        /// <param name="customHeaders">
        /// Optional custom headers
        /// </param>
        /// <param name="cancellationToken">
        /// Optional cancellation token
        /// </param>
        public async Task <HttpOperationResponse <Import> > PostImportFileWithHttpMessage(Guid?groupId, Stream file, string datasetDisplayName = default(string), ImportConflictHandlerMode?nameConflict = default(ImportConflictHandlerMode?), bool?skipReport = default(bool?), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Tracing
            string _invocationId = null;

            if (ServiceClientTracing.IsEnabled)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("groupId", groupId);
                tracingParameters.Add("file", file);
                tracingParameters.Add("datasetDisplayName", datasetDisplayName);
                tracingParameters.Add("nameConflict", nameConflict);
                tracingParameters.Add("skipReport", skipReport);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "PostImport", tracingParameters);
            }

            if (file == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "file");
            }

            if (string.IsNullOrEmpty(datasetDisplayName))
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "datasetDisplayName");
            }

            if (file.Length > 1 * GB)
            {
                return(await UploadLargeFile(groupId, file, datasetDisplayName, nameConflict, skipReport, customHeaders, cancellationToken));
            }
            else
            {
                return(await UploadFile(groupId, file, datasetDisplayName, nameConflict, skipReport, customHeaders, cancellationToken));
            }
        }
 /// <summary>
 /// Uploads a PBIX file to the MyWorkspace
 /// </summary>
 /// <param name='file'>
 /// The PBIX file to import
 /// </param>
 /// <param name='datasetDisplayName'>
 /// The dataset display name
 /// </param>
 /// <param name='nameConflict'>
 /// Whether to overwrite dataset during conflicts
 /// </param>
 /// <param name='skipReport'>
 /// Determines whether to skip report import, if specified value must be 'true'. Only supported for PBIX files.
 /// </param>
 /// <param name="customHeaders">
 /// Optional custom headers
 /// </param>
 /// <param name="cancellationToken">
 /// Optional cancellation token
 /// </param>
 public async Task <HttpOperationResponse <Import> > PostImportFileWithHttpMessage(Stream file, string datasetDisplayName = default(string), ImportConflictHandlerMode?nameConflict = default(ImportConflictHandlerMode?), bool?skipReport = default(bool?), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(await PostImportFileWithHttpMessage(
                groupId : null,
                file : file,
                datasetDisplayName : datasetDisplayName,
                nameConflict : nameConflict,
                skipReport : skipReport,
                customHeaders : customHeaders,
                cancellationToken : cancellationToken));
 }
        private async Task <HttpOperationResponse <Import> > UploadLargeFile(Guid?groupId, Stream file, string datasetDisplayName = default(string), ImportConflictHandlerMode?nameConflict = default(ImportConflictHandlerMode?), bool?skipReport = default(bool?), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            TemporaryUploadLocation temporaryUploadLocation;

            if (groupId == null)
            {
                temporaryUploadLocation = Client.Imports.CreateTemporaryUploadLocation();
            }
            else
            {
                temporaryUploadLocation = Client.Imports.CreateTemporaryUploadLocationInGroup(groupId.Value);
            }

            if (temporaryUploadLocation == null || string.IsNullOrEmpty(temporaryUploadLocation.Url))
            {
                throw new Exception("Create temporary upload location step failed");
            }

            await UploadFileToBlob(temporaryUploadLocation.Url, file, cancellationToken);

            using (var powerBIClient = new PowerBIClient(Client.BaseUri, Client.Credentials))
            {
                powerBIClient.HttpClient.Timeout = new TimeSpan(hours: 0, minutes: PostImportTimeoutInMinutes, seconds: 0);

                if (Path.GetExtension(datasetDisplayName) == string.Empty)
                {
                    datasetDisplayName = Path.GetFileNameWithoutExtension(datasetDisplayName) + ".pbix";
                }

                if (groupId == null)
                {
                    return(await powerBIClient.Imports.PostImportWithHttpMessagesAsync(datasetDisplayName, new ImportInfo { FileUrl = temporaryUploadLocation.Url }, nameConflict, skipReport));
                }
                else
                {
                    return(await powerBIClient.Imports.PostImportInGroupWithHttpMessagesAsync(groupId.Value, datasetDisplayName, new ImportInfo { FileUrl = temporaryUploadLocation.Url }, nameConflict, skipReport));
                }
            }
        }
        private async Task <HttpOperationResponse <Import> > UploadFile(Guid?groupId, Stream file, string datasetDisplayName = default(string), ImportConflictHandlerMode?nameConflict = default(ImportConflictHandlerMode?), bool?skipReport = default(bool?), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            var groupsPart = groupId.HasValue ? "v1.0/myorg/groups/{groupId}/imports" : "v1.0/myorg/imports";
            var _baseUrl   = this.Client.BaseUri.AbsoluteUri;
            var _url       = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), groupsPart).ToString();

            if (groupId.HasValue)
            {
                _url = _url.Replace("{groupId}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(groupId, Client.SerializationSettings).Trim('"')));
            }

            List <string> _queryParameters = new List <string>();

            if (datasetDisplayName != null)
            {
                _queryParameters.Add(string.Format("datasetDisplayName={0}", Uri.EscapeDataString(datasetDisplayName)));
            }
            if (nameConflict != null)
            {
                _queryParameters.Add(string.Format("nameConflict={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(nameConflict, Client.SerializationSettings).Trim('"'))));
            }
            if (skipReport != null)
            {
                _queryParameters.Add(string.Format("skipReport={0}", skipReport));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }

            // Create HTTP transport objects
            HttpRequestMessage  _httpRequest  = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            var multiPartContent = new MultipartFormDataContent();

            multiPartContent.Add(new StreamContent(file));

            _httpRequest.Content = multiPartContent;

            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 202) // Accepted
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, null);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <Import>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 202) // Accepted
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = SafeJsonConvert.DeserializeObject <Import>(_responseContent, this.Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }