Monday, June 30, 2014

JSON - JavaScript Object Notation

Combination of Showing MessageBox and select yes to backend.
  
JSON - Mostly use when UI to Backend
  <script type="text/javascript">
        function RedirectToEdit(userID) {
            $.ajax({
                type: "post",
                url: "Client.aspx/RedirectToEdit",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: '{"userID":"' + userID + '"}',
                success: function (result) {
                    window.parent.location.href = "Client.aspx?action=edit";
                },
                error: function (xhr, status, error) {
                    alert("Failed to go Edit Page.")
                }
            });
        }

JAVASCRIPT
        function DisplayClient() {
            var x = confirm('This User ID already exist. Press "Ok" to Edit Page.');
            if (x == true) {
                $('INPUT[id*=btnRedirectEdit]').click();
                var userID = $('INPUT[id*=txtUserID]').val();
                RedirectToEdit(userID);
            }
        }

    </script>


C# Backend
[System.Web.Services.WebMethod]
public static bool RedirectToEdit(string userID)
{
            ClientController clientController = new ClientController();
            UserSession upc = new UserSession();

            upc.SessionSelectedClientID = userID;
            upc.SessionSelectedModID = "*Client.aspx?action=edit";
            return true;
}

Wednesday, June 18, 2014

Way to Catch Exception ( Custom Exception)

OVERALL EXCEPTION 

Data Access Layer : Catch and Log 

catch (Exception ex)
{
  CommonLogger logger = new CommonLogger();
  logger.LogError(ExceptionType.DACException, ex);

   throw new DBException(SQL_STATEMENT, country.CountryID.ToString(), ex);
   //or
   throw new DBException(SQL_STATEMENT, "", ex);
}

Business Layer : No log and Catch (you can throw Exception, but better throw custom exception or application exception)

Service Layer : Catch, log and form fault exception(if want to catch business layer exception, you want to catch another 1)

//Normal Exception
catch (Exception ex)
{
  string message = "Error retrieving Country. " +
((ex.GetType() == typeof(DBException)) ? "Unable to retrieve data from database.": "An exception occurred.");

   CommonLogger logger = new CommonLogger();
   logger.LogError(ExceptionType.Country, ex);

   PYFault fault = new PYFault(message);
   throw new FaultException<PYFault>(fault, message);
}

//Custom Exception
catch (PYException vex)
{
  PYResultFault fault = new PYResultFault(vex.Message, vex.PYResults);
  throw new FaultException<PYResultFault>(fault);
}

HOW TO CREATE FAULT EXCEPTION

[DataContract]
public class PYResultFault
{
      [DataMember]
      public List<PYResult> PYResults { get; set; }

      [DataMember]
      public string Message { get; set; }

       public PYResultFault(string message, List<PYResult> pyResults)
       {
            this.Message = message;
            this. PYResults = pyResults;
       }
}

Controller Layer : Catch (you can throw Exception, but better throw custom exception or application exception)**Can use back the Custom Exception

catch (FaultException<PYFault> fex)   
{
  throw new PYException(fex.Detail.Message, fex);
}
catch (FaultException<PYResultFault> fex)
{
   throw new PYException(fex.Detail.Message, fex.Detail.PYResults); 
}
catch (Exception ex) //Catch Connection Error
{
  throw new Exception(ex.Message);
}

Presentation Layer : Catch and Log Presentation Error

catch (PYException validateEx)
{
  StringBuilder sbrError = new StringBuilder();
  sbrError.Append(validateEx.Message);
  
  if (validateEx.PYResults != null)
  {
     sbrError.Append(": <br />");

     foreach (var result in validateEx. PYResults)
     {
       sbrError.Append(result.Message + "<br />");
     }
  }
    ModelState.AddModelError("Error", sbrError.ToString());
}
catch (Exception ex)
{
     CommonLogger logger = new CommonLogger();
     logger.LogError(ExceptionType.CountryManagement, ex);
    
     ModelState.AddModelError("Error",ConfigurationManager.AppSettings.Get("generalErr"));
}

WHEN NEED USE THIS METHOD TO CATCH EXCEPTION
when the an exception form at Business Layer with a list of information need to show.

This method is included custom and fault exception.
Custom Exception used when form a list of exception.
Fault exception used when to Transfer whole exception from WCF.

Tuesday, June 17, 2014

Create Custom Exception

Create Custom exception
public class PYException : Exception
{
 public List<PYResult> PYResults { getset;}  //attribute

 public PYException() { }  // Default Constroctor

 public PYException(string message) : base(message) { } //like Application Exception

public PYException(string message, List<PYResult> pyResults): base(message)
        {
          this.PYResults = pyResults;
        }  //Application Exception with A List of Info , message usually is header.

 public PYException(string message, Exception inner) : base(message, inner) { }

 public PYException(string message, List<PYResult> pyResults, Exception inner)
        : base(message, inner)
        {
            this.ValidationResults = validationResults;
        }
}

Create exception class

[DataContract]
public class PYResult
{
  [DataMember]
  public ComponentsType ComponentType { get; set; }

  [DataMember]
  public string key { get; set; }

  [DataMember]
  public string Message { get; set; }
}


HOW TO THROW THIS ?

Use IF ELSE statement to create a exception class.

List<PYResult> pyResults = new List<PYResult>();

pyResults.Add(new PYResult ()
{
Message = String.Format("The Country cannot be selected for {0}. The country .",country.CountryName),
  key = CountryID.ToString(),
  ComponentType = PYComponentsType.Country
});


Use count to throw the exception

if (pyResults.Count() > 0)
  throw new PYException ("Updating errors. Please see the error detail",pyResults);

Monday, June 9, 2014

XML ENTITIES

[DataMember]        
[XmlAttribute
[Browsable(false)]            //Not Display
[Category("Mandatory")]      // Must Display
[DisplayName("Code")]        // Display Name
public int CodeID { getset; }