Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, 25 January 2022

Working with ExpandoObject in c# C-sharp

 Hello all,

Some of coolest topics , I came across, ExpandoObject in C#

dynamic dynamicObject = new ExpandoObject();


While addiing into code base, found compile time error, 

Error CS0656 Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'

To over come from this, You need to add a reference to the DLL Microsoft.CSharp.dll

It will resolve your compile time error, and you can take benifitws of ExpandoObject.

Saturday, 5 September 2015

Data Reader object to List type model Convert

How we can convert Data Reader object to List type model?
Most of developer are struggling while connecting with the DB, how to iterate those table data!
Developer may be go with DataTable fill using adapter concept, or it may be generic list concept.


I'm giving here pretty simple example for Mapping list.
 public static class Utility
    {
        public static List<T> DataReaderMappingToList<T>(IDataReader dr)
        {
            List<T> list = new List<T>();
            T obj = default(T);
            while (dr.Read())
            {
                obj = Activator.CreateInstance<T>();
                foreach (PropertyInfo prop in obj.GetType().GetProperties())
                {
                    if (!object.Equals(dr[prop.Name], DBNull.Value))
                    {
                        prop.SetValue(obj, dr[prop.Name], null);
                    }
                }
                list.Add(obj);
            }
            return list;
        }
    }

How we can access it?
// We are just passing command and iterating those kind of list.

 using (IDataReader dataReader = cmd.ExecuteReader())
                    {
                        stateDropdownAttribute = Utility.DataReaderMappingToList<StateDropdownAttribute>(dataReader);
                    }  

It's  pretty simple in this way to iterate it.

Thanks,
Gauttam

Monday, 23 March 2015

List of Model Object Post to Controller in ASP.NET MVC

Introduction

Several times, we want to post list of model object from view to controller while HttpPost. Many developers try to get the list of data through an array. But I'll tell you without using array also, we can get those list of model objects in a simpler way. Let's go step by step. Create an ASP.NET MVC 4 application. First, create two model classes, for example, EmployeeModelClass.cs and DepartmentModelClass.cs inside Model folder in solution.

Model


public class EmployeeModelClass
    {
        public string Name { get; set; }

        public string Address { get; set; }

        public string Contact { get; set; }

        public IEnumerable<DepartmentModelClass> DeptList { get; set; }                 
    }

public class DepartmentModelClass
    {
        public string DepartmentCode { get; set; }
        public string DepartmentName { get; set; }
    }  

Controller
public class EmployeeController : Controller
    {
        //
        // GET: /Employee/

        public ActionResult Index()
        {
            return View(new EmployeeModelClass());
        }

        [HttpPost]
        public ActionResult Index(EmployeeModelClass emp, IEnumerable<DepartmentModelClass> dept)
        {
            emp.DeptList = dept;
            return View(emp);
        }
    }

View

Here, I want to get Employee details with list of department names which belong to that employee. The business logic is multiple departments should assign to a single employee.
I hope you understood what I am trying to do here. See the controller. In HttpPost Action, I am not using any array to get the Department list from view page while HttpPost. Simply, I am passing two parameters inHttpPost like below:
[HttpPost]
        public ActionResult Index(EmployeeModelClass emp, IEnumerable<DepartmentModelClass> dept)
        {
            emp.DeptList = dept;
            return View(emp);
        }
See those parameters, EmployeeModelClass emp and IEnumerable<DepartmentModelClass> dept. We can get the employee data from emp object and list of department data from dept object very easily here.
See the view section inside for loop I am putting DepartmentCode and Departmentname four times. This property name should be the same as the property in Model object.
To see the result in output, append the following lines in view page:
@{
                    if (Model.Name != null)
                    {
                        <div>
                    
                            Employee Name : @Model.Name <br/>
                            Address : @Model.Address <br/>
                            Contact : @Model.Contact <br/>
                            
                            @{
                                if (Model.DeptList != null)
                                {
                                  <table>
                                        <tr>
                                            <th>Dept code</th>
                                            <th>Dept Name</th>
                                        </tr>
                                    
                                    @{
                                        foreach (var dept in Model.DeptList)
                                        {
                                            <tr>
                                                <td>@dept.DepartmentCode</td>
                                                <td>@dept.DepartmentName</td>
                                            </tr>
                                        }
                                    }
                                </table>
                            }
                            }

                        </div>
                    }
                }



Attached Code Link to Download Source


Tuesday, 18 November 2014

Twitter Auth login using dot .Net C#

Hello all,

Twitter Login using Auth in c#;

Step 1 : Create OAuthHelper.cs File use this below code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.IO;
using System.Text;
public class OAuthHelper
{
    public OAuthHelper()
    {
    }

    private static string oauth_consumer_key = "YOUR CONSUMER KEY";
    private static string oauth_consumer_secret = "YOUR CONSUMER SECRET";
    private static string callbackUrl = "YOUR CALL BACK URL";

    #region (Changable) Do Not Change It

    private static string REQUEST_TOKEN = "YOUR REQUEST TOKEN URL";
    private static string AUTHORIZE = "YOUR AUTHORIZE URL";
    private static string ACCESS_TOKEN = "YOUR ACCESS TOKEN URL";





    public enum httpMethod
    {
        POST, GET
    }
    public string oauth_request_token
    {
        get;
        set;
    }
    public string oauth_access_token
    {
        get;
        set;
    }
    public string oauth_access_token_secret
    {
        get;
        set;
    }
    public string user_id
    {
        get;
        set;
    }
    public string screen_name
    {
        get;
        set;
    }
    public string oauth_error
    {
        get;
        set;
    }

    public string GetRequestToken()
    {
        HttpWebRequest request = FetchRequestToken(httpMethod.POST, oauth_consumer_key, oauth_consumer_secret);
        string result = getResponce(request);
        Dictionary<string, string> resultData = OAuthUtility.GetQueryParameters(result);
        if (resultData.Keys.Contains("oauth_token"))
            return resultData["oauth_token"];
        else
        {
            this.oauth_error = result;
            return "";
        }
    }
    public string GetAuthorizeUrl(string requestToken)
    {
        return string.Format("{0}?oauth_token={1}", AUTHORIZE, requestToken);
    }
    public void GetUserTwAccessToken(string oauth_token, string oauth_verifier)
    {
        HttpWebRequest request = FetchAccessToken(httpMethod.POST, oauth_consumer_key, oauth_consumer_secret, oauth_token, oauth_verifier);
        string result = getResponce(request);

        Dictionary<string, string> resultData = OAuthUtility.GetQueryParameters(result);
        if (resultData.Keys.Contains("oauth_token"))
        {
            this.oauth_access_token = resultData["oauth_token"];
            this.oauth_access_token_secret = resultData["oauth_token_secret"];
            this.user_id = resultData["user_id"];
            this.screen_name = resultData["screen_name"];
        }
        else
            this.oauth_error = result;
    }
    public void TweetOnBehalfOf(string oauth_access_token, string oauth_token_secret, string postData)
    {
        HttpWebRequest request = PostTwits(oauth_consumer_key, oauth_consumer_secret, oauth_access_token, oauth_token_secret, postData);
        string result = OAuthHelper.getResponce(request);
        Dictionary<string, string> dcResult = OAuthUtility.GetQueryParameters(result);
        if (dcResult["status"] != "200")
        {
            this.oauth_error = result;
        }

    }


    HttpWebRequest FetchRequestToken(httpMethod method, string oauth_consumer_key, string oauth_consumer_secret)
    {
        string OutUrl = "";
        string OAuthHeader = OAuthUtility.GetAuthorizationHeaderForPost_OR_QueryParameterForGET(new Uri(REQUEST_TOKEN), callbackUrl, method.ToString(), oauth_consumer_key, oauth_consumer_secret, "", "", out OutUrl);

        if (method == httpMethod.GET)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(OutUrl + "?" + OAuthHeader);
            request.Method = method.ToString();
            return request;
        }
        else if (method == httpMethod.POST)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(OutUrl);
            request.Method = method.ToString();
            request.Headers["Authorization"] = OAuthHeader;
            return request;
        }
        else
            return null;


    }
    HttpWebRequest FetchAccessToken(httpMethod method, string oauth_consumer_key, string oauth_consumer_secret, string oauth_token, string oauth_verifier)
    {
        string postData = "oauth_verifier=" + oauth_verifier;
        string AccessTokenURL = string.Format("{0}?{1}", ACCESS_TOKEN, postData);
        string OAuthHeader = OAuthUtility.GetAuthorizationHeaderForPost_OR_QueryParameterForGET(new Uri(AccessTokenURL), callbackUrl, method.ToString(), oauth_consumer_key, oauth_consumer_secret, oauth_token, "", out AccessTokenURL);

        if (method == httpMethod.GET)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(AccessTokenURL + "?" + OAuthHeader);
            request.Method = method.ToString();
            return request;
        }
        else if (method == httpMethod.POST)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(AccessTokenURL);
            request.Method = method.ToString();
            request.Headers["Authorization"] = OAuthHeader;

            byte[] array = Encoding.ASCII.GetBytes(postData);
            request.GetRequestStream().Write(array, 0, array.Length);
            return request;
        }
        else
            return null;

    }
    HttpWebRequest PostTwits(string oauth_consumer_key, string oauth_consumer_secret, string oauth_access_token, string oauth_token_secret, string postData)
    {
        postData = "trim_user=true&include_entities=true&status=" + postData;
        string updateStatusURL = "https://api.twitter.com/1/statuses/update.json?" + postData;

        string outUrl;
        string OAuthHeaderPOST = OAuthUtility.GetAuthorizationHeaderForPost_OR_QueryParameterForGET(new Uri(updateStatusURL), callbackUrl, httpMethod.POST.ToString(), oauth_consumer_key, oauth_consumer_secret, oauth_access_token, oauth_token_secret, out outUrl);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(outUrl);
        request.Method = httpMethod.POST.ToString();
        request.Headers["Authorization"] = OAuthHeaderPOST;

        byte[] array = Encoding.ASCII.GetBytes(postData);
        request.GetRequestStream().Write(array, 0, array.Length);
        return request;

    }

    public static string getResponce(HttpWebRequest request)
    {
        try
        {
            HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(resp.GetResponseStream());
            string result = reader.ReadToEnd();
            reader.Close();
            return result + "&status=200";
        }
        catch (Exception ex)
        {
            string statusCode = "";
            if (ex.Message.Contains("403"))
                statusCode = "403";
            else if (ex.Message.Contains("401"))
                statusCode = "401";
            return string.Format("status={0}&error={1}", statusCode, ex.Message);
        }
    }


    #endregion
}

Step 2 : CreateOAuthUtility.cs File use this below code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

public class OAuthUtility
{
    public OAuthUtility()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    #region *******Common Methods**********
    protected static string unreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
    public static string UrlEncode(string value)
    {
        StringBuilder result = new StringBuilder();

        foreach (char symbol in value)
        {
            if (unreservedChars.IndexOf(symbol) != -1)
            {
                result.Append(symbol);
            }
            else
            {
                result.Append('%' + String.Format("{0:X2}", (int)symbol));
            }
        }

        return result.ToString();
    }

    public static string GenerateTimeStamp()
    {
        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        return Convert.ToInt64(ts.TotalSeconds).ToString();
    }
    public static string GenerateNonce()
    {
        // Just a simple implementation of a random number between 123400 and 9999999
        Random random = new Random();
        return random.Next(123400, 9999999).ToString();
    }
    public static Dictionary<string, string> GetQueryParameters(string dataWithQuery)
    {
        Dictionary<string, string> result = new Dictionary<string, string>();
        string[] parts = dataWithQuery.Split('?');
        if (parts.Length > 0)
        {
            string QueryParameter = parts.Length > 1 ? parts[1] : parts[0];
            if (!string.IsNullOrEmpty(QueryParameter))
            {
                string[] p = QueryParameter.Split('&');
                foreach (string s in p)
                {
                    if (s.IndexOf('=') > -1)
                    {
                        string[] temp = s.Split('=');
                        result.Add(temp[0], temp[1]);
                    }
                    else
                    {
                        result.Add(s, string.Empty);
                    }
                }
            }
        }
        return result;
    }
    #endregion Common Methods

    public static string GetAuthorizationHeaderForPost_OR_QueryParameterForGET(Uri url, string callbackUrl, string httpMethod, string consumerKey, string consumerSecret, string token, string tokenSecret, out string normalizedUrl)
    {
        string normalizedParameters = "";

        Dictionary<string, string> parameters = new Dictionary<string, string>();
        parameters.Add("oauth_version", "1.0");
        if (token != "")
            parameters.Add("oauth_token", token);
        parameters.Add("oauth_nonce", GenerateNonce()); //Random String
        parameters.Add("oauth_timestamp", GenerateTimeStamp()); // Current Time Span
        parameters.Add("oauth_consumer_key", consumerKey); //Customer Consumer Key
        parameters.Add("oauth_signature_method", "HMAC-SHA1"); //Singnatur Encription Method
        parameters.Add("oauth_callback", UrlEncode(callbackUrl)); //return url

        Dictionary<string, string> drQuery = GetQueryParameters(url.Query);
        foreach (string key in drQuery.Keys)
            parameters.Add(key, drQuery[key]);

        if (url.Query != "")
            normalizedUrl = url.AbsoluteUri.Replace(url.Query, "");
        else
            normalizedUrl = url.AbsoluteUri;

        List<string> li = parameters.Keys.ToList();
        li.Sort();

        StringBuilder sbOAuthHeader = new StringBuilder("OAuth ");
        StringBuilder sbSignatureBase = new StringBuilder();
        foreach (string k in li)
        {
            sbSignatureBase.AppendFormat("{0}={1}&", k, parameters[k]); // For Signature and Get Date (QueryString)
            sbOAuthHeader.AppendFormat("{0}=\"{1}\", ", k, parameters[k]); // For Post Request (Post Data)
        }

        string signature = GenerateSignatureBySignatureBase(httpMethod, consumerSecret, tokenSecret, normalizedUrl, sbSignatureBase);

        if (httpMethod == "POST")
        {
            string OAuthHeader = sbOAuthHeader.Append("oauth_signature=\"" + UrlEncode(signature) + "\"").ToString();
            normalizedParameters = OAuthHeader;
        }
        else if (httpMethod == "GET")
        {
            normalizedParameters = sbSignatureBase.AppendFormat("{0}={1}", "oauth_signature", signature).ToString(); ;
        }
        return normalizedParameters;
    }
    private static string GenerateSignatureBySignatureBase(string httpMethod, string consumerSecret, string tokenSecret, string normalizedUrl, StringBuilder sbSignatureBase)
    {
        string normalizedRequestParameters = sbSignatureBase.ToString().TrimEnd('&');
        StringBuilder signatureBase = new StringBuilder();
        signatureBase.AppendFormat("{0}&", httpMethod.ToString());
        signatureBase.AppendFormat("{0}&", UrlEncode(normalizedUrl));
        signatureBase.AppendFormat("{0}", UrlEncode(normalizedRequestParameters));

        HMACSHA1 hmacsha1 = new HMACSHA1();
        hmacsha1.Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", UrlEncode(consumerSecret), UrlEncode(tokenSecret)));
        byte[] hashBytes = hmacsha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(signatureBase.ToString()));
        return Convert.ToBase64String(hashBytes);
    }
}


Step 3 : Create login.aspx page use this code:
  var oauthhelper = new OAuthHelper();
            string requestToken = oauthhelper.GetRequestToken();

            if (string.IsNullOrEmpty(oauthhelper.oauth_error))
                Response.Redirect(oauthhelper.GetAuthorizeUrl(requestToken));
            else
                Response.Write(oauthhelper.oauth_error);



Step 4 : Create Response.aspx page to handle response use this code:
                   if (Request.QueryString["oauth_token"] != null && Request.QueryString["oauth_verifier"] != null)
                {
                    string oauth_token = Request.QueryString["oauth_token"];
                    string oauth_verifier = Request.QueryString["oauth_verifier"];
}


 Do you still need any help? Feel free to comment

Sunday, 14 September 2014

MULTIPLE VIEWMODELS IN A SINGLE MVC VIEW

This post shows how to use multiple models in a single view. The models can be used in separated forms or together in one form. You could use each child model with a separate ajax post if required. Only properties in the parent class affect the child models, but a property in a child model does not effect the Model State of the other child models. In this way multiple models can be used and also validation for each model.

How the ViewModels are implemented:
The parent model class contains all child classes. Each class is another reusable model. In this way, the validation and ModelState can be used.
namespace MultipleModelsDemo.ViewModels
{
    public class IndexViewModel
    {
        public string HeaderText { get; set; }
 
        public TestOneModel TestOne { get; set; }
 
        public TestTwoModel TestTwo { get; set; }
    }
}

A child model used for the first form.
1
2
3
4
5
6
7
8
9
10
11
12
13
using System.ComponentModel.DataAnnotations;
 
namespace MultipleModelsDemo.ViewModels
{
    public class TestOneModel
    {
        [Required]
        public string PropertyOne { get; set; }
 
        [Required]
        public string PropertyTwo { get; set; }
    }
}
A second child model used for the second form.
1
2
3
4
5
6
7
8
9
10
11
12
13
using System.ComponentModel.DataAnnotations;
 
namespace MultipleModelsDemo.ViewModels
{
    public class TestTwoModel
    {
        [Required]
        public string PropertyThree { get; set; }
 
        [Required]
        public string PropertyFour { get; set; }
    }
}
In the controller a single action method is used to recieve the form posts. The action method MyEditActionOne uses the Index model. In this action method, the ModelState.IsValid property can be checked. Due to the model structure, separate forms can be sent for each child model, or the whole model as one. Note: Any properties defined in a parent class muss be valid if set as required.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
using System.Web.Mvc;
using MultipleModelsDemo.ViewModels;
 
namespace MultipleModelsDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new IndexViewModel();
            model.HeaderText = "Strongly typed model used here, no view bag";
            return View(model);
        }
 
        public ActionResult MyEditActionOne(IndexViewModel model)
        {
            if (ModelState.IsValid)
            {
                return View("Index", model);
            }
 
            throw new Exception("My Model state is not valid");
        }
    }
}
The html uses razor and can send either a form with just the first child model, or the second child model or the whole model as one. Only what is required for each form is validated. This is due to the model structure.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@model MultipleModelsDemo.ViewModels.IndexViewModel
 
<div>
    @using (Html.BeginForm("MyEditActionOne", "Home"))
    {
        <div>
            <h4>Send Model One</h4>
            <fieldset>
                @Html.ValidationSummary(true, "ValidationSummary")
                <ol>
 
                    <li>
                        @Html.LabelFor(m => m.TestOne.PropertyOne)
                        @Html.TextBoxFor(m => m.TestOne.PropertyOne)
                        @Html.ValidationMessageFor(m => m.TestOne.PropertyOne)
                    </li>
                    <li>
                        @Html.LabelFor(m => m.TestOne.PropertyTwo)
                        @Html.TextBoxFor(m => m.TestOne.PropertyTwo)
                        @Html.ValidationMessageFor(m => m.TestOne.PropertyTwo)
                    </li>
                </ol>
            </fieldset>
             
            <input class="btn" type="submit" value="Send" />
        </div>
    }
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<div>
    @using (Html.BeginForm("MyEditActionOne", "Home"))
    {
        <div>
            <h4>Send both Models</h4>
            <fieldset>
                @Html.ValidationSummary(true, "ValidationSummary")
                <ol>
 
                    <li>
                        @Html.LabelFor(m => m.TestOne.PropertyOne)
                        @Html.TextBoxFor(m => m.TestOne.PropertyOne)
                        @Html.ValidationMessageFor(m => m.TestOne.PropertyOne)
                    </li>
                    <li>
                        @Html.LabelFor(m => m.TestOne.PropertyTwo)
                        @Html.TextBoxFor(m => m.TestOne.PropertyTwo)
                        @Html.ValidationMessageFor(m => m.TestOne.PropertyTwo)
                    </li>
                    <li>
                        @Html.LabelFor(m => m.TestTwo.PropertyThree)
                        @Html.TextBoxFor(m => m.TestTwo.PropertyThree)
                        @Html.ValidationMessageFor(m => m.TestTwo.PropertyThree)
                    </li>
                    <li>
                        @Html.LabelFor(m => m.TestTwo.PropertyFour)
                        @Html.TextBoxFor(m => m.TestTwo.PropertyFour)
                        @Html.ValidationMessageFor(m => m.TestTwo.PropertyFour)
                    </li>
                </ol>
            </fieldset>
 
            <input class="btn" type="submit" value="Send" />
        </div>
    }
</div>
As shown, it is very easy to implement multiple strongly typed models in a single view. Using this structure it would also be possible to implement a dynamic view with multiple forms or data.
Links: