internal async Task <T> PostMessage <T>(string url, HttpContent httpContent) where T : class
        {
            var message = PrepareMessage(HttpMethod.Post, url);

            using (message.Content = httpContent)
            {
                var result = await httpClient.SendAsync(message);

                if (!result.IsSuccessStatusCode)
                {
                    VismaNetExceptionHandler.HandleException(await result.Content.ReadAsStringAsync(), null, await httpContent.ReadAsStringAsync(), url);
                }
                if (result.Headers.Location != null)
                {
                    if (typeof(T) == typeof(string))
                    {
                        var absoluteUri = result.Headers.Location.AbsoluteUri;
                        return(absoluteUri.Substring(absoluteUri.LastIndexOf("/") + 1) as T);
                    }
                }

                var content = await result.Content.ReadAsStringAsync();

                if (!string.IsNullOrEmpty(content))
                {
                    return(JsonConvert.DeserializeObject <T>(content));
                }

                return(default(T));
            }
        }
Beispiel #2
0
        public static async Task <List <CustomerSalesPrice> > FetchCustomerSalesPricesForItem(string itemNo,
                                                                                              VismaNetAuthorization authorization, PriceType priceType = PriceType.Undefined)
        {
            var webclient = GetHttpClient(authorization);
            {
                var apiUrl = GetApiUrlForController(VismaNetControllers.CustomerSalesPrices);
                try
                {
                    string fullUrl = string.Empty;
                    if (priceType == PriceType.Undefined)
                    {
                        fullUrl = $"{apiUrl}?inventoryId={itemNo}";
                    }
                    else
                    {
                        fullUrl = $"{apiUrl}?priceType={priceType.ToString()}&inventoryId={itemNo}";
                    }

                    return(await webclient.Get <List <CustomerSalesPrice> >(fullUrl));
                }
                catch (AggregateException e)
                {
                    VismaNetExceptionHandler.HandleException(e);
                }
                catch (WebException e)
                {
                    VismaNetExceptionHandler.HandleException(e);
                }

                return(null);
            }
        }
Beispiel #3
0
        internal static async Task <string> GetToken(string username, string password, string clientId, string secret)
        {
            using (var webclient = GetHttpClient())
            {
                var url = GetApiUrlForController(VismaNetControllers.Token);
                try
                {
                    var content = new FormUrlEncodedContent(new[]
                    {
                        new KeyValuePair <string, string>("username", username),
                        new KeyValuePair <string, string>("password", password),
                        new KeyValuePair <string, string>("client_id", clientId),
                        new KeyValuePair <string, string>("client_secret", secret),
                        new KeyValuePair <string, string>("grant_type", "password"),
                    });
                    var data = await webclient.PostMessage <JObject>(url, content);

                    return(data["token"].Value <string>());
                }
                catch (AggregateException exception)
                {
                    VismaNetExceptionHandler.HandleException(exception);
                    return(null);
                }
            }
        }
Beispiel #4
0
        internal async Task <T> Post <T>(string url, object data, string urlToGet = null, bool ignoreAbsoluteUri = false)
        {
            using (var message = PrepareMessage(HttpMethod.Post, url))
            {
                var serialized = Serialize(data);
                message.Content = new StringContent(serialized, Encoding.UTF8, "application/json");

                var result = await HttpClient.SendAsync(message);

                if (result.Headers.Location != null && !ignoreAbsoluteUri)
                {
                    if (urlToGet == null)
                    {
                        return(await Get <T>(result.Headers.Location.AbsoluteUri));
                    }
                    else
                    {
                        var pattern      = @".(.*)\/(.+)";
                        var substitution = @"$2";
                        var regex        = new Regex(pattern);
                        var id           = regex.Replace(result.Headers.Location.AbsoluteUri, substitution);
                        return(await Get <T>($"{urlToGet}/{id}"));
                    }
                }
                if (result.StatusCode == HttpStatusCode.NoContent || ignoreAbsoluteUri)
                {
                    if (urlToGet != null)
                    {
                        return(await Get <T>(urlToGet));
                    }
                    else
                    {
                        return(await Get <T>(url));
                    }
                }

                var stringData = await result.Content.ReadAsStringAsync();

                if (result.StatusCode != HttpStatusCode.OK)
                {
                    VismaNetExceptionHandler.HandleException(stringData, null, serialized);
                    return(default(T));
                }
                if (string.IsNullOrEmpty(stringData))
                {
                    return(default(T));
                }
                try
                {
                    return(Deserialize <T>(stringData));
                }
                catch (Exception e)
                {
                    throw new Exception("Could not serialize:" + Environment.NewLine + Environment.NewLine +
                                        stringData, e);
                }
            }
        }
Beispiel #5
0
 public List <CustomerInvoice> ForCustomer(Customer customer)
 {
     try
     {
         return(Task.Run(async() => await ForCustomerAsyncTask(customer)).Result);
     }
     catch (AggregateException e)
     {
         VismaNetExceptionHandler.HandleException(e);
         return(null);
     }
 }
        internal async Task <T> Post <T>(string url, object data, string urlToGet = null)
        {
            var message    = PrepareMessage(HttpMethod.Post, url);
            var serialized = await Serialize(data);

            using (message.Content = new StringContent(serialized, Encoding.UTF8, "application/json"))
            {
                var result = await httpClient.SendAsync(message);

                if (result.Headers.Location != null)
                {
                    // Fix for Visma not returning correct URL when createing salesorders of not SO type
                    if (urlToGet == null)
                    {
                        return(await Get <T>(result.Headers.Location.AbsoluteUri));
                    }
                    else
                    {
                        string pattern      = @".(.*)\/(\d+)";
                        string substitution = @"$2";
                        var    regex        = new System.Text.RegularExpressions.Regex(pattern);
                        var    id           = regex.Replace(result.Headers.Location.AbsoluteUri, substitution);
                        return(await Get <T>($"{urlToGet}/{id}"));
                    }
                }
                if (result.StatusCode == HttpStatusCode.NoContent)
                {
                    return(await Get <T>(url));
                }

                var stringData = await result.Content.ReadAsStringAsync();

                if (result.StatusCode != HttpStatusCode.OK)
                {
                    VismaNetExceptionHandler.HandleException(stringData, null, serialized);
                    return(default(T));
                }
                if (string.IsNullOrEmpty(stringData))
                {
                    return(default(T));
                }
                try
                {
                    return(await Deserialize <T>(stringData));
                }
                catch (Exception)
                {
                    throw new Exception("Could not serialize:" + Environment.NewLine + Environment.NewLine +
                                        stringData);
                }
            }
        }
        internal async Task <Stream> GetStream(string url)
        {
            url = url.Replace("http://", "https://");             // force https
            var result = await httpClient.SendAsync(PrepareMessage(HttpMethod.Get, url));

            var streamData = await result.Content.ReadAsStreamAsync();

            if (result.StatusCode != HttpStatusCode.OK)
            {
                VismaNetExceptionHandler.HandleException("Error downloading stream from Visma.net", null, null, url);
            }
            return(streamData);
        }
Beispiel #8
0
        internal static IEnumerable <Customer> FindCustomers(IEnumerable <string> urlParams,
                                                             VismaNetAuthorization authorization, string orderBy = null, int numberToRead = 0)
        {
            var listOfCustomers = new List <Customer>();
            var listOfTasks     = new List <Task>();

            var parameters = new NameValueCollection();

            if (!string.IsNullOrEmpty(orderBy))
            {
                parameters.Add("OrderBy", orderBy);
            }
            if (numberToRead > 0)
            {
                parameters.Add("NumberToRead", $"{numberToRead}");
            }

            if (urlParams == null)
            {
                var apiCallUrl = GetApiUrlForController(VismaNetControllers.Customers, parameters: parameters);
                listOfTasks.Add(GetCustomerDataTaskAsync(apiCallUrl, listOfCustomers, authorization));
            }
            else
            {
                foreach (var urlParameters in urlParams)
                {
                    var apiCallUrl = GetApiUrlForController(VismaNetControllers.Customers, urlParameters, parameters);
                    listOfTasks.Add(GetCustomerDataTaskAsync(apiCallUrl, listOfCustomers, authorization));
                }
            }

            try
            {
                Task.WaitAll(listOfTasks.ToArray());
            }
            catch (AggregateException e)
            {
                if (e.InnerException is WebException webException)
                {
                    if (webException.Response is HttpWebResponse response &&
                        response.StatusCode == HttpStatusCode.NotFound)
                    {
                        return(new List <Customer>());
                    }
                    VismaNetExceptionHandler.HandleException(webException);
                }
            }

            return(listOfCustomers);
        }
Beispiel #9
0
        internal static async Task <List <CustomerDocument> > FetchCustomerDocumentsForCustomerCd(string customerNumber,
                                                                                                  VismaNetAuthorization authorization)
        {
            using (var webclient = GetHttpClient(authorization))
            {
                var endpoint = GetApiUrlForController(VismaNetControllers.Customers);
                try
                {
                    endpoint = $"{endpoint}/{customerNumber}/documents";
                    var alldocuments = new List <CustomerDocument>();
                    int count;
                    do
                    {
                        try
                        {
                            var url = endpoint;
                            if (alldocuments.Count > 0)
                            {
                                var maxId = alldocuments.Max(x => TryParseToInt(x.referenceNumber));
                                url = AppendToQuery(endpoint, "greaterThanValue", maxId);
                            }
                            var batch = await webclient.Get <List <CustomerDocument> >(url);

                            count = batch.Count;
                            if (count == 0)
                            {
                                break;
                            }
                            alldocuments.AddRange(batch);
                        }
                        catch (Exception)
                        {
                            return(alldocuments);
                        }
                    } while (count == MaxReturnableEntitiesFromVismaNet);
                    return(alldocuments);
                }
                catch (AggregateException e)
                {
                    VismaNetExceptionHandler.HandleException(e);
                }
                catch (WebException e)
                {
                    VismaNetExceptionHandler.HandleException(e);
                }
                return(null);
            }
        }
Beispiel #10
0
 private static async Task <List <Customer> > GetCustomerDataTaskAsync(string url, List <Customer> listOfCustomer,
                                                                       VismaNetAuthorization auth)
 {
     using (var webClient = GetHttpClient(auth))
     {
         try
         {
             return(await webClient.Get <List <Customer> >(url));
         }
         catch (AggregateException e)
         {
             VismaNetExceptionHandler.HandleException(e);
             return(null);
         }
     }
 }
Beispiel #11
0
 internal static async Task Update <T>(T entity, string number, string apiControllerUri,
                                       VismaNetAuthorization authorization)
     where T : DtoProviderBase
 {
     using (var webclient = GetHttpClient(authorization))
     {
         var apiUrl = GetApiUrlForController(apiControllerUri, $"/{number}");
         try
         {
             await webclient.Put <T>(apiUrl, entity.ToDto());
         }
         catch (AggregateException e)
         {
             VismaNetExceptionHandler.HandleException(e);
         }
     }
 }
Beispiel #12
0
 internal static async Task <T> Create <T>(T entity, string apiControllerUri, VismaNetAuthorization authorization)
     where T : DtoProviderBase
 {
     using (var webclient = GetHttpClient(authorization))
     {
         var apiUrl = GetApiUrlForController(apiControllerUri);
         try
         {
             return(await webclient.Post <T>(apiUrl, entity.ToDto()));
         }
         catch (AggregateException e)
         {
             VismaNetExceptionHandler.HandleException(e);
             return(default(T));
         }
     }
 }
Beispiel #13
0
 internal static async Task <T> Get <T>(string entityNumber, string apiControllerUri,
                                        VismaNetAuthorization authorization)
 {
     using (var webclient = GetHttpClient(authorization))
     {
         var apiUrl = GetApiUrlForController(apiControllerUri, $"/{entityNumber}");
         try
         {
             return(await webclient.Get <T>(apiUrl));
         }
         catch (AggregateException e)
         {
             VismaNetExceptionHandler.HandleException(e);
             return(default(T));
         }
     }
 }
        internal async Task <T> Get <T>(string url)
        {
            url = url.Replace("http://", "https://"); // force https
            var result = await httpClient.SendAsync(PrepareMessage(HttpMethod.Get, url));

            var stringData = await result.Content.ReadAsStringAsync();

            if (result.StatusCode != HttpStatusCode.OK)
            {
                VismaNetExceptionHandler.HandleException(stringData, null, null, url);
                return(default(T));
            }
            if (string.IsNullOrEmpty(stringData))
            {
                return(default(T));
            }

            return(await Deserialize <T>(stringData));
        }
Beispiel #15
0
 internal static async Task<T> Create<T>(T entity, string apiControllerUri, VismaNetAuthorization authorization,
     string apiUriToGetFrom = null)
     where T : DtoProviderBase
 {
     var webclient = GetHttpClient(authorization);
     {
         var apiUrl = GetApiUrlForController(apiControllerUri);
         string apiGetUrl = null;
         if (apiUriToGetFrom != null)
             apiGetUrl = GetApiUrlForController(apiUriToGetFrom);
         try
         {
             return await webclient.Post<T>(apiUrl, entity.ToDto(), apiGetUrl);
         }
         catch (AggregateException e)
         {
             VismaNetExceptionHandler.HandleException(e);
             return default(T);
         }
     }
 }
Beispiel #16
0
 public static async Task <List <Contact> > FetchContactsForCustomer(string customerNumber, VismaNetAuthorization authorization)
 {
     using (var webclient = GetHttpClient(authorization))
     {
         var apiUrl = GetApiUrlForController(VismaNetControllers.Customers);
         try
         {
             var fullUrl = $"{apiUrl}/{customerNumber}/contact";
             return(await webclient.Get <List <Contact> >(fullUrl));
         }
         catch (AggregateException e)
         {
             VismaNetExceptionHandler.HandleException(e);
         }
         catch (WebException e)
         {
             VismaNetExceptionHandler.HandleException(e);
         }
         return(null);
     }
 }
        internal async Task <T> Put <T>(string url, object data, string urlToGet = null)
        {
            var message    = PrepareMessage(HttpMethod.Put, url);
            var serialized = await Serialize(data);

            using (var content = new StringContent(serialized, Encoding.UTF8, "application/json"))
            {
                message.Content = content;
                var result = await httpClient.SendAsync(message);

                if (result.Headers.Location != null)
                {
                    return(await Get <T>(result.Headers.Location.AbsoluteUri));
                }
                if (result.StatusCode == HttpStatusCode.NoContent)
                {
                    if (urlToGet != null)
                    {
                        return(await Get <T>(urlToGet));
                    }
                    else
                    {
                        return(await Get <T>(url));
                    }
                }
                var stringData = await result.Content.ReadAsStringAsync();

                if (result.StatusCode != HttpStatusCode.OK)
                {
                    VismaNetExceptionHandler.HandleException(stringData, null, serialized, url);
                    return(default(T));
                }

                if (string.IsNullOrEmpty(stringData))
                {
                    return(default(T));
                }
                return(await Deserialize <T>(stringData));
            }
        }
 public static async Task <List <InventorySummary> > FetchInventorySummaryForItem(string itemNo,
                                                                                  VismaNetAuthorization authorization)
 {
     using (var webclient = GetHttpClient(authorization))
     {
         var apiUrl = GetApiUrlForController(VismaNetControllers.InventorySummary);
         try
         {
             var fullUrl = $"{apiUrl}/{itemNo}";
             return(await webclient.Get <List <InventorySummary> >(fullUrl));
         }
         catch (AggregateException e)
         {
             VismaNetExceptionHandler.HandleException(e);
         }
         catch (WebException e)
         {
             VismaNetExceptionHandler.HandleException(e);
         }
         return(null);
     }
 }
Beispiel #19
0
 internal static async Task <List <CustomerInvoice> > FetchInvoicesForCustomerCd(string customerCd,
                                                                                 VismaNetAuthorization authorization)
 {
     using (var webclient = GetHttpClient(authorization))
     {
         var apiUrl = GetApiUrlForController(VismaNetControllers.Customers);
         try
         {
             var fullUrl = $"{apiUrl}/{customerCd}/invoice";
             return(await webclient.Get <List <CustomerInvoice> >(fullUrl));
         }
         catch (AggregateException e)
         {
             VismaNetExceptionHandler.HandleException(e);
         }
         catch (WebException e)
         {
             VismaNetExceptionHandler.HandleException(e);
         }
         return(null);
     }
 }
Beispiel #20
0
 internal static async Task <List <CustomerDocument> > FetchCustomerDocumentsForCustomerCd(string customerNumber,
                                                                                           VismaNetAuthorization authorization)
 {
     var webclient = GetHttpClient(authorization);
     {
         var endpoint = GetApiUrlForController(VismaNetControllers.Customers);
         try
         {
             var url = $"{endpoint}/{customerNumber}/document";
             await webclient.Get <List <CustomerDocument> >(url);
         }
         catch (AggregateException e)
         {
             VismaNetExceptionHandler.HandleException(e);
         }
         catch (WebException e)
         {
             VismaNetExceptionHandler.HandleException(e);
         }
         return(null);
     }
 }
Beispiel #21
0
        internal static async Task <List <DimensionSegment> > FetchDimension(string dimension,
                                                                             VismaNetAuthorization auth)
        {
            using (var webclient = GetHttpClient(auth))
            {
                var apiUrl = GetApiUrlForController(VismaNetControllers.Dimensions,
                                                    string.Format("/{0}", dimension.TrimStart('/')));
                try
                {
                    var container = await webclient.Get <DimensionContainer>(apiUrl);

                    return(container.segments);
                }
                catch (AggregateException e)
                {
                    VismaNetExceptionHandler.HandleException(e);
                }
                catch (WebException e)
                {
                    VismaNetExceptionHandler.HandleException(e);
                }
            }
            return(null);
        }