locked
C# Return a List from a Class Library RRS feed

  • Question

  • I have a dll file I made for my UWP application that contains multiple list.

    I want to be able to get the list from the main application based on which list I request.

    That way I would just have one return method depending on what list I wanted...

    Example from DLL...

    public class DataBaseInfo
        {
            public List<string> SupportedDeviceTypes = new List<string>();
            public List<LightingDevices> SupportedLightingDevices = new List<LightingDevices>();
    
            public DataBaseInfo()
            {
                SupportedDeviceTypes.Add("Lights");
                SupportedDeviceTypes.Add("Displays");
                SupportedDeviceTypes.Add("Recievers");
                load_LightingDatabase();           
            }
    
            private void load_LightingDatabase()
            {
                SupportedLightingDevices.Add(new LightingDevices()
                {
                    Manufacturer = "Lutron",
                    Model = "Casseta"
                });
                SupportedLightingDevices.Add(new LightingDevices()
                {
                    Manufacturer = "Philips",
                    Model = "Hue"
                });
            }
    
    
            public void getlist(string name)
            {
                // Return the list to the calling method
    
            }
        }

    How can I just get the list I want?

    For example:

    In my main program:

     for (int i = 0; i < d.SupportedDeviceTypes.Count; i++)
                {
    
                    MenuItems.Items.Add(d.SupportedDeviceTypes[i].ToString());
                }

    I want to be able to just get the list and display in on the UI.


    • Edited by CMCTS Saturday, June 8, 2019 5:14 PM
    Saturday, June 8, 2019 1:47 PM

Answers

  • Hi CMCTS,

    Thank you for posting here.

    Based on your description, you want to return a list from a classlibrary.

    You could try the following code.

     public  List<string> getlist(string name)
            {
                
                List<string> list = new List<string>();
                if(name== "Lights")
                {
                    list = SupportedDeviceTypes;
                    return list;
                }
                else
                {
                    return list;
    
                }
    
            }

    I used console app to test it.

    static void Main(string[] args)
            {
                DataBaseInfo dataBase = new DataBaseInfo();
                foreach (var item in dataBase.getlist("Lights"))
                {
                    Console.WriteLine(item);
                }
    
            }

    Test Result:

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by CMCTS Sunday, June 16, 2019 9:45 PM
    Monday, June 10, 2019 5:47 AM
  • You've added an async method, which you didn't have before (or at least didn't show us before). There are good reasons to use async void, but it needs to be done correctly, and you're doing it incorrectly. I am not an async expert at all, but Stephen Cleary certainly is. His posts about async are legend.

    This article he wrote should help you get it right:



    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    • Marked as answer by CMCTS Sunday, June 16, 2019 11:00 PM
    Sunday, June 16, 2019 10:29 PM

All replies

  • Basic example is string key indexer https://stackoverflow.com/questions/18193794/string-as-indexer-in-c-sharp

    And there is enum key indexer https://stackoverflow.com/questions/981776/using-an-enum-as-an-array-index-in-c-sharp

    Saturday, June 8, 2019 2:16 PM
  • Not sure how this would work with what I am trying to do.

    I want to be able to call the list and loop through it to display on a UI.

    I updated my original port with an example.

    Saturday, June 8, 2019 5:15 PM
  • This appears to be working like this:

    public List<string> GetDeviceList(string input)
            {
                var newList = "";
    
                List<string> RequestedList = new List<string>();
    
                if (input == "Lights")
                {
                    for (int i = 0; i < SupportedLightingDevices.Count; i++)
                    {
                        newList = SupportedLightingDevices[i].Manufacturer + " : " + SupportedLightingDevices[i].Model;
                        RequestedList.Add(newList);
                    }
                    return(RequestedList);
                }
                else
                {
                    return null;
                }
            }

    Not the most eloquent but appears to work.

    Saturday, June 8, 2019 6:01 PM
  • Actually, you should learn how to use a Layered style that just consist of the UI presentation layer and Data Access Layer (DAL) a classlib project.  Or you can have the BLL in the architecture too.

    https://www.codeproject.com/Articles/36847/Three-Layer-Architecture-in-C-NET

    What travels between layers is the DTO.

    https://www.codeproject.com/articles/1050468/data-transfer-object-design-pattern-in-csharp

    You see the concept of using the DTO pattern where the DAL does CRUD operations with the database with a DTO that is be sent to the presentation layer and the presentation layer sends the DTO back to the DAL for data persistence.

    The DTO(s) are kept in a classlib project called Entitles you can call it whatever you want to call it, and all projects have project reference to Entities and know about the DTO(s).

    I want to be able to just get the list and display in on the UI.

    One of the methods is returning a List of DtoProject objects back to the UI/presentation layer.

    using System.Collections.Generic;
    using System.Linq;
    using System.Transactions;
    using DAL.Models.DB;
    using Entities;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Options;
    
    namespace DAL
    {
        public class DaoProject :IDaoProject
        {
            private readonly IOptions<ConnectionStrings> _options;
            
            public DaoProject(IOptions<ConnectionStrings> options)
            {
                _options = options;
            }
    
            public DtoProject GetProjectById(int id)
            {
                var dto = new DtoProject();
    
                using (var context = new ProjectManagementContext(_options))
                {
                    var project = (context.Projects.Where(a => a.ProjectId == id)).SingleOrDefault();
    
                    if (project == null) return dto;
                    dto.ProjectId = project.ProjectId;
                    dto.ClientName = project.ClientName;
                    dto.ProjectName = project.ProjectName;
                    dto.Technology = project.Technology;
                    dto.ProjectType = project.ProjectType;
                    dto.UserId = project.UserId;
                    dto.StartDate = project.StartDate;
                    dto.EndDate = project.EndDate;
                    dto.Cost = project.Cost;
                }
    
                return dto;
            }
    
            public List<DtoProject> GetProjectsByUserId(string userid)
            {
                var dtos = new List<DtoProject>();
    
                using (var context = new ProjectManagementContext(_options))
                {
                    
                    dtos = (from a in context.Projects.Where(a => a.UserId.Contains(userid))
                        select new DtoProject
                        {
                            ProjectId = a.ProjectId,
                            ClientName = a.ClientName,
                            ProjectName = a.ProjectName,
                            Technology = a.Technology,
                            ProjectType = a.ProjectType,
                            UserId = a.UserId,
                            StartDate = a.StartDate,
                            EndDate = a.EndDate,
                            Cost = a.Cost
                        }).ToList();
                }
    
                return dtos;
            }
    
            public void CreateProject(DtoProject dto)
            {
                using (var context = new ProjectManagementContext(_options))
                {
                    var project = new Projects
                    {
                        ClientName = dto.ClientName,
                        ProjectName = dto.ProjectName,
                        Technology = dto.Technology,
                        ProjectType = dto.ProjectType,
                        UserId = dto.UserId,
                        StartDate = dto.StartDate,
                        EndDate = dto.EndDate,
                        Cost = dto.Cost
                    };
    
                    context.Projects.Add(project);
                    context.SaveChanges();
               }
            }
    
            public void UpdateProject(DtoProject dto)
            {
                var project = new Projects();
                
                using (var context = new ProjectManagementContext(_options))
                {
                   project = (context.Projects.Where(a => a.ProjectId == dto.ProjectId)).SingleOrDefault();
                }
    
                if (project != null)
                {
                    project.ClientName = dto.ClientName;
                    project.ProjectName = dto.ProjectName;
                    project.Technology = dto.Technology;
                    project.ProjectType = dto.ProjectType;
                    project.UserId = dto.UserId;
                    project.StartDate = dto.StartDate;
                    project.EndDate = dto.EndDate;
                    project.Cost = dto.Cost;
                }
    
                using (var dbcontext = new ProjectManagementContext(_options))
                {
                    if (project == null) return;
                    dbcontext.Entry(project).State = EntityState.Modified;
                    dbcontext.SaveChanges();
                }
            }
    
            public void DeleteProject(int id)
            {
                Projects project;
    
                using (var context = new ProjectManagementContext(_options))
                {
                   project = (context.Projects.Where(a => a.ProjectId == id)).SingleOrDefault();
                }
    
                if (project == null) return;
    
                using (var newContext = new ProjectManagementContext(_options))
                {
                   
                    var tasks = new DaoTask(_options).GetTasksByProjectId(project.ProjectId);
                    using (TransactionScope scope = new TransactionScope())
                    {
                        foreach (var task in tasks)
                        {
                            new DaoTask(_options).DeleteTask(task.TaskId);
                        }
    
                        newContext.Entry(project).State = EntityState.Deleted;
                        newContext.SaveChanges();
    
                        scope.Complete();
                    }
                }
            }
        }
    }
    

    using System;
    
    namespace Entities
    {
        public class DtoProject
        {
            public int ProjectId { get; set; }
            public string ClientName { get; set; }
            public string ProjectName { get; set; }
            public string Technology { get; set; }
            public string ProjectType { get; set; }
            public string UserId { get; set; }
            public DateTime StartDate { get; set; }
            public DateTime EndDate { get; set; }
            public decimal Cost { get; set; }
        }
    }
    

    Saturday, June 8, 2019 6:16 PM
  • Thank you. I will try to understand this and see if I can clean up my code a little bit.

    I am by far not an expect and don't always know the best and most efficient way to get the result.

    Saturday, June 8, 2019 6:58 PM
  • Thank you. I will try to understand this and see if I can clean up my code a little bit.

    I am by far not an expect and don't always know the best and most efficient way to get the result.

    I am using the DAO pattern in the DAL.

    https://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm

    http://www.dotnetfunda.com/articles/show/2319/implement-decouple-architecture-in-interface

    using System;
    using System.Collections.Generic;
    using System.Text;
    using Entities;
    
    namespace DAL
    {
        public interface IDaoProject
        {
            DtoProject GetProjectById(int id);
            List<DtoProject> GetProjectsByUserId(string userid);
            void CreateProject(DtoProject dto);
            void UpdateProject(DtoProject dto);
            void DeleteProject(int id);
        }
    }
    

    Saturday, June 8, 2019 8:22 PM
  • https://www.interactivemedia.az/sayt-acmaq-yaratmaq/Sayt açmaq bir çox insanlar üçün olduqca mürəkkəb, xeyli vaxt və xərc tələb edən bir prosess kimi görünür. Əslində isə bu, web saytların hazırlanması işini kimə etibar etdiyinizdən asılı olaraq dəyişə bilir. Sayt açmaq işini peşəkarlara həvalə etdiyiniz təqdirdə, siz qısa zaman çərçivəsində yüksək peşəkarlıqla hazırlanmış, müasir və kreativ dizayna sahib, funksional veb dizayna sahib ola bilərsiniz.

    Saturday, June 8, 2019 8:29 PM
  • https://www.interactivemedia.az/sayt-acmaq-yaratmaq/Sayt açmaq bir çox insanlar üçün olduqca mürəkkəb, xeyli vaxt və xərc tələb edən bir prosess kimi görünür. Əslində isə bu, web saytların hazırlanması işini kimə etibar etdiyinizdən asılı olaraq dəyişə bilir. Sayt açmaq işini peşəkarlara həvalə etdiyiniz təqdirdə, siz qısa zaman çərçivəsində yüksək peşəkarlıqla hazırlanmış, müasir və kreativ dizayna sahib, funksional veb dizayna sahib ola bilərsiniz.


    This is an English forum, right?
    Saturday, June 8, 2019 8:46 PM
  • Hi CMCTS,

    Thank you for posting here.

    Based on your description, you want to return a list from a classlibrary.

    You could try the following code.

     public  List<string> getlist(string name)
            {
                
                List<string> list = new List<string>();
                if(name== "Lights")
                {
                    list = SupportedDeviceTypes;
                    return list;
                }
                else
                {
                    return list;
    
                }
    
            }

    I used console app to test it.

    static void Main(string[] args)
            {
                DataBaseInfo dataBase = new DataBaseInfo();
                foreach (var item in dataBase.getlist("Lights"))
                {
                    Console.WriteLine(item);
                }
    
            }

    Test Result:

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by CMCTS Sunday, June 16, 2019 9:45 PM
    Monday, June 10, 2019 5:47 AM
  • Thank you very much. This worked. but now I am running into a new issue.

    I am trying to create separate classes inside of my .dll.  I only want to expose the main class and call all other classes from it.  I created a new UWP C# Class Library.

    First class is:

    using System.Collections.Generic;
    
    namespace Database
    {
    
        public class DeviceDatabase
        {
            ReadLibrary _read = new ReadLibrary();
    
            public void InitializeFile()
            {
                _read.InitializeFileSystem();
            }
    
            public List<string> getDeviceList()
            {
    
                return null;
    
            }
    
            public string TestReturn()
            {
                return ("Got string");
            }
        }
    }

    the method that does not work and causes my app to crash is the InitializeFile().

    namespace Database
    {
        public class ReadLibrary
        {
            string deviceList = string.Format("Configuration_Files\\Dev-Config-package.json");
    
            public List<DeviceList> _devices = new List<DeviceList>();
    
            public async void InitializeFileSystem()
            {
                StorageFile deviceFile = await Package.Current.InstalledLocation.GetFileAsync(deviceList);
    
                try
                {
                    using (StreamReader SR = new StreamReader(await deviceFile.OpenStreamForReadAsync()))
                    {
                        string jsonstring = SR.ReadToEnd();
                        RootObject config = JsonConvert.DeserializeObject<RootObject>(jsonstring);
    
                        for (int i = 0; i < config.Devices.Count; i++)
                        {
                            _devices.Add(new DeviceList()
                            {
                                Manufacturer = config.Devices[i].Manufacturer,
                                Model = config.Devices[i].Model,
                                Type = config.Devices[i].Type
                            });
                        }
                    }
                }
                catch
                {
    
                }
            }
    
        }

    when I try to run my application it crashes and i get

    #if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
                UnhandledException += (sender, e) =>
                {
                    if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
                };
    #endif

    what I want to be able to do is create a dll with multiple classes and use different ones based on the code running. like a database of devices where I can choose which one I want to use but only use the main file as an entry point.

    Sunday, June 16, 2019 9:52 PM
  • You've added an async method, which you didn't have before (or at least didn't show us before). There are good reasons to use async void, but it needs to be done correctly, and you're doing it incorrectly. I am not an async expert at all, but Stephen Cleary certainly is. His posts about async are legend.

    This article he wrote should help you get it right:



    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    • Marked as answer by CMCTS Sunday, June 16, 2019 11:00 PM
    Sunday, June 16, 2019 10:29 PM
  • Thank you. I read through that article and I was able to work out some of my issues.

    Sunday, June 16, 2019 11:01 PM
  • what I want to be able to do is create a dll with multiple classes and use different ones based on the code running. like a database of devices where I can choose which one I want to use but only use the main file as an entry point.

    I showed you the example of using the DTO pattern in a prior post. The DTO is being used in the example where CRUD operations with the database is being done with the Data Access Layer ((DAL), a classlib project, sitting  behind a ASP.NET WebAPI service which is being done on the behalf the WebAPI client program. The default data exchange used by WebAPI is Json. The WebAPI service code you don't see. 

    The DTO travels between processes. The DTO travels between layers aka the classlib projects

    https://en.wikipedia.org/wiki/Data_transfer_object

    https://www.codeproject.com/Articles/1050468/Data-Transfer-Object-Design-Pattern-in-Csharp

    Below is the WebAPI client code that is doing the CRUD operations with the DAL through the WebAPI service, which also happens to be sitting in a classlib project. The WCF client is communicating with the DAL through the WebAPI service. 

    The DTO is kept in a classlib project called Entities, and the WebAPI client project, the WebAPI service project and the DAL classlib project have project reference to Entities, and they know what the DTO is about.

    You also see the Interface in play, and the purpose of using the Interface implemented the classes in each layer aka the classlib projects.

    http://www.dotnetfunda.com/articles/show/2319/implement-decouple-architecture-in-interface

    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Entities;
    
    namespace ProgMgmntCore2UserIdentity.WebApi
    {
        public interface IWebApi
        {
            List<DtoProject> GetProjsByUserIdApi(string userid);
            DtoProject GetProjByIdApi(int id);
            void CreateProjectApi(DtoProject dto);
            void UpdateProjectApi(DtoProject dto);
            void DeleteProjectApi(DtoId dto);
        }
    }
    
    =========================================================
    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using Entities;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    
    namespace ProgMgmntCore2UserIdentity.WebApi
    {
        public class WebApi : IWebApi
        {
            #region ProjectApi
            
            public List<DtoProject> GetProjsByUserIdApi(string userid)
            {
                var dtoprojects = new List<DtoProject>();
    
                using (var client = new HttpClient())
                {
                    var uri = new Uri("http://progmgmntcore2api.com/api/project/GetProjsByUserId?userid=" + userid);
    
                    var response = client.GetAsync(uri).Result;
    
                    if (!response.IsSuccessStatusCode)
                        throw new Exception(response.ToString());
    
                    var responseContent = response.Content;
                    var responseString = responseContent.ReadAsStringAsync().Result;
    
                    dynamic projects = JArray.Parse(responseString) as JArray;
    
                    foreach (var obj in projects)
                    {
                        DtoProject dto = obj.ToObject<DtoProject>();
    
                        dtoprojects.Add(dto);
                    }
                }
    
                return dtoprojects;
            }
    
            public DtoProject GetProjByIdApi(int id)
            {
                DtoProject dto;
    
                using (var client = new HttpClient())
                {
                    var uri = new Uri("http://progmgmntcore2api.com/api/project/GetProjById?id=" + id);
                    HttpResponseMessage getResponseMessage = client.GetAsync(uri).Result;
    
                    if (!getResponseMessage.IsSuccessStatusCode)
                        throw new Exception(getResponseMessage.ToString());
    
                    var responsemessage = getResponseMessage.Content.ReadAsStringAsync().Result;
    
                    dynamic project = JsonConvert.DeserializeObject(responsemessage);
    
                    dto = project.ToObject<DtoProject>();
                }
    
                return dto;
            }
    
            public void CreateProjectApi(DtoProject dto)
            {
                using (var client = new HttpClient { BaseAddress = new Uri("http://progmgmntcore2api.com") })
                {
                    string serailizeddto = JsonConvert.SerializeObject(dto);
    
                    var inputMessage = new HttpRequestMessage
                    {
                        Content = new StringContent(serailizeddto, Encoding.UTF8, "application/json")
                    };
    
                    inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                    HttpResponseMessage message =
                        client.PostAsync("api/project/CreateProject", inputMessage.Content).Result;
    
                    if (!message.IsSuccessStatusCode)
                        throw new Exception(message.ToString());
                }
            }
    
            public void UpdateProjectApi(DtoProject dto)
            {
                using (var client = new HttpClient { BaseAddress = new Uri("http://progmgmntcore2api.com") })
                {
                    string serailizeddto = JsonConvert.SerializeObject(dto);
    
                    var inputMessage = new HttpRequestMessage
                    {
                        Content = new StringContent(serailizeddto, Encoding.UTF8, "application/json")
                    };
    
                    inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                    HttpResponseMessage message =
                        client.PostAsync("api/project/UpdateProject", inputMessage.Content).Result;
    
                    if (!message.IsSuccessStatusCode)
                        throw new Exception(message.ToString());
                }
            }
    
            public void DeleteProjectApi(DtoId dto)
            {
                using (var client = new HttpClient { BaseAddress = new Uri("http://progmgmntcore2api.com") })
                {
                    string serailizeddto = JsonConvert.SerializeObject(dto);
    
                    var inputMessage = new HttpRequestMessage
                    {
                        Content = new StringContent(serailizeddto, Encoding.UTF8, "application/json")
                    };
    
                    inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                    HttpResponseMessage message =
                        client.PostAsync("api/project/DeleteProject", inputMessage.Content).Result;
    
                    if (!message.IsSuccessStatusCode)
                        throw new Exception(message.ToString());
                }
            }
    
            #endregion
    }



    • Edited by DA924x Sunday, June 16, 2019 11:14 PM
    Sunday, June 16, 2019 11:09 PM
  • I'll show another example where multiple collections of DTO(s) are coming back in a single DTO as the container for all the DTO(s). So either a collection of DTO(s) is coming back with objects in the collection with data or the collection for a given DTO of objects is empty with a collection.Count = 0.

    using Entities;
    
    namespace DAL
    {
        public interface IDaoCache
        {
            DtoCache GetCache();
        }
    }
    
    =========================================================
    using System.Collections.Generic;
    using System.Linq;
    using DAL.Models.DB;
    using Entities;
    using Microsoft.Extensions.Logging;
    using Microsoft.Extensions.Options;
    
    namespace DAL
    {
        public class DaoCache : IDaoCache
        {
            private readonly IOptions<ConnectionStrings> _options;
          
            public DaoCache(IOptions<ConnectionStrings> options)
            {
                _options = options;
            }
    
            public DtoCache GetCache()
            {
                var dtocache = new DtoCache
                {
                    ProjectTypes = new List<DtoProjectType>(),
                    Statuses = new List<DtoStatus>(),
                    Resources = new List<DtoResource>(),
                    Durations = new List<DtoDuration>()
                };
    
                using (var context = new ProjectManagementContext(_options))
                {
                    var projectypes = (from a in context.ProjectTypes select a).ToList();
                    CreateProjectTypes(dtocache, projectypes);
    
                    var statuses = (from a in context.Statuses select a).ToList();
                    CreateStatuses(dtocache, statuses);
    
                    var resources = (from a in context.Resources select a).ToList();
                    CreateResources(dtocache, resources);
    
                    var durations = (from a in context.Durations select a).ToList();
                    CreateDurations(dtocache, durations);
                }
    
                return dtocache;
            }
    
            private static void CreateProjectTypes(DtoCache dtocache, List<ProjectTypes> projectypes)
            {
                foreach (var pt in projectypes)
                {
                    var dto = new DtoProjectType
                    {
                        ProjectTypeId = pt.ProjectTypeId,
                        Text = pt.Text,
                        Value = pt.Value
                    };
    
                    dtocache.ProjectTypes.Add(dto);
                }
            }
    
            private static void CreateStatuses(DtoCache dtocache, List<Statuses> statuses)
            {
                foreach (var st in statuses)
                {
                    var dto = new DtoStatus()
                    {
                        StatusId = st.StatusId,
                        Text = st.Text,
                        Value = st.Value
                    };
    
                    dtocache.Statuses.Add(dto);
                }
            }
    
            private static void CreateResources(DtoCache dtocache, List<Resources> resources)
            {
    
                foreach (var rc in resources)
                {
                    var dto = new DtoResource()
                    {
                        ResourceId = rc.ResourceId,
                        Text = rc.Text,
                        Value = rc.Value
                    };
    
                    dtocache.Resources.Add(dto);
                }
            }
    
            private static void CreateDurations(DtoCache dtocache, List<Durations> durations)
            {
    
                foreach (var du in durations)
                {
                    var dto = new DtoDuration()
                    {
                        DurationId = du.DurationId,
                        Text = du.Text,
                        Value = du.Value
                    };
    
                    dtocache.Durations.Add(dto);
                }
            }
        }
    }
    

    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Entities;
    
    namespace ProgMgmntCore2UserIdentity.WebApi
    {
        public interface IWebApi
        {
             DtoCache GetCacheApi();
        }
    }
    
    
    ========================================
    
    
    using System.Net.Http.Headers;
    using System.Text;
    using Entities;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    
    namespace ProgMgmntCore2UserIdentity.WebApi
    {
        public class WebApi : IWebApi
        {
            #region ProjectApi
            
    
            #region CacheApi
    
            public DtoCache GetCacheApi()
            {
                var dtocache = new DtoCache();
    
                using (var client = new HttpClient())
                {
                    var uri = new Uri("http://progmgmntcore2api.com/api/cache");
    
                    var response = client.GetAsync(uri).Result;
    
                    if (!response.IsSuccessStatusCode)
                        throw new Exception(response.ToString());
    
                    var responseContent = response.Content;
                    var responseString = responseContent.ReadAsStringAsync().Result;
    
                    var deserialized = JsonConvert.DeserializeObject<DtoCacheRoot>(responseString);
    
                    dtocache.ProjectTypes = deserialized.DtoCache.ProjectTypes;
                    dtocache.Durations = deserialized.DtoCache.Durations;
                    dtocache.Statuses = deserialized.DtoCache.Statuses;
                    dtocache.Resources = deserialized.DtoCache.Resources;
                }
    
                return dtocache;
            }
    
            #endregion
        }
    }
    
    

    namespace Entities
    {
        public class DtoCacheRoot
        {
            public DtoCache DtoCache { get; set; }
        }
    }
    
    =================================================
    
    using System.Collections.Generic;
    
    namespace Entities
    {
        public class DtoCache
        {
            public List<DtoProjectType> ProjectTypes { get; set; } = new List<DtoProjectType>();
            public List<DtoStatus> Statuses { get; set; } = new List<DtoStatus>();
            public List<DtoResource> Resources { get; set; } = new List<DtoResource>();
            public List<DtoDuration> Durations { get; set; } = new List<DtoDuration>();
        }
    }
    

    Monday, June 17, 2019 12:18 AM