locked
ASP.NET Rest API RRS feed

  • Question

  • User1402230106 posted

    Ola my friends.  I am learning how to create an ASP.NET API to communicate with C# and SQL Server.  I have seen multiple examples online of creating a class and using get; set; to return the data, but how would I store the data in a List<>?

    I did not specify int, or string as there is one int field I want to return and 5 string fields.  Which maybe a dictionary would be a better way.  However, with me being completely new to this, I thought I would reach out and ask how to use an ASP.NET api to query SQL Server and store the results in this format?

    Wednesday, November 28, 2018 2:07 AM

All replies

  • User1402230106 posted

    Update to my OP - I have set my API to read like so

    public IEnumerable<string> GetProperties()
    {
      return new string[] { "id", "empfirstname", "emplastname", "empphone", "empaddress", "empzip" };
    }

    However, when I try to create my grid like the below, I am unable to actually access the fields that are returned in the above api call...I get compile errors of 'string' does not contain a definition for 'ID' and no extension method 'ID' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?

    And this is the code I am using to attempt to create the grid, but why are none of the values I am querying from API being "visible" to the compiler?

    private void LoadApproveUserGrid()
            {
                List<string> ApprovedUser = new List<string>();
                ApprovedUser = dal.GetApprovalGrid();
    
                Grid usergrid = new Grid();
                usergrid.Padding = new Thickness(10, 120, 0, 0);
                usergrid.RowDefinitions.Add(new RowDefinition { Height = 50 });
                foreach (var item in ApprovedUser)
                {
                    usergrid.RowDefinitions.Add(new RowDefinition { Height = 50 });
                }
                usergrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Star });
                usergrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Star });
                usergrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Star });
                usergrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Star });
                usergrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Star });
    
                Switch approveSwitch = new Switch();
                approveSwitch.IsEnabled = false;
    
                Label idHeader = new Label
                {
                    Text = "ID"
                };
                Label firstnameHeader = new Label
                {
                    Text = "First Name"
                };
                Label lastnameHeader = new Label
                {
                    Text = "Last Name"
                };
                Label phoneHeader = new Label
                {
                    Text = "Phone Number"
                };
                Label companyHeader = new Label
                {
                    Text = "Company Name"
                };
                Grid.SetColumn(idHeader, 1);
                Grid.SetColumn(firstnameHeader, 2);
                Grid.SetColumn(lastnameHeader, 3);
                Grid.SetColumn(phoneHeader, 4);
                Grid.SetColumn(companyHeader, 5);
                usergrid.Children.Add(idHeader);
                usergrid.Children.Add(fnameHeader);
                usergrid.Children.Add(lnameHeader);
                usergrid.Children.Add(phoneHeader);
                usergrid.Children.Add(zipHeader);
    
                int rowIndex = 1;
                foreach (var item in ApprovedUser)
                {
                    Switch userswitch = new Switch
                    {
                        ClassId=item.ID.ToString()
                    };
                    Label firstName = new Label
                    {
                        Text = item.fname
                    };
                    Label lastName = new Label
                    {
                        Text = item.lname
                    };
                    Grid.SetRow(userswitch, rowIndex);
                    Grid.SetRow(id, rowIndex);
                    Grid.SetRow(empfirstname, rowIndex);
                    Grid.SetRow(emplastname, rowIndex);
                    Grid.SetRow(empphone, rowIndex);
                    Grid.SetRow(empaddress, rowIndex);
                    Grid.SetColumn(id, 1);
                    Grid.SetColumn(empfirstname, 2);
                    Grid.SetColumn(emplastname, 3);
                    Grid.SetColumn(empphone, 4);
                    Grid.SetColumn(empaddress, 5);
                    usergrid.Children.Add(id);
                    usergrid.Children.Add(empfirstname);
                    usergrid.Children.Add(emplastname);
                    usergrid.Children.Add(empphone);
                    usergrid.Children.Add(empaddress);
                    usergrid.Children.Add(userswitch);
                    rowIndex++;
                }
                ApprovedUserGrid = usergrid;
            }
            
            public List<string> GetApprovalGrid()
            {
                string URI = "localhost/api/properties";
    
                using (var webClient = new System.Net.WebClient())
                {
                    var json = webClient.DownloadString(URI);
    
                    var message = JsonConvert.DeserializeObject<List<string>>(json);
    
                    return message;
                }
            }

    Wednesday, November 28, 2018 4:33 AM
  • User1120430333 posted

    Here is a VB.NET example using WebClient and the DTO pattern. The DTO(s) are kept in a classlib project called Entities, and all projects that need to know about the DTO(s) have reference to the Entities project. The DAL using the DAO pattern is sitting behind the WebAPI  using a single DTO or a collection of DTO(s) is a List<T> for CRUD operations with the database using EF. . The collection of DTO(s) are bindable to a UI control's Datasource.

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

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

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

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-5

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

    Imports System.Net
    Imports Entities
    Imports Newtonsoft.Json
    
    Namespace WebApi
        Public Class WebApi
            Implements IWebApi
    
            #Region "Project"
            public Function  GetProjsByUserIdApi(userid As String) as List(of DtoProject) Implements IWebApi.GetProjsByUserIdApi
    
                dim dtoprojects = new List(Of DtoProject)
    
                dim url = "http://localhost/WebApiVB/api/project/GetProjectsByUserId?userid=" & userid
    
                Using webclient As New WebClient
                    dim json  = webclient.DownloadString(url)
                    Dim projects = JsonConvert.DeserializeObject(of List(Of DtoProject))(json)
                    dtoprojects = projects
                End Using
    
                Return dtoprojects
    
            End Function
           
            public Function GetProjByIdApi(id As int32) as DtoProject Implements IWebApi.GetProjByIdApi
    
                dim dto as DtoProject
    
                dim url = "http://localhost/WebApiVB/api/project/GetProjectById?id=" & id
    
                Using webclient As New WebClient
                    dim json  = webclient.DownloadString(url)
                    Dim project = JsonConvert.DeserializeObject(of DtoProject)(json)
                    dto = project
                End Using
               
                Return dto
    
            End Function
    
            public sub CreateProjectApi(dto As DtoProject) Implements IWebApi.CreateProjectApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/project/CreateProject"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
                
            End sub
            
            public sub UpdateProjectApi(dto As DtoProject) Implements IWebApi.UpdateProjectApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/project/UpdateProject"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
    
            End sub
    
            public sub DeleteProjectApi(dto As DtoId) Implements IWebApi.DeleteProjectApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/project/DeleteProject"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
    
            End sub
    end class
    Imports System.Web.Http
    Imports DAL
    Imports Entities
    
    Namespace Controllers
    
        <CustomExceptionFilter>
        Public Class ProjectController
            Inherits ApiController
    
            Private ReadOnly _daoproject As IDaoProject
    
            public sub New (daoproject As IDaoProject)
                _daoproject = daoproject
            End sub
    
            <HttpGet>
            <ActionName("GetProjectById")>
            public Function GetProjectById(ByVal id As Int32) As DtoProject
                return _daoproject.GetProjectById(id)
            End Function
    
    
            <HttpGet>
            <ActionName("GetProjectsByUserId")>
            public Function GetProjectsByUserId(ByVal userid As String) As List(Of DtoProject)
                return _daoproject.GetProjectsByUserId(userid)
            End Function
    
            <HttpPost>
            <ActionName("CreateProject")>
            public sub CreateProject(ByVal dto As DtoProject)
                Call _daoproject.CreateProject(dto)
            End sub
            
            <HttpPost>
            <ActionName("UpdateProject")>
            public sub UpdateProject(ByVal dto As DtoProject)
                Call _daoproject.UpdateProject(dto)
            End sub
    
            <HttpPost>
            <ActionName("DeleteProject")>
            public sub  DeleteProject(ByVal dto As DtoId)
                Call _daoproject.DeleteProject(dto.Id)
            End sub
            
        End Class
    End Namespace
    Imports Entities
    
    Public Interface IDaoProject
        Function GetProjectById(ByVal id As Int32) As DtoProject
        Function GetProjectsByUserId(ByVal userid As String) As List(Of DtoProject)
        Sub CreateProject(ByVal dto As DtoProject)
        Sub UpdateProject(ByVal dto As DtoProject)
        Sub DeleteProject(ByVal id As Int32)
    End Interface
    
    Imports System.Data.Entity
    Imports Entities
    
    Public Class DaoProject
        Implements IDaoProject
    
        Private ReadOnly context As ProjectManagementEntities
    
        public sub New (dbcontext As ProjectManagementEntities)
            context = dbcontext
        End sub
    
        Public Function GetProjectById(ByVal id As Int32) As DtoProject Implements IDaoProject.GetProjectById
    
            Dim dto = New DtoProject()
       
            Dim project = (context.Projects.Where(Function(a) a.ProjectId = id)).SingleOrDefault()
    
            If IsNothing(project) Then
                Return dto
            End If
    
            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
    
        End Function
    
        Public Function GetProjectsByUserId(ByVal userid As String) As List(Of DtoProject) Implements IDaoProject.GetProjectsByUserId
    
            Dim dtos = New List(Of DtoProject)
    
            dtos = (From a In context.Projects.Where(Function(a) a.UserId.Contains(userid))
                    Select New DtoProject With {.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
    
        End Function
    
        Public Sub CreateProject(ByVal dto As DtoProject) Implements IDaoProject.CreateProject
    
            Dim project = New Project() With {.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()
    
           
        End Sub
    
        Public Sub UpdateProject(ByVal dto As DtoProject) Implements IDaoProject.UpdateProject
    
            Dim project = New Project()
           
            project = (context.Projects.Where(Function(a) a.ProjectId = dto.ProjectId)).SingleOrDefault()
           
            If Not IsNothing(project) Then
                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
            End If
    
          
            If IsNothing(project) Then
                Exit Sub
            End If
    
            context.Entry(project).State = EntityState.Modified
            context.SaveChanges()
           
        End Sub
    
        Public Sub DeleteProject(ByVal id As Int32) Implements IDaoProject.DeleteProject
    
            Dim project As Project
            
            project = (context.Projects.Where(Function(a) a.ProjectId = id)).Include("Tasks").SingleOrDefault()
           
            If IsNothing(project) Then
                Exit Sub
            End If
    
            For i As Integer = 0 To  project.Tasks.Count - 1
                Dim task = project.Tasks(i)
                context.Entry(task).State = EntityState.Deleted
            Next
            
            context.Entry(project).State = EntityState.Deleted
            context.SaveChanges()
           
        End Sub
    Public Class DtoProject
    
        Public Property ProjectId As Int32
        Public Property ClientName As String
        Public Property ProjectName As String
        Public Property Technology As String
        Public Property ProjectType As String
        Public Property UserId As String
        Public Property StartDate  As DateTime
        Public Property EndDate As DateTime? 
        Public Property Cost As Decimal
       
    End Class

    End Class
    Wednesday, November 28, 2018 7:15 AM
  • User61956409 posted

    Hi ndigoMontoya,

    'string' does not contain a definition for 'ID' and no extension method 'ID' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?

    Switch userswitch = new Switch
    {
    ClassId = item.ID.ToString()
    };

    The ApprovedUser would contain the following items, and the item is string type that does not contain ID property.

    To assign value based on item of ApprovedUser, you can achieve it via index.

    Switch userswitch = new Switch
    {
        ClassId = ApprovedUser[0].ToString()
    };
    Label firstName = new Label
    {
        Text = ApprovedUser[1].ToString()
    };
    Label lastName = new Label
    {
        Text = ApprovedUser[2].ToString()
    };

    With Regards,

    Fei Han

    Thursday, November 29, 2018 9:33 AM