Thursday, January 18, 2018

How to create Web api And consuming web api in asp.net mvc application using http client

How to create api service in asp.net mvc

public class Student
        {
            public int studentId{get;set;}
            public string studentName{set;get;}

       }
public class StudentController : ApiController
    {

List<Student> _studentList=new List<Student>(){new Student(){ studentId=1, studentName=”A”}, new Student(){ studentId=2, studentName=”B”} };
     
        [Route("api/methodname")]
        [AcceptVerbs("GET")]
        public HttpResponseMessage GET()
        {
            ResponseModel responseStatus;
            try
            {
                return Request.CreateResponse(HttpStatusCode.OK, _studentList);       
            }
            catch (Exception ex)
            {
            }
        }

        public HttpResponseMessage GET(int studentId)
        {
             

         Student student=_studentList.FirstOrDefault(x=>x.studentId==studentId);
            if(student!=null)
             return Request.CreateResponse(HttpStatusCode.OK,student);       
           else
             return Request.CreateResponse(HttpStatusCode. NotFound
, null);       


        }

        [Route("api/Edit")]
        [AcceptVerbs("PUT")]
        public HttpResponseMessage PUT(int studentId,[FromBody]Student studentDetails)
        {
           
              Student student=_studentList.FirstOrDefault(x=>x.studentId==studentId);
            if(student!=null)
{
      student.studentName= studentDetails.studentName;

return Request.CreateResponse(HttpStatusCode.OK,student);       
}
 else
             return Request.CreateResponse(HttpStatusCode. NotFound
, null);       
            

        }
        [Route("api/Delete")]
        [AcceptVerbs("DELETE")]
        public HttpResponseMessage Delete (int studentId)
        {
           _studentList.Remove(studentList.FirstOrDefault(x=>x.studentId== studentId));
   return Request.CreateResponse(HttpStatusCode.OK,null);       

        }
[Route("api/POST")]
        [AcceptVerbs("POST")]
        public HttpResponseMessage POST(Student student)
        {
          //add syntax
           int i=1 //success
return Request.CreateResponse(HttpStatusCode.OK,null);       
 i=0 // insert fail
return Request.CreateResponse(HttpStatusCode.OK,i);       

        }

    }

How to consuming web api in asp.net mvc application using http client

                HttpClient client = new HttpClient();
                HttpResponseMessage response = new HttpResponseMessage();
                client.BaseAddress = new Uri(Uri);//api url ex: http://localhost:2454/api/
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
               
var result = client.GetAsync(“Get”).Result; //method name
if(result. IsSuccessStatusCode)
{
Var data = response.Content.ReadAsAsync<Student>().Result; //model class name : model type
}


//post and delete next session-- minor mistakes

Wednesday, January 10, 2018

Resolved :Failed to register URL "http://localhost:6264/" for site "Solution name(1)" application "/". Error description: Access is denied. (0x80070005)


Resolved[Resolved]
if you get an error like this while running Vs2012 project
Failed to register address "http://:/" for website "" application "/".
Error description: Access is denied. (0x80070005)
Solution
Open command prompt and run the following command as administrator
netsh http add urlacl url=http://localhost:6162/ user=everyone
Project answer > Properties > amendment Port range and make... njoyyyyyy

Tuesday, December 26, 2017

Remove last comma in a string c# WinForms

string Something = "1,5,12,34,";
Something = Something.TrimEnd(','); 

Friday, December 22, 2017

List of Entities to Datatable - Convert Entity List to DataTable

1). public static DataTable ConvertToDatatable<T>(List<T> data)
        {
            PropertyDescriptorCollection props =
                TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            for (int i = 0; i < props.Count; i++)
            {
                PropertyDescriptor prop = props[i];
                if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    table.Columns.Add(prop.Name, prop.PropertyType.GetGenericArguments()[0]);
                else
                    table.Columns.Add(prop.Name, prop.PropertyType);
            }
            object[] values = new object[props.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = props[i].GetValue(item);
                }
                table.Rows.Add(values);
            }
            return table;

        }

2). var table = entities.Select(x => new
                {
                    x.Id,
                    Contact = x.Contact.Name,
                    Address = x.Address.Address
                }).CopyToDataTable();
                

Emi calculation formula

Open Ms-Excel And type =PMT(1.3325,48,410000)

Red - interest rate 15.99% = 1.3325

black- 4 years = 48 months 

blue  -410000 - amount 

Tuesday, December 19, 2017

Sql Server Single User To Multi User

Step 1: select d.name, d.dbid, spid, login_time, nt_domain, nt_username, loginame
from sysprocesses p inner join sysdatabases d on p.dbid = d.dbid
where d.name = 'DBName'
go


Step 2: kill 122--(SpId)--spid

Step 3:ALTER DATABASE DBName

       SET MULTI_USER

Generate class from database table -- Sql to C# properties generate

declare @TableName sysname = 'TableName'
declare @Result varchar(max) = 'public class ' + @TableName + '
{'

select @Result = @Result + '
    public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; }
'
from
(
    select 
        replace(col.name, ' ', '_') ColumnName,
        column_id ColumnId,
        case typ.name 
            when 'bigint' then 'long'
            when 'binary' then 'byte[]'
            when 'bit' then 'bool'
            when 'char' then 'string'
            when 'date' then 'DateTime'
            when 'datetime' then 'DateTime'
            when 'datetime2' then 'DateTime'
            when 'datetimeoffset' then 'DateTimeOffset'
            when 'decimal' then 'decimal'
            when 'float' then 'float'
            when 'image' then 'byte[]'
            when 'int' then 'int'
            when 'money' then 'decimal'
            when 'nchar' then 'string'
            when 'ntext' then 'string'
            when 'numeric' then 'decimal'
            when 'nvarchar' then 'string'
            when 'real' then 'double'
            when 'smalldatetime' then 'DateTime'
            when 'smallint' then 'short'
            when 'smallmoney' then 'decimal'
            when 'text' then 'string'
            when 'time' then 'TimeSpan'
            when 'timestamp' then 'DateTime'
            when 'tinyint' then 'byte'
            when 'uniqueidentifier' then 'Guid'
            when 'varbinary' then 'byte[]'
            when 'varchar' then 'string'
            else 'UNKNOWN_' + typ.name
        end ColumnType,
        case 
            when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier') 
            then '?' 
            else '' 
        end NullableSign
    from sys.columns col
        join sys.types typ on
            col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
    where object_id = object_id(@TableName)
) t
order by ColumnId

set @Result = @Result  + '
}'

print @Result