CodeSmith Community
Your Code. Your Way. Faster!

ServiceLayer Usage Example w/ SecurityContext

Latest post 10-04-2007 9:46 AM by nokas. 29 replies.
  • 06-01-2006 11:29 PM In reply to

    Re: ServiceLayer Usage Example w/ SecurityContext

    I agree that there should be some events firing in the DAL that would allow you to touch things internally without having to dig into the DAL.

    I'll look at adding that this weekend.

    I'm unsure as to how else you would handle that scenario.  Fire an event, and let the dev decide to rollback or not?

    it's irresponsible to leave that table blocked, if the query already failed so that's why we did it that way the first go around.  But I do see your point, got any suggestions?


    Robert Hinojosa
    -------------------------------------
    Member of the Codesmith Tools, .netTiers, teams
    http://www.nettiers.com
    -------------------------------------
    • Post Points: 45
  • 06-02-2006 12:12 AM In reply to

    • MrBretticus
    • Top 75 Contributor
    • Joined on 02-10-2006
    • Perth, Australia
    • Posts 54
    • Points 1,360

    Re: ServiceLayer Usage Example w/ SecurityContext

    Yes I agree that is the safest way by default which is fair enough. The transaction exception that I get is "This SqlTransaction has completed; it is no longer usable." I have made sure that I'm not "completing" the transaction myself anywhere, so I think the problem (and I could very well be wrong) is because the transaction has been opened by never used when the .RollBack is called.

    As far as suggestions, if I think of one I'll let you know, but as just a thought could the TransactionManager cater for the situation above?
    Cheers, Brett "Most human beings have an almost infinite capacity for taking things for granted." - Aldous Huxley
    • Post Points: 35
  • 06-02-2006 1:43 AM In reply to

    • bdiaz
    • Top 10 Contributor
    • Joined on 02-20-2006
    • Houston, TX
    • Posts 504
    • Points 15,290

    Re: ServiceLayer Usage Example w/ SecurityContext

    The transaction exceptions were caused by a bug in the BeginTransaction method.  It has been fixed in SVN  rev 204.

    Bobby Diaz ------------------------------------------ Member of the .NetTiers team http://www.nettiers.com ------------------------------------------
    • Post Points: 5
  • 06-05-2006 12:29 AM In reply to

    Re: ServiceLayer Usage Example w/ SecurityContext

    mrizaullah,

    Here's a quick InventoryProcessor sample class.

        public class InventoryProcessor : ProcessorBase
    {
    private Entities.Orders order;
    private GenericProcessorResult genericProcessorResult;

    /// <summary> /// Inventory Processor /// </summary> /// <param name="order"></param> public InventoryProcessor(Entities.Orders order)
    {
    this.order = order;
    }

    /// <summary> /// Process the IProcessResult /// </summary> /// <returns></returns> public override IProcessorResult Process()
    {
    try { order.AddInventoryRules(); //check stock order.Validate();

    if (!order.IsValid)
    ProcessResult.AddBrokenRulesList(typeof (Entities.Orders), order.BrokenRulesList);
    }
    catch(Exception exc)
    {
    if (DomainUtil.HandleException(exc, "NoneExceptionPolicy"))
    throw;
    }

    return ProcessResult;
    }

    /// <summary> /// ProcessResult /// </summary> public override IProcessorResult ProcessResult
    {
    get { if (genericProcessorResult == null)
    {
    genericProcessorResult = new GenericProcessorResult();

    }
    return genericProcessorResult;
    }
    }

    Custom Business Rule in Orders.cs
        /// <summary>
        /// Add Extra Custom Validation Rules
        /// </summary>
        public void AddInventoryRules()
    {
    ValidationRules.AddRule(InventoryRuleCheck, new ValidationRuleArgs("UnitsInStock"));
    }

    /// <summary> /// Check Inventory /// </summary> /// <param name="target"></param> /// <param name="e"></param> /// <returns></returns> public bool InventoryRuleCheck(object target, ValidationRuleArgs e)
    {
    foreach(OrderDetails detail in OrderDetailsCollection)
    {
    if (detail.ProductIDSource == null)
    continue;

    if (detail.ProductIDSource.UnitsInStock < detail.Quantity)
    {
    e.Description = string.Format("{0} - is out of stock, {1} units are on order.",
    detail.ProductIDSource.ProductName, detail.ProductIDSource.UnitsOnOrder);
    return false;
    }
    }
    return true;
    }


    Program.cs
    using System;
    using System.Collections.Generic;
    using System.Text;
    using Northwind.Entities;
    using Northwind.Entities.Validation;
    using Northwind.Services;
    using Northwind.Services.Processors.Orders;

    namespace NorthwindWebConsole
    {
    class Program
    {
    static void Main(string[] args)
    {
    //create a fake order
    OrdersService service = new OrdersService();
    Orders o = new Orders();
    ProductsService products = new ProductsService();
    TList<Products> plist = products.GetAll();

    for(int j=0;j<10;j++)
    {
    OrderDetails detail = new OrderDetails();
    detail.ProductID = plist[j].ProductID;
    detail.ProductIDSource = plist[j];
    detail.Quantity = Convert.ToInt16(j * j);
    o.OrderDetailsCollection.Add(detail);
    }

    service.ProcessorList.Add(new InventoryProcessor(o));
    ServiceResult result = service.Execute();
    if (result.HasErrors)
    Console.WriteLine(result.Error);


    Console.ReadLine();
    }
    }
    }

    Robert Hinojosa
    -------------------------------------
    Member of the Codesmith Tools, .netTiers, teams
    http://www.nettiers.com
    -------------------------------------
    • Post Points: 60
  • 06-05-2006 9:35 AM In reply to

    Re: ServiceLayer Usage Example w/ SecurityContext

    Thanks Robert. It is very helpful.
    • Post Points: 5
  • 06-10-2006 8:42 PM In reply to

    Re: ServiceLayer Usage Example w/ SecurityContext

    I have noticed that there is no code generated for BLL (Service Layer) objects for Views. Shouldn't it be there?

    What is your idea on this?

    Thanks

    • Post Points: 5
  • 06-26-2006 6:39 PM In reply to

    Re: ServiceLayer Usage Example w/ SecurityContext

    I appriciate the hard work of NetTiers team. Excellent job.

    Since I did not hear anything on View objects in Service Layer from the forum, I thought I could just add templates my self. I am able to generate code for View objects but I am getting compilation errors on EntityKey. As the EntityKey is generated only for Tables (not Views).

    Do I need to create separate base, basecore and IEntityProvider classes without EntityKey object for views as well?

    Any suggestion?

    • Post Points: 35
  • 06-26-2006 11:02 PM In reply to

    Re: ServiceLayer Usage Example w/ SecurityContext

    The views should implement IEntityViewProvider and not IEntityProvider, so it should be much easier.  Mind sharing those template when you're done?

    Robert Hinojosa
    -------------------------------------
    Member of the Codesmith Tools, .netTiers, teams
    http://www.nettiers.com
    -------------------------------------
    • Post Points: 35
  • 06-28-2006 9:05 PM In reply to

    Big Smile [:D] Re: ServiceLayer Usage Example w/ SecurityContext

    Happily!

     

    Please find the attached zip file which contains a “Views” folder and “NetTiers.cst” file.

    Readme.txt is also included for additional help.

     

    Note: SecurityContext is disabled because Entity objects based on views do not implement IEntity interface.

     

    Code generated by these templates does not have compile error. But no guarantees or warranties what so ever.Smile [:)]. It passed my basic test cases.

     

    It would be nice if the common methods in both table based and view based Entities, like Get, GetAll, GetPaged and Find are synchronized in method signature and implementation. That includes sqlClient as well. I wouldn't mind volunteering.

    Please give your feedback. Report any issues. I will be happy to fix them.

     

    • Post Points: 35
  • 07-19-2006 9:02 AM In reply to

    • tomek
    • Top 100 Contributor
    • Joined on 04-20-2006
    • Posts 47
    • Points 1,370

    Re: ServiceLayer Usage Example w/ SecurityContext

    I am just curious is this has been or is planned to be implemented. It would be really nice to have service support for views. thanks tom
    • Post Points: 35
  • 07-20-2006 11:26 PM In reply to

    Re: ServiceLayer Usage Example w/ SecurityContext

    Post 14938 has the attachment of the files needed. It has a Reame.txt file which explains how to you could integrate these (Svc for Views) file. It is very simple. I am currently using it without any issues.

    • Post Points: 35
  • 07-21-2006 12:37 AM In reply to

    Re: ServiceLayer Usage Example w/ SecurityContext

    This patch was applied to the code yesterday.

    Robert Hinojosa
    -------------------------------------
    Member of the Codesmith Tools, .netTiers, teams
    http://www.nettiers.com
    -------------------------------------
    • Post Points: 5
  • 12-14-2006 5:20 PM In reply to

    Re: ServiceLayer Usage Example w/ SecurityContext

    I can't seem to get this working using the config sections above. My web.config file is below. I'm using the 12/15 nightly build of 2.0. I have an entity called Building and I'm calling an insert like this:

                 Building b = new Building();
                b.BuildingName = "test";
                BuildingService bs = new BuildingService();
                bs.Insert(b);

    I'm getting an exception when it tries to get the RuleProvider in SecurityContext.cs on line 100:

                                "ruleProvider = AuthorizationFactory.GetAuthorizationProvider(ruleProviderKey);"

    The exception that is passed back to the IsAuthorized method says " _COMPlusExceptionCode = -532459699 ".

     Very strange.  Any ideas or better code samples for Method authorization and the web.config configuration sections??

    Thanks!!

    Anne

     

    -------------web.config--------------

    <?xml version="1.0"?>

    <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
      <configSections>
        <section name="netTiersService" type="RR.DataAccessLayer.Bases.NetTiersServiceSection, RR.DataAccessLayer" allowDefinition="MachineToApplication" restartOnExternalChanges="true" />
        <section name="securityConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Security.Configuration.SecuritySettings, Microsoft.Practices.EnterpriseLibrary.Security, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />
        <section name="securityCryptographyConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.Configuration.CryptographySettings, Microsoft.Practices.EnterpriseLibrary.Security.Cryptography, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />
      </configSections>

      <appSettings>
       
      </appSettings>

        <connectionStrings>
          <add name="ConnectionString" connectionString="{stringhere}" />
        </connectionStrings>
     
        <location path="admin">
            <system.web>
              <authorization>
                <deny users="?" />
              </authorization>
            </system.web>
          </location>
     
        <system.web>
         
            <compilation debug="true" />

          <authentication mode="Forms">
            <forms loginUrl="Login.aspx"
                   protection="All"
                   timeout="30"
                   name="Cookie"
                   path="/"
                   requireSSL="false"
                   slidingExpiration="true"
                   defaultUrl="admin/default.aspx"
                   cookieless="UseCookies"
                   enableCrossAppRedirects="false" />
          </authentication>

          <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
            <providers>
              <clear />
              <add
                name="SqlProvider"
                type="System.Web.Security.SqlMembershipProvider"
                connectionStringName="ConnectionString"
                applicationName="RR"
                enablePasswordRetrieval="true"
                enablePasswordReset="true"
                requiresQuestionAndAnswer="false"
                requiresUniqueEmail="false"
                passwordFormat="Clear"
                minRequiredPasswordLength="6"
                minRequiredNonalphanumericCharacters="0"
           />
            </providers>
          </membership>

          <roleManager defaultProvider="SqlRoleProvider" enabled="true">
            <providers>
              <clear/>
              <add name="SqlRoleProvider" connectionStringName="ConnectionString"
                applicationName="EAGM"
                type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
            </providers>
          </roleManager>
         
        </system.web>

      <netTiersService defaultProvider="SqlNetTiersProvider">
        <providers>

          <add
        name="SqlNetTiersProvider"
        type="RR.DataAccessLayer.SqlClient.SqlNetTiersProvider, RR.DataAccessLayer.SqlClient"
        connectionStringName="ConnectionString"
        providerInvariantName="System.Data.SqlClient"
        entityFactoryType="RR.EntitiesLayer.EntityFactory"
        useEntityFactory="true"
        enableEntityTracking="true"
        enableMethodAuthorization="true"
        useStoredProcedure="false"
      />

        </providers>
      </netTiersService>
     
      <securityConfiguration defaultAuthorizationInstance="netTiersRuleProvider"
        defaultSecurityCacheInstance="Caching Store Provider">
          <authorizationProviders>
            <add
              type="Microsoft.Practices.EnterpriseLibrary.Security.AuthorizationRuleProvider, Microsoft.Practices.EnterpriseLibrary.Security, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
              name="netTiersRuleProvider">
              <rules>
                <add name="Building.Insert" expression="((R:WebsiteAdmins))"  />
                </rules>
            </add>
          </authorizationProviders>
        <securityCacheProviders>
          <add cacheManagerInstanceName="Cache Manager" defaultSlidingSessionExpirationInMinutes="10"
            defaultAbsoluteSessionExpirationInMinutes="60"
            type="Microsoft.Practices.EnterpriseLibrary.Security.Cache.CachingStore.CachingStoreProvider, Microsoft.Practices.EnterpriseLibrary.Security.Cache.CachingStore, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
            name="Caching Store Provider" />
        </securityCacheProviders>
        </securityConfiguration>
     
    </configuration>


     

    • Post Points: 35
  • 12-15-2006 1:47 PM In reply to

    Re: ServiceLayer Usage Example w/ SecurityContext

    That exception is very strange.  There's no more information that you can provide?  Have you tried using the generated config that we generate just to test?

    Robert Hinojosa
    -------------------------------------
    Member of the Codesmith Tools, .netTiers, teams
    http://www.nettiers.com
    -------------------------------------
    • Post Points: 35
  • 10-04-2007 9:46 AM In reply to

    • nokas
    • Not Ranked
    • Joined on 09-28-2006
    • Posts 2
    • Points 10

    Re: ServiceLayer Usage Example w/ SecurityContext

    Hi,

    I have some doubts about the usage of ServiceLayer. My principal question is why is it a _static_ member of service layer classes.

    I was using SecurityContext.Identity.Name to perform audit logs, but it was getting something wrong, the .Name sometimes wasn't the same as the user authenticated on the interface, and yet, different from System.Threading.Thread.CurrentPrincipal.Identity.Name.

     I'm using Windows Authentication mode on IIS.

    Since I deleted "static", it all worked fine. 

    • Post Points: 5
Page 2 of 2 (30 items) < Previous 1 2 | RSS
Copyright © 2008 CodeSmith Tools, LLC
Powered by Community Server (Commercial Edition), by Telligent Systems