Monday, 10 December 2018

Web Api calling from client MVC c#

//WEB API CALL FROM CLIENT MVC C#

Step1: create [MVC client project]
Step2:// User.cs [Model class]
 public class User
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    }
Step3://CALLPACKAGE.cs class
  public class CallPackage
    {
        public CallPackage()
        {
            Encoding = DefaultEncoding;
            EndPointUrl = string.Empty;
            Parameters = string.Empty;
            Method = HttpVerbs.Get;
            ContentType = "application/json";
            PostData = string.Empty;
        }

        public CallPackage(string endpointUrl)
            : this()
        {
            EndPointUrl = endpointUrl;
        }

        public CallPackage(string endpoint, HttpVerbs method)
            : this(endpoint)
        {
            Method = method;
        }

        public CallPackage(string endpoint, HttpVerbs method, string postData)
            : this(endpoint, method)
        {
            PostData = postData;
        }

        public string EndPointUrl { get; set; }

        public HttpVerbs Method { get; set; }

        public string ContentType { get; set; }

        public string PostData { get; set; }
        public string Parameters { get; set; }
        public Encoding Encoding { get; set; }
        public static Encoding DefaultEncoding = Encoding.GetEncoding("iso-8859-1");
    }

Step4: // call web api from [HTTPPOST LoginPost] after you click login button, to authenticate entered credentials.
 [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult LoginPost(User obj)
        {
            if (ModelState.IsValid)
            {
                var user = AuthenticateUser(obj);
                if (user == null)
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }
            }
       
            return View();
        }

Step5:// create the api call
  public string AuthenticateUser(User authenticateUserData)
        {
            var url = GetUrl("WebAPI", "AuthenticateUser");

            var authenticateUserJson = JsonConvert.SerializeObject(authenticateUserData);
            var callPackageData = new CallPackage(url, HttpVerbs.Post, authenticateUserJson);
            var authentication = ExecString(callPackageData);
            return authentication;
        }
      
        public string GetUrl(string host, string key)
        {
           //[WEB.config =  <add key="WebAPI" value="http://localhost:000000/" />]
            string hostConfig = ConfigurationManager.AppSettings[host];
            string url = hostConfig + key;
            return url;
        }

        public string ExecString(CallPackage callPackage)
        {
            var request = (HttpWebRequest)WebRequest.Create(callPackage.EndPointUrl + callPackage.Parameters);

            request.Method = callPackage.Method.ToString();
            request.ContentLength = 0;
            request.ContentType = callPackage.ContentType;

            if (!string.IsNullOrEmpty(callPackage.PostData) && callPackage.Method == HttpVerbs.Post)
            {
                byte[] bytes = callPackage.Encoding.GetBytes(callPackage.PostData);
                request.ContentLength = bytes.Length;

                using (Stream writeStream = request.GetRequestStream())
                {
                    writeStream.Write(bytes, 0, bytes.Length);
                }
            }

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    string message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
                    throw new ApplicationException(message);
                }
                // grab the response
                StreamReader reader = new StreamReader(response.GetResponseStream());
                //// Read the content.
                string responseFromServer = reader.ReadToEnd();
                return responseFromServer;
            }
        }

Saturday, 30 May 2015

Bind Data to DataGridview using Lamba expression

If we want to bind list of objects to datagridview using coding ,we can do that by using
the following approach :-

For e.g:- If we have list of custom class that we want to bind to datagridview
List<ClassName> searchList;
 this.transactiondataGridView.DataSource = searchList.Select(x => new

{

    x.TrustAccount.Code,
 
    x.Amount,

    x.Payor,

    x.SettlementDate,

    x.PropertyAddress,

    x.Borrower

}).ToList();






                   


 




 

Wednesday, 27 May 2015

Adding file structure using treeview

  private void ListDirectory(TreeView treeView, string path)
        {
            treeView.Nodes.Clear();
            var rootDirectoryInfo = new DirectoryInfo(path);
            treeView.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo));
        }

        private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
        {
            var directoryNode = new TreeNode(directoryInfo.Name);
            foreach (var directory in directoryInfo.GetDirectories())
                directoryNode.Nodes.Add(CreateDirectoryNode(directory));
            foreach (var file in directoryInfo.GetFiles())
                directoryNode.Nodes.Add(new TreeNode(file.Name));
            return directoryNode;
        }

Wednesday, 6 May 2015

Binding List to datagridview using LINQ


List<string> listFiles=new List<string>();
//FIll your list with data that you want to display in datagridview

documentsDataGridView.DataSource = listFiles.Select(x => new { ColmnName1 = Path.GetFileName(x), ColumnName2 = x }).ToList();

//This will create two columns in datagridview with the name as :-ColmnName1 /ColmnName2
 

Tuesday, 5 May 2015

Merging Two rows in sql

How to combine two or more rows corresponding to same id to remove duplicate rows


step 1 : Create Table #EscrowNo(rootId int,reference nvarchar(50))

steo2 : insert into #EscrowNo (select distinct RootId# ,

STUFF((Select ','+ReferenceNumber

from [pfm].[Contact] pfmEscrow)

where pfmEscrow.RootId#=pfmEscrow2.RootId#

FOR XML PATH('')),1,1,'') from [pfm].[Contact] pfmEscrow2

step 3 : select * from #EscrowNo

Result:
You have merged all the rows corresponding to similar id in one row

Monday, 4 May 2015

How to delete duplicate rows table in sql

Deleting duplicate rows

e.g:- Suppose that we have a table named "Employees" having auto increment id and we want to delete latest duplicate row. In the following table we would like to delete the latest duplicate salary row, which in this case is [id=3,name=f,salary=200]




DELETE FROM [Data].[dbo].[employees] 
WHERE  id IN (SELECT TOP(1)id 
              FROM   [Data].[dbo].[employees] 
              WHERE  salary IN (SELECT salary 
                                FROM   [Data].[dbo].[employees] 
                                GROUP  BY salary 
                                HAVING Count(*) > 1) 
              ORDER  BY id DESC) 

After executing this query you will get a table without any duplicate salary



Thursday, 30 April 2015

Sql query to find Nth highest salary using TOP

SELECT TOP 1 Salary
FROM (
      SELECT DISTINCT TOP N Salary
      FROM Employee
      ORDER BY Salary DESC
      ) AS Emp
ORDER BY Salary