none
add feature in if else cond RRS feed

  • Question

  • I have already develped Web Service project in a working conditon after some time there is a new fetaure add in this project for log the information. here is a pretty and simple code

    string txtCode = string.empty;
    string txtStatus = string.empty;
    if(Session["Name"] == null || Session[Id"] == null)
    {
    txtStatus = "
    Reject";
    txtCode = "
    W101";
    AcceptMethod(param1, param2)
    }

    else if(ClassName.getValue != null)
    {
    txtStatus = "
    Reject";
    txtCode = "
    W102";
    AcceptMethod(param1, param2)
    }

    else if(Session["
    Name"].tostring() != ClassName.getValue)
    {
    txtStatus = "
    Reject";
    txtCode = "
    W103";
    AcceptMethod(param1, param2)
    }

    else if(Session["
    Name"] == "Some Name" || Convert.Toint32(Session[Id"]) >= 0)
    {
    txtStatus
    = "Accept"
    //Further code running
    AcceptMethod(param1, param2)
    }

    Now the change request is that if code succefully comes out from first condition it creates a log in database, same for the second else condition an so on.

    for example

    • Session Check successfully passed
    • Name value not null
    • Session Name and method Name are same

    Further more if the Condition true than it already creates a log in Database with the method name AcceptMethod(param1, param2) which is already developed.

    I need to create a log which is discuss in example i.e. change request with optimization.


    طحہ زبیر احمد Taha Zubair Ahmed http://www.tahazubair.blogspot.com

    • Moved by John Saunders Friday, December 28, 2012 5:35 PM General C# question, even though it's C# in a web service (From:ASMX Web Services and XML Serialization)
    Monday, December 24, 2012 7:03 AM

All replies

  • I'm sorry, but you haven't told us what problem you're having.

    John Saunders
    WCF is Web Services. They are not two separate things.
    Use WCF for All New Web Service Development, instead of legacy ASMX or obsolete WSE
    Use File->New Project to create Web Service Projects

    Monday, December 24, 2012 5:29 PM
  • Top three (03) if else condition checking validation in in four (04) it accepts the condition which is the last if else check.

    I want to log the activity what happens with my validation in that way if it successfully passed from first one it calls a log method, pass from second one it also calls a log method, same for the third and in fourth it get inside the if else condition accept it and Further code running.

    I have approximately 30 if else condition in code.

    If you more queries feel free to ask me

    Thanks


    طحہ زبیر احمد Taha Zubair Ahmed http://www.tahazubair.blogspot.com


    • Edited by Taha Zubair Tuesday, December 25, 2012 8:01 AM
    Tuesday, December 25, 2012 8:00 AM
  • I'm still not sure what you're trying to accomplish.

    Maybe you just want to use the System.Diagnostics.Debug.WriteLine method to trace your logic?


    John Saunders
    WCF is Web Services. They are not two separate things.
    Use WCF for All New Web Service Development, instead of legacy ASMX or obsolete WSE
    Use File->New Project to create Web Service Projects

    Wednesday, December 26, 2012 5:26 PM
  • No problem.

    i would like to explain using code..

    if(Session["Name"] == null || Session[Id"] == null)
    {
    txtStatus = "Reject";
    txtCode = "W101";
    AcceptMethod(param1, param2)
    }
    LogMethod(1);
    else if(ClassName.getValue != null)
    {
    txtStatus = "Reject";
    txtCode = "W102";
    AcceptMethod(param1, param2)
    }
    LogMethod(1);
    else if(Session["Name"].tostring() != ClassName.getValue)
    {
    txtStatus = "Reject";
    txtCode = "W103";
    AcceptMethod(param1, param2)
    }
    LogMethod(1);
    else if(Session["Name"] == "Some Name" || Convert.Toint32(Session[Id"]) >= 0)
    {
    txtStatus = "Accept"
    //Further code running
    AcceptMethod(param1, param2)
    }
    

    I want to call LogMethod(int i); after every successful condition, Hope you understand

    I Know the code is incorrect but i want to do some thing like that, on every successful condition creates a log.


    طحہ زبیر احمد Taha Zubair Ahmed http://www.tahazubair.blogspot.com

    Thursday, December 27, 2012 5:45 AM
  • I see that this is just a general C# question, so I'm moving it to the C# forum.

    John Saunders
    WCF is Web Services. They are not two separate things.
    Use WCF for All New Web Service Development, instead of legacy ASMX or obsolete WSE
    Use File->New Project to create Web Service Projects

    Friday, December 28, 2012 5:35 PM
  • Only one block will execute, if the outer if/else if condition will satisfy. As per your code there have not any option to write into the log file after every successful condition.

    You can't add any statement between "if" and "else if"; i.e. LogMethod(1).

    You should call this method within if/else if block.

    e.g.

    if(CONDITION1){
        //set values into the variable
        //call function to write into the log. i.e. LogMethod(1)
    }else if(CONDITION2){
        //set values into the variable
        //call function to write into the log. i.e. LogMethod(1)
    }else if(CONDITION3){
        //set values into the variable
        //call function to write into the log. i.e. LogMethod(1)
    }

    Friday, December 28, 2012 8:22 PM
  • ...or (if txtStatus and txtCode are used by LogMethod...) only one call to LogMethod at the end of all conditions.

    Classified SR-2 | 2x Xeon W5580 - 3.20 GHz | 12x 2GB Kingston KHX2000C9D3T1K3/6GX | 2x MARS II/2DIS/3GD5 | SAMSUNG 830 MZ-7PC512D/AM 2.5" 512GB SATA III MLC | 4x Spinpoint F3EG HD503HI 500GB 5400 16MB SATA 3.0Gb/s |

    Friday, December 28, 2012 9:02 PM
  • I would suggest for each condition implementing a chain of responsibility and creating one to handle each item except I would modify the method that handles it to return a Boolean and only continue if it was not handled. Then use the abstract implementation to do your logging. You will have many classes due to the number of conditions but it can easily handle your situation. However, I would suggest creating a basic type that has a Predicate and a delegate (Action or Func). This basic type would check the Predicate and if true run the delegate, log the method, return true and end the chain. Then use the factory to pass in the delegates and create the chain for you by passing the delegate in as necessary. This will make it easier to code and handle as you need to add more items. You maybe creating many methods but it is easier to test and maintain.

    Thanks,

    Brad

    Saturday, December 29, 2012 12:30 AM
  • No problem.

    i would like to explain using code..

    if(Session["Name"] == null || Session[Id"] == null) { txtStatus = "Reject"; txtCode = "W101"; AcceptMethod(param1, param2) LogMethod(1);

    } else if(ClassName.getValue != null) { txtStatus = "Reject"; txtCode = "W102"; AcceptMethod(param1, param2) LogMethod(1);

    } else if(Session["Name"].tostring() != ClassName.getValue) { txtStatus = "Reject"; txtCode = "W103"; AcceptMethod(param1, param2) LogMethod(1);

    } else if(Session["Name"] == "Some Name" || Convert.Toint32(Session[Id"]) >= 0) { txtStatus = "Accept" //Further code running AcceptMethod(param1, param2)

    I want to call LogMethod(int i); after every successful condition, Hope you understand

    I Know the code is incorrect but i want to do some thing like that, on every successful condition creates a log.


    طحہ زبیر احمد Taha Zubair Ahmed http://www.tahazubair.blogspot.com

    See the changes in Bold italic and underline text.

    Ashutosh Tripathi

    Saturday, December 29, 2012 6:27 AM
  • Do you want to log when the conditions are true, false, or both?

    Log every 'true' condition:

    if ((condition) && LogThis())
    {
        ....
    }
    else if ((condition) && LogThis())
    {
        ....
    }
    else
    {
        ....
    }

    with LogThis returning true after your log code.

    Log every 'false' condition:

    if ((condition) || LogThis())
    {
        ....
    }
    else if ((condition) || LogThis())
    {
        ....
    }
    else
    {
        ....
    }

    with LogThis returning false after your log code.

    General solution:

    if (LogThis(condition))
    {
        ....
    }
    else if (LogThis(condition))
    {
        ....
    }
    else
    {
        ....
    }

    with LogThis returning its parameter value.

    Monday, December 31, 2012 10:23 AM
  • I write a custom LogEvent class

    [Serializable()]
    [XmlRootAttribute("LogEvent")]
    public class LogEvent
    {
        private LogEvent()
        {
    
        }
    
        public LogEvent(bool success, int code, string param1Type, string param1Value, string param2Type, string param2Value)
        {
            Success = success;
            Code = code;
            Param1TypeName = param1Type;
            Param1Value = param1Value;
    
            Param2TypeName = param2Type;
            Param2Value = param2Value;
        }
    
        public byte[] ToArray()
        {
            using (var memoryStream = new MemoryStream())
            {
                Write(memoryStream);
                return memoryStream.ToArray();
            }
        }
    
        public void Write(Stream stream)
        {
            if (stream == null)
                return;
    
            using (var writer = new BinaryWriter(stream))
            {
                Write(writer);
            }
        }
    
        public void Write(BinaryWriter writer)
        {
            if (writer == null)
                return;
    
            writer.Write(Success);
                    
            writer.Write(Code);
                    
            writer.Write(Param1TypeName);
            writer.Write(Param1Value);
    
            writer.Write(Param2TypeName);
            writer.Write(Param2Value);
        }
    
        public static LogEvent FromArray(byte[] bytes)
        {
            if (bytes == null)
                return null;
    
            using (var stream = new MemoryStream(bytes))
            {
                return FromStream(stream);
            }
        }
    
        public static LogEvent FromStream(Stream stream)
        {
            if (stream == null)
                return null;
    
            using (var reader = new BinaryReader(stream))
            {
                return FromReader(reader);
            }
        }
    
        public static LogEvent FromReader(BinaryReader reader)
        {
            if (reader == null)
                return null;
    
            var obj = new LogEvent();
            obj.Success = reader.ReadBoolean();
    
            obj.Code = reader.ReadInt32();
    
            obj.Param1TypeName = reader.ReadString();
            obj.Param1Value = reader.ReadString();
    
            obj.Param2TypeName = reader.ReadString();
            obj.Param2Value = reader.ReadString();
    
            return obj;
        }
    
        [XmlAttribute("Success")]
        public bool Success { get; set; }
    
        [XmlAttribute("Code")]
        public int Code { get; set; }
    
        [XmlAttribute("Param1TypeName")]
        public string Param1TypeName { get; set; }
    
        [XmlAttribute("Param1Value")]
        public string Param1Value { get; set; }
    
        [XmlAttribute("Param2TypeName")]
        public string Param2TypeName { get; set; }
    
        [XmlAttribute("Param2Value")]
        public string Param2Value { get; set; }
    }
    
    public enum LogStatus
    {
        Accept,
        Reject,
    }

    and a method

    /// <param name="status">pass LogStatus for recjected and accpeted calls.</param>
    /// <param name="code">this parameter show you which block execute(i.e. W101, W102, W103).</param>
    /// <param name="param1">first parameter for logging</param>
    /// <param name="param2">second parameter for logging</param>
    public static void LogMethodCustom(LogStatus status, string code, object param1, object param2)
    {
        bool success = status == LogStatus.Accept;
        int blockCode = int.Parse(code.Remove(0, 1));
    
        string param1Type = "Null";
        string param1Value = string.Empty;
        if (param1 != null)
        {
            param1Type = param1.GetType().FullName;
            param1Value = param1.ToString();
        }
    
        string param2Type = "Null";
        string param2Value = string.Empty;
        if (param2 != null)
        {
            param2Type = param2.GetType().FullName;
            param2Value = param2.ToString();
        }
    
        //Now, you can save your custom log with
        //blockCode: which code is passed
        //success: is successfull or not
        //
        //param1Type: which type is param1
        //param1Value: which is value of param1
        //
        //param2Type: which type is param2
        //param2Value: which is value of param2
    
        LogEvent log = new LogEvent(success, blockCode, param1Type, param1Value, param2Type, param2Value);
    
        //Method 1: Soap serialization - require System.Runtime.Serialization.Formatters.Soap
        SoapFormatter formatter = new SoapFormatter();
        using (var stream = new MemoryStream())
        {
            formatter.Serialize(stream, log);
        }
    
        //Method 2: Xml serialization
        XmlSerializer serializer = new XmlSerializer(typeof(LogEvent));
        using (var writer = new StringWriter())
        {
            serializer.Serialize(writer, log);
        }
    
        //Method 3: custom binary
        byte[] bytes = log.ToArray();
    
        //and you can serialize in any other way.
    }

    Now, Call LogMethodCustom after all of if, else conditions like below

    LogMethodCustom(txtStatus == "Reject" ? LogStatus.Reject : LogStatus.Accept, txtCode, param1, param2);
    In this code sample, You can serialize your data in any format or write your data in a custom binary manner.

    Any fool can know. The point is to understand.(Albert Einstein)

    Monday, December 31, 2012 12:35 PM
  • The answer is simple, don't use those javascript else if's they are not in any way making your program faster, but are for sure make it less maintainable. If you even don't know what happens then how would somebody else know; Make it in a way you simply can read what happens. 

    If I look at your code it seems to me from a method, so you can simply put returns in it if an condition is true and done.

    (And if it is not in a method then create a method)

    :-)


    Success
    Cor



    • Edited by Cor Ligthert Tuesday, January 1, 2013 1:39 PM typo
    Tuesday, January 1, 2013 1:38 PM
  • Dear John Saunders,

    Thanks for your help after a little time i solve my problem using a trick that if i put all my validations in a method1, method2  and so on, on success of this method i run the log method, Lets clear this using example

    private bool verifySession()
    {
    	bool bVerifySession = Session["Name"] == null || Session["Id"] == null;
    	//if bVerifySession returns me false that means condition is successfully passed so i call method else just return
    	if(bVerifySession == false)
    	{
    		LogMethod();
    	}
    	return bVerifySession;
    }
    
    //if(Session["Name"] == null || Session["Id"] == null)
    if(verifySession())
    {
    txtStatus = "Reject";
    txtCode = "W101";
    AcceptMethod(param1, param2)
    }

    Instead of checking validation in a if else condition i created a another method for all if else condition

    I hope its now clear to you

    Thanks


    طحہ زبیر احمد Taha Zubair Ahmed http://www.tahazubair.blogspot.com



    • Edited by Taha Zubair Wednesday, January 2, 2013 7:40 PM
    Wednesday, January 2, 2013 7:38 PM