Saturday 13 December 2014

Printing a sequence with out using multiple loops


Sequence

*
**
***
****
*****
****
***
**
*

How to do it

using System;
using System.Collections;
 
namespace PrintStarSequence
{
    class Program
    {
        static ArrayList arrayList = null;
        static void Main(string[] args)
        {
            int countofMaxStars= 5;
            int start =1;
            int counter = 1;
            bool taskDone = false;
            bool isReverse = false;
            arrayList = new ArrayList();
 
            do
            {
                if(isReverse == true)
                {
                    arrayList.Remove("*");
                    Console.Write(String.Join(String.Empty, arrayList.ToArray()));
                    countofMaxStars--;
                    if(countofMaxStars < start)
                        taskDone = true;
                    
                }
                else
                {
                    arrayList.Add("*");
                    Console.Write(String.Join(String.Empty, arrayList.ToArray()));
                    if (counter == countofMaxStars)
                    { 
                        isReverse = true;
                        counter = 1;
                        countofMaxStars--;
                    }
 
                }
 
                Console.WriteLine();
                counter++;
 
 
            } while (taskDone == false);
 
            Console.Read();
        }
 
        
    }
 
}

Thursday 10 July 2014

structure map with factory pattern using structuremap.config

I was looking for a very simple example around for integrating structure map with factory pattern , since I found it in bit and pieces.. I am here documenting my own version of it.


Before I  jump in to code and configuration the jist of below code is that, I would like to create Italian or Indian food object based on what customer request.

StructureMap.config -  make sure you set property Copy to out put directory as Copy always

feel free to download complete code from https://github.com/varunpathak/samples.git
 
 <?xml version="1.0" encoding="utf-8" ?>
<StructureMap>


  <PluginFamily Type="StructureMapHelloWorld.IFood" Assembly="StructureMapHelloWorld" DefaultKey="IndianFoodKey">
    <Plugin Type="StructureMapHelloWorld.SouthIndian" Assembly="StructureMapHelloWorld" ConcreteKey="IndianFoodKey" />
    <Plugin Type="StructureMapHelloWorld.Italian" Assembly="StructureMapHelloWorld" ConcreteKey="ItalianFoodKey" />
  </PluginFamily>



</StructureMap>


 FoodEngine.cs

namespace StructureMapHelloWorld
{
    
    public interface IFood
    {
        string GetFood();
    }

    public class SouthIndian : IFood
    {
        public string GetFood()
        {
            return "Idly-Dosa";
        }
    }

    public class Italian : IFood
    {
        public string GetFood()
        {
            return "Pizza";
        }
    }


}





Program.cs


using StructureMap;
using System;

namespace StructureMapHelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            ConfigureDependencies();


            Console.WriteLine("Type indian for Indian food / type italian for Italian Food / Press E to Exit");

            string foodKind = Console.ReadLine();

            while (String.IsNullOrEmpty(foodKind) == false && foodKind.ToLower() != "e")
            {

                IFood food;

                if (foodKind.ToLower().Contains("italian"))
                {
                    food = ObjectFactory.GetNamedInstance<IFood>("ItalianFoodKey");
                    Console.WriteLine("Thanks for Ordering " + food.GetFood());
                    foodKind = Console.ReadLine();
                }

                else if (foodKind.ToLower().Contains("indian"))
                {
                    food = ObjectFactory.GetNamedInstance<IFood>("IndianFoodKey");
                    Console.WriteLine("Thanks for Ordering " + food.GetFood());
                    foodKind = Console.ReadLine();
                }

                else
                {
                    Console.WriteLine("Type indian for Indian food / type italian for Italian Food / Press E to Exit");
                    foodKind = Console.ReadLine();
                }


            }

            Environment.Exit(0);

        }


        private static void ConfigureDependencies()
        {
            
            ObjectFactory.Initialize(x =>
            {
                // We put the properties for an NHibernate ISession
                // in the StructureMap.config file, so this file
                // must be there for our application to
                // function correctly
                //http://docs.structuremap.net/ConfiguringStructureMap.htm
                x.UseDefaultStructureMapConfigFile = true;
                //x.PullConfigurationFromAppConfig = true;
            });

        }
    }
}
 

Wednesday 23 April 2014

JSON Date input to WCF Rest service

what's the problem .....in passing date using ajax/JSON method to wcf rest service ,you can read it here ....from Scott and problem here

now you got to pass a date(JSON FORMAT) using ajax/JSON call from asp.net page. ,

I have taken bits of code and modified to my needs from here


using System;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace SomeNameSpace
{
/// <summary>
/// Class describes the Entities for Persons
/// </summary>
[DataContract(Namespace = "")]
public class Person
{
private int _personId;
private string _emailAddress;
private string _IP;
private DateTime _CreatedOn;
private DateTime _ModifiedOn;
private DateTime _subscribedOn;
private string _statusCD;
private string _sourceCD;


[DataMember]
public virtual int PersonId
{
get
{
return _personId;
}
set
{
_personId = value;
}
}
[DataMember]
public virtual string EmailAddress
{
get
{
return _emailAddress;
}
set
{
_emailAddress = value;
}
}
[DataMember]
public virtual string IP
{
get
{
return _IP;
}
set
{
_IP = value;
}
}
[DataMember]
public virtual DateTime CreatedOn
{
get
{
return _CreatedOn;
}
set
{
_CreatedOn = value;
}
}
[DataMember]
public virtual DateTime ModifiedOn
{
get
{
return _ModifiedOn;
}
set
{
_ModifiedOn = value;
}
}
/// <summary>
/// Gets or sets the subscriptione date.
/// </summary>
/// <value>
/// The subscribed on.
/// </value>
[DataMember]
public virtual DateTime SubscribedOn
{
get
{
return _subscribedOn;
}
set
{
_subscribedOn = value;
}
}
/// <summary>
/// Gets or sets the status cd.this is null when a user unsubscribes
/// </summary>
/// <value>
/// The status cd.
/// </value>
[DataMember]
public virtual string StatusCD
{
get
{
return _statusCD;
}
set
{
_statusCD = value;
}
}
/// <summary>
/// Gets or sets the source cd.To Identify whether a user is valid
/// </summary>
/// <value>
/// The source cd.
/// </value>
[DataMember]
public virtual string SourceCD
{
get
{
return _sourceCD;
}
set
{
_sourceCD = value;
}
}

}
}


                 [OperationContract()]
[WebInvoke(Method = "POST", UriTemplate = "AddUser")]
bool AddUser(Person user);



       
      [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerCall)]
public class TestService : ISubscriberService
{

       public bool AddUser(Person user)
{
            return true;
//Do what ever you want
}
    }


download ww.jquey.js from here

under your aspx page refer <script src="scripts/ww.jquery.js"></script>


<script type="text/javascript">

        var date = new Date();

        EmailAddress = 'varunpathak123@gmail.com';
        SourceCD = 'testapp';

       

        var person =
                        {
                            'IP': "12.22.434",
                            'CreatedOn': date,
                            'ModifiedOn': date,
                            'SubscribedOn': date,
                            'StatusCD': "ACTV",
                            'EmailAddress': EmailAddress,
                            'SourceCD': SourceCD,
                           
                        };







                        person = JSON.stringifyWcf(person);

        function PostData() {
            $.ajax(
                        {
                            type: "POST",
                            url: "http://localhost:9234/AddUser",
                            contentType: "application/json; charset=utf-8",
                            data: person,
                            dataType: "json",
                            success: function (result) {
                             
                                alert("Success");
                            },
                            failure: function (result) {
                                alert("Failure");
                            }
                        });
        }
                   

                 

    </script>

I want to give a vote of thanks again to Rick Strahl. There are plenty of post out there which I tried but did not work for me....apart from this one .
I could have changed my wcf service ,but dates have always been a problem be it any world.

I have highlighted the function JSON.stringifyWCF which looks like this

 JSON.stringifyWcf = function(json) {
        /// <summary>
        /// Wcf specific stringify that encodes dates in the
        /// a WCF compatible format ("/Date(9991231231)/")
        /// Note: this format works ONLY with WCF.
        ///       ASMX can use ISO dates as of .NET 3.5 SP1
        /// </summary>
        /// <param name="key" type="var">property name</param>
        /// <param name="value" type="var">value of the property</param>        
        return JSON.stringify(json, function(key, value) {
            if (typeof value == "string") {
                var a = reISO.exec(value);
                if (a) {
                    var val = '/Date(' + new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])).getTime() + ')/';
                    this[key] = val;
                    return val;
                }
            }
            return value;
        })
    };

one can make out it is specifically targeting dates format.which is always a issue with JSON to WCF


I hope this post will help some one.