Wednesday 4 June 2014

Get user Roles list in DNN

It is a very common task in DNN, when we need to get users Roles. I am posting the different ways we have in DNN by which we can get userRoles.

1. Using this code you can get User List who belongs to particular role and show users from combo box:

 DotNetNuke.Security.Roles.RoleController objRoleController = new DotNetNuke.Security.Roles.RoleController();  
 ArrayList listroles = objRoleController.GetUsersByRoleName(PortalId, "Single Portal Admin");  
 List liUserInfo=new List();  
 foreach (object i in listroles)  
 {  
 DotNetNuke.Entities.Users.UserInfo objuser = (DotNetNuke.Entities.Users.UserInfo)i;  
 liUserInfo.Add(objuser);  
 }  
 drpuser.DataSource = liUserInfo;  
 drpuser.DataTextField = "Username";  
 drpuser.DataValueField = "UserID";  
 drpuser.DataBind();  
 drpuser.Items.Insert(0, "Select User");  
 drpuser.SelectedValue = "Select User";  


OR YOU CAN USE THE FOLLOWING CODE

private void BindRolesDropDownList()
{
   drpRoles.Items.Clear();
   var roles = _roleGroupId < -1
          ? TestableRoleController.Instance.GetRoles(PortalId)
 : TestableRoleController.Instance.GetRoles(PortalId, r => r.RoleGroupID == _roleGroupId);
      drpRoles.DataSource = roles;
      drpRoles.DataTextField = "RoleName";
      drpRoles.DataValueField = "RoleId";
      drpRoles.DataBind();
      drpRoles.Items.Insert(0, new ListItem("Select Role", "-1"));
}


2. How to get portal user

 DotNetNuke.Entities.Users.UserController objUserController = new DotNetNuke.Entities.Users.UserController();  
       ArrayList listroles = objUserController.GetUsers(PortalId, true, true);  
       List liUserInfo = new List();  
       foreach (object i in listroles)  
       {  
         DotNetNuke.Entities.Users.UserInfo objuser = (DotNetNuke.Entities.Users.UserInfo)i;  
         liUserInfo.Add(objuser);  
       }  
       drpuserlist.DataSource = liUserInfo;  
       drpuserlist.DataTextField = "Username";  
       drpuserlist.DataValueField = "UserID";  
       drpuserlist.DataBind();  


3. How to add user to perticular role

 SqlDataProvider objSqlDataProvider = new SqlDataProvider();  
         Guid objGuid=new Guid(hdngroupid.Value.ToString());  
         if (objSqlDataProvider.AddUserInGroup(objGuid,Convert.ToInt32(drpuserlist.SelectedValue)) > 0)  
         {  
           Lblerror.Text = "User added in Group!";  
           Lblerror.ForeColor = System.Drawing.Color.Green;  
           binduserlist(objGuid);  
         }  
         else  
         {  
           Lblerror.Text = "User exist in Group!";  
           Lblerror.ForeColor = System.Drawing.Color.Red;  
         }  


4. How to get roles by name

 RoleController ObjRoleController = new RoleController();  
         RoleInfo OBjRoleInfo = ObjRoleController.GetRoleByName(this.PortalId, drproledropdown.SelectedValue.ToString());  
         ObjRoleController.AddUserRole(this.PortalId, this.UserId, OBjRoleInfo.RoleID, DateTime.Now, DateTime.Now.AddYears(100));  
         string flag = drproledropdown.SelectedValue.ToString();  
         switch (flag)  
         {  
           case "Practice_Admin":  
             SessionManager.eH_ControlName = "SigningUpPractice.ascx";  
             break;  
           case "Patients":  
             SessionManager.eH_ControlName = "PatientRegistration.ascx";  
             break;  
    }   


5. Get All Roles in the Website:

 ArrayList list = new ArrayList();  
     DotNetNuke.Security.Roles.RoleController mUserRoles = new DotNetNuke.Security.Roles.RoleController();  
     list = mUserRoles.GetRoles();  
     drpRoles.DataSource = list;  
     drpRoles.DataTextField = "RoleName";  
     drpRoles.DataValueField = "RoleId";  
     drpRoles.DataBind();   

That's all

Paypal Integration in ASP.NET using C#

It is very general requirement for e-commerce websites, we need to use payment gateways to implement Online Shopping in our website, which is very common functionality needed in any new website we are building in the current era of technology.
I am going to represent how we can integrate PayPal in to a website creating in ASP.NET using C#. Below steps we need to do for integration except the coding part.
1.      We need to create a test account on https://www.sandbox.paypal.com/in/webapps/mpp/home
2.      Now create an application on sandbox which will provide you app key and secret, which we need in code.
3.      Create two accounts on for buyer and one for merchant.
4.      Use the below written code to implement PayPal.

.aspx page's code is ::
  <div>  
       <table>  
         <tr>  
           <td>Price</td>  
           <td>  
             <asp:TextBox ID="txtPrice" runat="server"></asp:TextBox></td>  
         </tr>  
          <tr>  
           <td>Qunatity</td>  
           <td>  
             <asp:TextBox ID="txtQunatity" runat="server"></asp:TextBox></td>  
         </tr>  
         <tr>  
           <td>Shipping</td>  
           <td>  
             <asp:TextBox ID="txtShipping" runat="server"></asp:TextBox></td>  
         </tr>  
         <tr>  
           <td>Item Name</td>  
           <td>  
             <asp:TextBox ID="txtItemName" runat="server"></asp:TextBox></td>  
         </tr>  
         <tr>  
           <td colspan="2">  
             <asp:Button ID="btnSubmit" runat="server" Text="Pay  
               Now" OnClick="btnSubmit_Click" /></td>  
         </tr>  
       </table>  
     </div>  



.aspx.cs file's code is ::

 using System;  
 using System.Collections.Generic;  
 using System.Configuration;  
 using System.Linq;  
 using System.Web;  
 using System.Web.UI;  
 using System.Web.UI.WebControls;  
 public partial class _Default : System.Web.UI.Page  
 {  
   protected void Page_Load(object sender, EventArgs e)  
   {  
   }  
   protected void btnSubmit_Click(object sender, EventArgs e)  
   {  
     Session["pType"] = "att";  
     String rooturl = "http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"].Replace("www.", string.Empty);  
     String SuccessURL = "http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"].Replace("www.", string.Empty) + "/Success.aspx";  
     String FailedURL = "http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"].Replace("www.", string.Empty) + "/Failed.aspx";  
     Boolean IsPaypalAccountlive = Convert.ToBoolean(ConfigurationManager.AppSettings["IsPaypalAccountlive"].ToString());  
     string paypal_testing = ConfigurationManager.AppSettings["paypal_testing"].ToString();  
     string paypal_live = ConfigurationManager.AppSettings["paypal_live"].ToString();  
     string business_account = ConfigurationManager.AppSettings["business_account"].ToString();  
     string IPN_page = ConfigurationManager.AppSettings["IPN"].ToString();  
     Int32 qty = 0;  
     qty = Convert.ToInt32(txtQunatity.Text.Trim());  
     if (IsPaypalAccountlive == false)  
     {  
       Response.Redirect(paypal_testing + "?cmd=_xclick&business=" + business_account + "&item_name=" + txtItemName.Text.Trim() + "&quantity=" + qty + "&amount=" + Convert.ToDecimal(txtPrice.Text.Trim()) + "&no_shipping=2&return=" + SuccessURL + "&notify_url=" + rooturl + "/" + IPN_page + "&paypal='true'" + "&p=success" + "&cancel_return=" + FailedURL + " &custom=" + /*this.UserInfo.UserID + "_" + this.PortalId +*/"1_1" + "&no_note=10&shipping=0&currency_code=AUD&lc=US&bn=PP-BuyNowBF&charset=UTF-8");  
     }  
     else if (IsPaypalAccountlive == true)  
     {  
       Response.Redirect(paypal_live + "?cmd=_xclick&business=" + business_account + "&item_name=" + txtItemName.Text.Trim() + "&quantity=" + qty + "&amount=" + Convert.ToDecimal(txtPrice.Text.Trim()) + "&no_shipping=2&return=" + SuccessURL + "&notify_url=" + rooturl + "/" + IPN_page + "&paypal='true'" + "&p=success" + "&cancel_return=" + FailedURL + " &custom=" + /*this.UserInfo.UserID + "_" + this.PortalId +*/"1_1" + "&no_note=10&shipping=0&currency_code=AUD&lc=US&bn=PP-BuyNowBF&charset=UTF-8");  
     }  
     Session.Remove("AttendeeFee");  
     Session.Remove("AttendeeList");  
     Session.Remove("ServiceName");  
   }  
 }  


Here is the code of web.config file:
 <appSettings>  
    <add key="business_account" value="*****"/>  
   <add key="paypal_live" value="https://www.paypal.com/cgi-bin/webscr"/>  
   <add key="paypal_testing" value="https://www.sandbox.paypal.com/cgi-bin/webscr"/>  
   <add key="IsPaypalAccountlive" value="false"/>  
   <add key="IPN" value="ipnpal.aspx"/>  
  </appSettings>   

here is the IPN page's code:

Page Load code of IPN Page




IPN Page is used to verify the status of the Payment, it is verified by PayPal it self weather the payment has completed successfully or not.
 public int UserID_prop { get; set; }  
   public static int orderid = 0;  
   protected void Page_Load(object sender, EventArgs e)  
   {  
     //Post back to either sandbox or live  
     string PaypalURL = string.Empty;  
     string IsPaypalAccountlive = ConfigurationManager.AppSettings["IsPaypalAccountlive"].ToString();  
     string paypal_testing = ConfigurationManager.AppSettings["paypal_testing"].ToString();  
     string paypal_live = ConfigurationManager.AppSettings["paypal_live"].ToString();  
     if (IsPaypalAccountlive == "false")  
     {  
       //PaypalURL = "https://www.sandbox.paypal.com/cgi-bin/webscr";  
       PaypalURL = paypal_testing;  
     }  
     else  
     {  
       //PaypalURL = "https://www.paypal.com/cgi-bin/webscr";  
       PaypalURL = paypal_live;  
     }  
     HttpWebRequest req = (HttpWebRequest)WebRequest.Create(PaypalURL);  
     //Set values for the request back  
     req.Method = "POST";  
     req.ContentType = "application/x-www-form-urlencoded";  
     byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);  
     string strRequest = Encoding.ASCII.GetString(param);  
     string strResponse_copy = strRequest; //Save a copy of the initial info sent by PayPal  
     strRequest += "&cmd=_notify-validate";  
     req.ContentLength = strRequest.Length;  
     //Send the request to PayPal and get the response  
     StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);  
     streamOut.Write(strRequest);  
     streamOut.Close();  
     StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());  
     string strResponse = streamIn.ReadToEnd();  
     //Send mail with strResponse <br> strResponse_copy  
     string strtestcopy = strResponse_copy + "<br />" + strResponse;  
     streamIn.Close();  
     if (strResponse == "VERIFIED")  
     {  
       //check the payment_status is Completed  
       //check that txn_id has not been previously processed  
       //check that receiver_email is your Primary PayPal email  
       //check that payment_amount/payment_currency are correct  
       //process payment  
       // pull the values passed on the initial message from PayPal  
       NameValueCollection these_argies = HttpUtility.ParseQueryString(strResponse_copy);  
       //string user_email = these_argies["payer_email"];  
       string pay_stat = these_argies["payment_status"];  
       string amount = these_argies["amount"];  
       String[] split_values = these_argies["custom"].ToString().Split('_');  
       if (pay_stat.Equals("Completed"))  
       {  
         try  
         {  
           Response.Write("Sucess");  
         }  
         catch (Exception ex)  
         {  
           Response.Write(ex.Message);  
         }  
       }  
       // more checks needed here specially your account number and related stuff  
     }  
     else if (strResponse == "INVALID")  
     {  
       //log for manual investigation  
     }  
     else  
     {  
       //log response/ipn data for manual investigation  
     }  
   }  

That's all.