Translate

ASP.NET authorize base class AuthorizeAttribute overload example

Tuesday, September 1, 2015 Category : 0

 public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        public string UsersConfigKey { get; set; }
        public string RolesConfigKey { get; set; }

        protected virtual CustomPrincipal CurrentUser
        {
            get { return HttpContext.Current.User as CustomPrincipal; }
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAuthenticated)
            {
                var authorizedUsers = ConfigurationManager.AppSettings[UsersConfigKey];
                var authorizedRoles = ConfigurationManager.AppSettings[RolesConfigKey];

                Users = String.IsNullOrEmpty(Users) ? authorizedUsers : Users;
                Roles = String.IsNullOrEmpty(Roles) ? authorizedRoles : Roles;

                if (!String.IsNullOrEmpty(Roles))
                {
                    if (!CurrentUser.IsInRole(Roles))
                    {
                        filterContext.Result = new RedirectToRouteResult(new
                        RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));

                         base.OnAuthorization(filterContext); returns to login url
                    }
                }

                if (!String.IsNullOrEmpty(Users))
                {
                    if (!Users.Contains(CurrentUser.UserId.ToString()))
                    {
                        filterContext.Result = new RedirectToRouteResult(new
                        RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));

                         base.OnAuthorization(filterContext); returns to login url
                    }
                }
            }

        }

ASP.NET GridView Sorting

Saturday, March 21, 2015 Category : 0

Process 1 : 
 protected void gvUser_Sorting(object sender, GridViewSortEventArgs e)
        {

            string search = txtSearch.Text.Trim();
            string SortExp = e.SortExpression;
           
           
            List<Common.TblUser> oList = UserBLL.GetUserList();
            if (txtSearch.Text != "")
            {
                string text = txtSearch.Text.ToUpper();
                oList = oList.FindAll(m => m.FullName.ToUpper().Contains(text) || m.RoleName.ToUpper().Contains(text) || m.UserName.ToUpper().Contains(text) || m.ExternalID.ToUpper().Contains(text)).ToList();
            }

            System.Reflection.PropertyInfo property = oList.GetType().GetGenericArguments()[0].GetProperty(SortExp);
            if (e.SortDirection == SortDirection.Ascending)
            {
                oList = oList.OrderBy(g => property.GetValue(g, null)).ToList<Common.TblUser>();
            }
            else
            {
              oList =  oList.OrderByDescending(g => property.GetValue(g, null)).ToList<Common.TblUser>();
            }

            this.gvUser.DataSource = oList;
            this.gvUser.DataBind();

        }

Process 2
Using Object Datasource


  <asp:GridView ID="GVUserList" runat="server" AutoGenerateColumns="False"
                        DataSourceID="odsGrid" AllowPaging="True" AllowSorting="True"
 DataKeyNames="CBTID" >
                        <Columns>
                            <asp:BoundField DataField="BTName" HeaderText="BTName" SortExpression="BTName" />
                        </Columns>
                        <EmptyDataTemplate>
                            <table style="width:100%;">
                                <tr>
                                    <th>No Record Added</th>
                                </tr>
                            </table>
                        </EmptyDataTemplate>
                    </asp:GridView>


<asp:ObjectDataSource ID="odsGrid" runat="server" OldValuesParameterFormatString="original_{0}"
                        SelectMethod="SelectAllForGrid" TypeName="WellFood.Business.Managers.BrandTypeManager"
                        SortParameterName="Sortby">
                        <SelectParameters>
                            <asp:Parameter Name="SearchExpression" Type="String" />
                        </SelectParameters>
                    </asp:ObjectDataSource>





[DataObjectMethod(DataObjectMethodType.Select)]
        public List<BrandType> SelectAllForGrid(string SearchExpression, string Sortby)
        {
            if (string.IsNullOrEmpty(Sortby))
                Sortby = "PrdID";

            Query = @"SELECT ROW_NUMBER() OVER(ORDER BY   " + Sortby + @" ) as RowNum,
                    CBTID ,BTID ,BTName ,PrdID ,
                    PrdName ,GroupID ,GroupName ,FloorID ,VATPrcnt ,DiscPrcnt
                    FROM [BrandType]
                    order by RowNum";
            oR = sQLDal.Select(Query);
            List<BrandType> oList = new List<BrandType>();
            if (oR.ResultState && oR.Data.Rows.Count > 0)
            {
                oList = DataTableToClass.DataTableToList<BrandType>(oR.Data);
                return oList;
            }
            else return null;
        }

Entity Framework Connection Use As SqlConnection

Thursday, November 13, 2014 Category : , 0

        public static string GetConnectionString()
        {
            string entityConnectionString = ConfigurationManager.ConnectionStrings["ERPEntities"].ConnectionString;
            string providerConnectionString = new EntityConnectionStringBuilder(entityConnectionString).ProviderConnectionString;
            return providerConnectionString;
        }

C# DataTable to List Convert

Wednesday, November 12, 2014 Category : , 0


public static List DataTableToList(this DataTable table) where T : class, new()

        {
           try
            {
                List list = new List();
                foreach (var row in table.AsEnumerable())
               {
                    T obj = new T();
                    foreach (var prop in obj.GetType().GetProperties())
                    {
                        try
                        {
                            PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);

                            propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);

                        }
                        catch
                        {
                            continue;
                        }
                    }
                    list.Add(obj);
                }
                return list;
            }
            catch
            {
                return null;
            }
        }

ASP.net dropdown with searching textbox

Tuesday, September 30, 2014 Category : 0

    <link href="~/js/chosen.css" rel="stylesheet" type="text/css" runat="server" />
    <script src="<%#ResolveUrl("~") %>js/chosen.jquery.js" type="text/javascript"></script>



<asp:DropDownList ID="ddlAssignGroup" class="form-control"
     CssClass="chosen-select" Width="157px" runat="server">
</asp:DropDownList>


  <script type="text/javascript">

        var config = {
            '.chosen-select': {},
        }
        for (var selector in config) {
            $(selector).chosen(config[selector]);
        }
      </script>


Out put







at this point. everything is ok. but when this page is postback then this option is gone.
then i have find a solution by using this javascript code.

    <script type="text/javascript">
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_endRequest(function (s, e) {
            var config = {
                '.chosen-select': {},
            }
            for (var selector in config) {
                $(selector).chosen(config[selector]);
            }
        });
    </script>


this code actually fire when a post back occurs.

Jquery and css link
https://docs.google.com/file/d/0B2qzKDIYFsGgWFZHMFRDNU50SDg/edit

Silver light Comon Operation Syntext

Thursday, September 4, 2014 Category : 0

Datagrid  Date column format : 
<sdk:DataGridTextColumn Header="From" IsReadOnly="True"
                                                Binding="{Binding FromDate, StringFormat='{}{0:MM/dd/yyyy}'}" Width="auto"/>


<sdk:DataGridTextColumn Header="Discharge Date"
                                                Binding="{Binding DischargeDate, StringFormat='{}{0:MM/dd/yyyy a\\t h:mm tt}'}"/>
                        

Silverlight : The remote server returned an error: NotFound [Solution]

Tuesday, August 5, 2014 Category : , 0

System.Net.WebException: The remote server returned an error: NotFound

 

 

 

There are two places you have to edit:
1. edit the ServiceReferences.ClientConfig to accept a large buffer.
 <binding name="BasicHttpBinding_MosaicService" maxBufferSize="2147483647"
                    maxReceivedMessageSize="2147483647"> 
2. on the server in the web.config
 <system.serviceModel>
add a Httpbinding and name it
<bindings>
     <basicHttpBinding>
       <binding name="ServicesBinding" maxReceivedMessageSize="2000000" maxBufferSize="2000000">
         <readerQuotas maxArrayLength="2000000" maxStringContentLength="2000000"/>
    </binding>

which setts it to 2MB and  tell the service to use this binding
 <system.serviceModel>
    <services>
         <service behaviorConfiguration="TekPlayground.MosaicServiceBehavior"
    name="TekPlayground.MosaicService">
    <endpoint address="" binding="basicHttpBinding" bindingConfiguration="ServicesBinding" contract="TekPlayground.MosaicService" />
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
   </service>

 

Powered by Blogger.