Tuesday, December 10, 2013

Update app config values in run time using C#

Normally we use app.config file to store some config values. as we all know, we can easily read values from app.config using C#. but we rarely update that file in run time. but this is also possible in C#.
here i have explained how to write back(Add new keys or update values of certain key) to app.config file in run time.


/// <summary>
/// Update app config values
/// </summary>
 /// <param name="key">app config key</param>
/// <param name="value">app config value</param>

public static void UpdateAppSettings(string key, string value)
{
          // Give the correct path of an app.config file
          Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (ConfigurationManager.AppSettings[key] == null)
            {
                config.AppSettings.Settings.Add(key, value);
            }
            else
            {
                config.AppSettings.Settings[key].Value = value;
             
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");          
}

Write a main method and call this function to update app.config values. cool :)


Tuesday, June 4, 2013

Call Rest Service from C#


There are lots of ways to call REST Services in your applcation, you can either use Javascript (JQuery Functions) or C# . here i am not going to compare anything. If you want to know how to call using JQuery go here. in this post we are going to look how to call REST Services using C#

Invoking Rest Services from C# Application

public class ServiceConnector
    {
        string EndPoint ;
        string Method ; 
        string ContentType ;
        EventLogger logger ;

        public ServiceConnector(string endpoint,string method, string contenttype,string logName)
        {
            this.EndPoint = endpoint;
            this.Method = method;
            this.ContentType = contenttype;
            logger = new EventLogger(logName);
        }
        public string MakeRestRequest(string parameters, string PostData)
        {
            var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);
            logger.WriteToEventLog("Calling Services...");
            request.Method = Method;
            request.ContentLength = 0;
            request.ContentType = ContentType;

            if (!string.IsNullOrEmpty(PostData) && Method == "POST")
            {
                var encoding = new UTF8Encoding();
                var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);
                request.ContentLength = bytes.Length;

                using (var writeStream = request.GetRequestStream())
                {
                    writeStream.Write(bytes, 0, bytes.Length);
                }
            }
           
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var responseValue = string.Empty;

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
                    logger.WriteToEventLog("Web Service Call Failed. More Details : " + message);
                    throw new ApplicationException(message);
                }

                // grab the response
                using (var responseStream = response.GetResponseStream())
                {  
                    if (responseStream != null)
                        using (var reader = new StreamReader(responseStream))
                        {
                            responseValue = reader.ReadToEnd();
                        }
                    logger.WriteToEventLog("Web Service Call succeed, response value is " + responseValue);
                }

                return responseValue;
            }
        }
    }

Check whether Service call work fines or not by creating console application.
use this code to call that function


ServiceConnector Service = new ServiceConnector("Enter your Service EndPoint here", "Enter Method", "Enter ContentType", "MyServiceLog");
String response = Service.MakeRestRequest("Pass your parameters", "Pass your PostData, keep it as empty if you do GET");