6 Replies Latest reply on Aug 25, 2010 6:05 AM by BhaskerChari

    Help me in completing my First Cairngorm Login Example .

    kiran7881 Level 1

      Hi ,

       

      Still i am fearing to do an Application using Cairngorm . Please help

       

      This will be my ROugh  sketch of my Caringorm Application .

       

      This will is a LoginExample where on a successful login will display as WELCOME or else INVALID LOGIN in case of a incorrect login .

      Please go through my code :

       

      This is my Main mxml file


      <?xml version="1.0" encoding="utf-8"?>
      <mx:Application xmlns:controller="uk.co.clockobj.cairngormdemo.controller.*">
          <controller:AppController/>
      <mx:Script>

      var user:UserDTO = new UserDTO();
      public function login():void
      {
      user.username  = UNAMETI.text;
      user.password = PASSTI.text;
      systemManager.dispatchEvent(LoginEvent.LOG_USER_IN,user );

      }
      </mx:Script>
      </mx:Application>

       

      This is my UserDTO Object :

      package dto
      {
          [Bindable]
          [RemoteClass(alias="namespace.to.some.server.dto")]
          public class UserDTO
          {
              public var username : String;
              public var password : String;
             
              public function UserDTO()
              {
              }
          }
      }

       

      This is my controller class :

       

      package controller
      {
          public class AppController extends FrontController
          {
              public function AppController()
              {
                  super();
                  initialiseCommands();
              }
             
              private function initialiseCommands() : void
              {
                  addCommand(LOG_USER_IN, LogUserInCommand);
          }
          }
      }

       

      This is my Event class :

       

      package events
      {
          import com.adobe.cairngorm.control.CairngormEvent;

       

          public class LoginEvent extends CairngormEvent
          {

       

      public static const var LOG_USER_IN:String = "LOG_USER_IN";
             
              public var user: UserDTO
                     
              public function LoginEvent(type:String,user:UserDTO,bubbles:Boolean=false, cancelable:Boolean=false)
              {
                  super(type, bubbles, cancelable);
                 
                  this.user = UserDTO;
              }
             
          }
      }

       

      This is my Command class :

       

      package commands
      {
          public class LogUserInCommand implements  ICommand, IResponder
          {

      Service myremoteservice;
              public function LogUserInCommand()
              {        
              }

              override public function execute(event:CairngormEvent):void
              {
                 
      myremoteservice = ServiceLocator.getInstance().getRemoteObject( 'docsServices' );
              }
             
              public function result(data:Object):void
              {
                 

      ModelLocator.getInstance().welcome = ResultEvent( data ).result;

              }
             
              public function fault(info:Object):void
              {

      ModelLocator.getInstance().invalid = FaultEvent( data ).result;


              }
             
          }
      }

       

      This is my ModelLocator class :

       

      package model
      {    [Bindable]
          public class ModelLocator implements IModelLocator
          {
              private static var _instance:ModelLocator;
             
              public static function getInstance():ModelLocator {
                  if (_instance == null) {
                      _instance = new ModelLocator();
                  }
                  return _instance;
              }
             
              public function ModelLocator()
              {
                  if ( _instance != null )
                  {
                      throw( new Error( "Singleton class has already been instantiated" ) );
                  } else
                  {
                      session = new SessionModel();
                  }
              }
             
             
      public var user : UserDTO

       

      public var welcome : String;
      public var invalid : String;

       

          }
      }


      I have my services.mxml file defined in connection to my java file :


      <mx:RemoteObject
          id="docsServices"
          destination="ToRemote"
          source="cairngormcf.com.cf.CairngormJava">
      </mx:RemoteObject>

       

       

      my queries with respect to above code are :

       

      1. How can i call the FrontController from my login function of the Main Application under the Form COntainer .

       

      2. After dispatching the Event from my login function, who should listen to this Event .(How do it here)

       

      3.
      3. After getting the User DTO details into my Java Layer , i will validate the Data and  I am sending a String either Valid Login or Invalid Login as String , here how does my Main Application get this data ??

       

       

      Please help me in all these things , really it will be a great help .

       

      expecting replies from experts

       

      Thank you very much for reading long code .

        • 1. Re: Help me in completing my First Cairngorm Login Example .
          betheflexcoder Level 2

          1. How can i call the FrontController from my login function of the Main Application under the Form COntainer . - The front controller will be initialzed when once you run your main applciation by this code which you have written :   <controller:AppController/>

           

          2. After dispatching the Event from my login function, who should listen to this Event .(How do it here)

           

          Your command LogUserInCommand will listen to this event. and the exceute method in the command should do your job of calling the remote object method or call the delegate which inturn calls the remote object method.

           


          3. After getting the User DTO details into my Java Layer , i will validate the Data and  I am sending a String either Valid Login or Invalid Login as String , here how does my Main Application get this data ?? your java method which gets the DTO details and validates it should return a String which you can recieve it in the result method of your command.

          i.e;

          public function result(data:Object):void
            {

          var resultObj:ResultEvent = ResultEvent ( data)

          var status:String = resultObj.result as String;

          //here update your modelLocator's required variable with this string

          }

           

           

          By the way, where are you calling you login function?

          • 2. Re: Help me in completing my First Cairngorm Login Example .
            flex4 Level 2

            Hi Kiran

             

               What is the necessity of dispatching the event through SystemManager class.. U have create custom event by extending CairgormEvent.i.e

             

                         public class LoginEvent extends CairngormEvent...        so you need to dispatch that event through

             

             

                                          CairngormEventDispatcher.getInstance.dispatch(loginEvent);

             

             

                          and in the application u need to import the frontcontroller and servicelocator ,,, then only front controller will listen ur custom event...

             

             

                                          so try this .. if u face some difficulty let me know and if u want i will post u the login code also if u dont mind

            • 3. Re: Help me in completing my First Cairngorm Login Example .
              kiran7881 Level 1

              .. .. if u face some difficulty let me know and if u want i will post u the login code also if u dont mind

               

              That will be  a great help , for me . If you dont mind can you please post the code .

              • 4. Re: Help me in completing my First Cairngorm Login Example .
                flex4 Level 2

                Hi Kiran this is ur stuff place class as mentioned in the classes below as it is

                 

                        or if u can change it ur self   Here i am using custom component and i am importing that custom component to application...  so use custom component to send cairngorm event..

                 

                                    the best practice is to create a view part and then import that view into ur application and that will reduce ur application file size and download file size .. so if u have any problem using this code let me know

                 

                 

                 

                 

                business
                ------------
                1.MyServices
                ------------
                <?xml version="1.0" encoding="utf-8"?>
                <cairngorm:ServiceLocator xmlns:mx="http://www.adobe.com/2006/mxml"
                   
                    xmlns:cairngorm="com.adobe.cairngorm.business.*">
                   
                    <!-- Declare your service objects here -->
                    <mx:RemoteObject
                        destination="user"
                        id="userRO">
                    </mx:RemoteObject>   
                   
                   
                </cairngorm:ServiceLocator>

                 

                2.UserDelegate
                --------------
                package business
                {
                    import com.adobe.cairngorm.business.ServiceLocator;
                   
                    import mx.rpc.AsyncToken;
                    import mx.rpc.IResponder;
                    import mx.rpc.remoting.RemoteObject;
                   
                    import vo.UserVO;
                   
                    public class UserDelegate
                    {
                       
                        public var myServices:ServiceLocator;
                       
                        public function UserDelegate()
                        {
                            //TODO: implement function
                            myServices = ServiceLocator.getInstance();
                           
                        }
                       
                        //create a function to communicate with server here

                 

                        public function validateUser(userObj:UserVO,responder:IResponder):void{
                           
                            //retrieve the service you want to
                            //communicate from the servicelocator
                           
                            var userRO:RemoteObject = myServices.getRemoteObject("userRO");           
                            var resMsg:AsyncToken = userRO.validateUser(userObj);
                           
                            //attach the responder
                           
                            resMsg.addResponder(responder);
                           
                           
                        }

                 

                    }
                }

                 

                LoginCommand
                ------------
                package commands
                {
                    import business.UserDelegate;
                   
                    import com.adobe.cairngorm.commands.ICommand;
                    import com.adobe.cairngorm.control.CairngormEvent;
                   
                    import events.LoginEvent;
                   
                    import model.MyModelLocator;
                   
                    import mx.controls.Alert;
                    import mx.rpc.IResponder;
                    import mx.rpc.events.ResultEvent;
                   
                    import vo.UserVO;

                 

                    public class LoginCommand implements ICommand,IResponder
                    {
                        public var myModel:MyModelLocator;
                        public var userDelegate:UserDelegate;
                       
                        public function LoginCommand()
                        {
                            //TODO: implement function
                            //use this to manipulate data in the
                            //model
                           
                            myModel = MyModelLocator.getInstace();
                        }

                 

                        public function execute(event:CairngormEvent):void
                        {
                            //TODO: implement function
                            //we will do our business logic here
                           
                            var loginEvent:LoginEvent = event as LoginEvent;
                            var userObj:UserVO = loginEvent.userDtl;
                           
                            /*if(userObj.userName=="naresh@naresh.com" &&
                                    userObj.password=="naresh"){
                                //do something
                                myModel.userDtl = userObj;
                                myModel.APP_STATE="login";
                               
                            }else{
                                //do something else
                                Alert.show("Login Failed");
                            }*/
                           
                            //create the instace of the user delegate
                           
                            userDelegate = new UserDelegate();
                            userDelegate.validateUser(userObj,this);
                            
                        }
                       
                        public function result(event:Object):void{
                           
                            var resultEvent:ResultEvent = event as ResultEvent;
                           
                            if(resultEvent.result!=null){

                 

                             myModel.userDtl = resultEvent.result as UserVO;
                             myModel.APP_STATE="login";
                            
                            }else{
                               
                                Alert.show("Login Failed");           
                            }
                           
                        }
                       
                        public function fault(event:Object):void{
                           
                        }
                       
                       
                    }
                }

                 


                LoginPanel
                ----------
                <?xml version="1.0" encoding="utf-8"?>
                <mx:Panel
                    xmlns:mx="http://www.adobe.com/2006/mxml"
                    title="Login Here">
                   
                    <mx:Script>
                        <![CDATA[
                            import events.LoginEvent;
                            import vo.UserVO;
                            import model.MyModelLocator;
                            import mx.events.ValidationResultEvent;
                           
                            public function loginUser(event:MouseEvent):void{
                               
                            var emailValEvnt:ValidationResultEvent   
                                            = emailVal.validate();
                            var pswdValEvnt:ValidationResultEvent
                                            =pswdVal.validate();
                                           
                                if(emailValEvnt.type==ValidationResultEvent.VALID
                                            && pswdValEvnt.type==ValidationResultEvent.VALID){
                                   
                                    //as the validation is done
                                    //communicate the data to the server
                                   
                                    //the instace of the value object
                                    var userObj:UserVO = new UserVO();
                                    userObj.userName = userNameTI.text;
                                    userObj.password = passwordTI.text;
                                   
                                    var loginEvent:LoginEvent =
                                            new LoginEvent(LoginEvent.LOGIN_EVENT,userObj);
                                    //dispatch the event                    
                                   // loginEvent.dispatch();       

                                    CairngormEventDispatcher.getInstance.dispatch(loginEvent);  //Import CairngormEventDispathcer from com.adobe.cairgorm.CairngormEventDispatcher
                                }else{
                                    //show the error message
                                    this.errorString="Pleae Enter Valid Details";
                                }           
                               
                            }
                           
                        ]]>
                    </mx:Script>
                   
                <mx:EmailValidator
                    source="{userNameTI}"
                    property="text"
                    id="emailVal"
                    required="true"
                    triggerEvent=""
                    />

                 

                <mx:StringValidator
                    source="{passwordTI}"
                    id="pswdVal"
                    maxLength="16"
                    minLength="6"
                    property="text"
                    triggerEvent=""
                    />   

                 

                   
                    <mx:Form>
                        <mx:FormItem label="User Name" required="true">
                        <mx:TextInput id="userNameTI"/>   
                        </mx:FormItem>
                        <mx:FormItem label="Password" required="true">
                        <mx:TextInput id="passwordTI" displayAsPassword="true"/>   
                        </mx:FormItem>
                    </mx:Form>   
                    <mx:ControlBar>
                        <mx:Button label="Login" click="loginUser(event)"/>
                    </mx:ControlBar>
                   
                </mx:Panel>

                 

                MyFrontController
                -----------------
                package controller
                {
                    import com.adobe.cairngorm.control.FrontController;
                   
                    import events.LoginEvent;
                    import commands.LoginCommand;

                 

                    public class MyFrontController extends FrontController
                    {
                        public function MyFrontController()
                        {
                            super();
                            addCommand(LoginEvent.LOGIN_EVENT,LoginCommand);
                           
                        }
                       
                    }
                }

                 


                LoginEvent
                -----------
                package events
                {
                    import com.adobe.cairngorm.control.CairngormEvent;
                   
                    import flash.events.Event;
                   
                    import vo.UserVO;

                 

                    public class LoginEvent extends CairngormEvent
                    {
                        public static const LOGIN_EVENT:String= "loginEvent";
                        
                        public var userDtl:UserVO;
                       
                        public function LoginEvent(type:String,userObj:UserVO)
                        {
                            //TODO: implement function
                            super(type);
                            this.userDtl = userObj;
                        }
                       
                        override public function clone():Event{
                           
                            return new LoginEvent(type,userDtl);
                        }
                    }
                }

                 


                MyModelLocator
                --------------
                package model
                {
                    import com.adobe.cairngorm.CairngormError;
                    import com.adobe.cairngorm.model.IModelLocator;
                   
                    import vo.UserVO;
                   
                    [Bindable]
                    public class MyModelLocator implements IModelLocator
                    {
                        public static var instance:MyModelLocator;
                       
                        public function MyModelLocator(enforcer:SingletonEnforcer)
                        {
                            //TODO: implement function
                            if(enforcer==null){                           
                               
                                trace("You Can't Create Multiple Instaces of ModelLocator");               
                                throw new CairngormError("Multiple Initialization");
                                               
                            }
                           
                        }
                       
                        static public  function getInstace():MyModelLocator{
                           
                            if(instance==null){
                                //create new instace
                                //return it
                                instance = new MyModelLocator(new SingletonEnforcer());
                                return instance;

                 

                            }else{
                                //return existing instace    
                                return instance;
                            }
                           
                        }
                       
                        //Declare Various Variables here
                        //Just remember to initialize them
                       
                        //contains the user data
                        public var userDtl:UserVO = new UserVO();
                        //control the application state
                        public var APP_STATE:String="";
                       
                    }       
                }
                class SingletonEnforcer{}

                 


                UserVO
                -------
                package vo
                {
                    [Bindable]
                    [RemoteClass(alias="com.test.lcds.vo.UserVO")]
                    public class UserVO
                    {
                        public var userName:String;
                        public var password:String;
                       
                        public function UserVO()
                        {
                        }

                 

                    }
                }

                 

                Cairngorm2
                -----------
                <?xml version="1.0" encoding="utf-8"?>
                <mx:Application
                    xmlns:mx="http://www.adobe.com/2006/mxml"
                    layout="absolute"
                    xmlns:comp="comp.*"
                    xmlns:control="controller.*"
                    xmlns:vo="vo.*"
                    xmlns:business="business.*"
                    initialize="initApp()"
                    currentState="{myModel.APP_STATE}">
                   
                   
                    <!-- Initialize the controller -->
                    <control:MyFrontController id="myControl"/>
                   
                    <!-- Create the instace of the service locator -->
                    <business:MyServices id="servicesObj" />
                   
                    <vo:UserVO id="userObj" />
                    <mx:Script>
                        <![CDATA[
                            import model.MyModelLocator;
                           
                            [Bindable]
                            public var myModel:MyModelLocator;
                           
                            public function initApp():void{
                               
                                myModel = MyModelLocator.getInstace();
                               
                               
                            }
                           
                        ]]>
                    </mx:Script>
                    <mx:states>
                        <mx:State name="login">
                            <mx:SetProperty target="{loginpanel1}" name="visible" value="false"/>
                            <mx:AddChild position="lastChild">
                                <mx:Label x="281" y="200"
                                    text="Congratulation {myModel.userDtl.userName}" fontWeight="bold" fontSize="18"/>
                            </mx:AddChild>
                        </mx:State>
                    </mx:states>
                   
                    <comp:LoginPanel
                        horizontalCenter="0"
                        verticalCenter="0" id="loginpanel1">
                       
                    </comp:LoginPanel>
                   
                </mx:Application>

                 

                 

                Place these classes in relavent pakages ane try it ... u need to implement service locator in delegate pakage along with the UserDelegate class

                • 5. Re: Help me in completing my First Cairngorm Login Example .
                  kiran7881 Level 1

                  flex4 , thanks for the pain , you have taken for helping me .

                   

                  Working with cairngorm has been a night mare for me till now .

                   

                  Thanks once again Mate . Have great time .

                  • 6. Re: Help me in completing my First Cairngorm Login Example .
                    BhaskerChari Level 4

                    Hi Kiran,

                     

                    It will be very easy once you get one screen done say for example the Login Screen which you are working by handling all the events and Service calls.

                     

                    Once you understand the flow I am sure it will become very easy for you...

                     

                    All the very best and Happy Coding!!

                     

                     

                    Thanks,

                    Bhasker