Showing posts with label Visual Studio 2013. Show all posts
Showing posts with label Visual Studio 2013. Show all posts

Wednesday, January 4, 2017

Restful WCF service

Even though its a pretty old topic, thought this post would be helpful for newbie's.
Here, I created a WCF Service Application (Name: WcfService1)

Deleted the svc created by default and created my own WCF Service (Name: MyRestService)

In the interface IMyRestService add the below code

[ServiceContract]
    public interface IMyRestService
    {
        [OperationContract]
        void DoWork();

        [OperationContract]
        [WebInvoke(Method = "GET",
              ResponseFormat = WebMessageFormat.Json,
              BodyStyle = WebMessageBodyStyle.Bare,
              UriTemplate = "GetProductList/")]
        List<Product> GetProductList();

        [OperationContract]
        [WebInvoke(Method = "GET",
              ResponseFormat = WebMessageFormat.Json,
              BodyStyle = WebMessageBodyStyle.Bare,
             UriTemplate = "GetName/")]
        string GetName();
    }

in the .svc implemented the below:

public class MyRestService : IMyRestService
    {
        public void DoWork()
        {
        }

        public List<Product> GetProductList()
        {
            //Product is a class which I used to load product details from repository
            Product p = new Product();
            return p.GetProducts();
        }

        public string GetName()
        {
            return "Hello World";
        }
    }

Solution structure is



In the web.config do the below settings

  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="serviceBehavior">
          <serviceMetadata httpGetEnabled="false"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>    
    </behaviors>

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
 
    <services>
      <service name="WcfService1.MyRestService" behaviorConfiguration="serviceBehavior">
        <endpoint address=""
                  binding="webHttpBinding"
                  contract="WcfService1.IMyRestService"
                  behaviorConfiguration="web"></endpoint>
      </service>
    </services>
  </system.serviceModel>

Now you can test the methods using the urls:

1) http://localhost:63337/MyRestService.svc/GetName/
2) http://localhost:63337/MyRestService.svc/GetProductList/



Saturday, February 21, 2015

Playing around with the TreeView

Playing around with the ASP.Net TreeView.

Initially a TreeNode is created and child nodes are added under the node.

        TreeNode tree = new TreeNode();
        
        tree.Value = "Social Media";
        tree.ImageUrl = "/images/home.png";
        tree.ChildNodes.Add(new TreeNode("Facebook", "Facebook","/images/fb.png"));
        tree.ChildNodes.Add(new TreeNode("G+","GPlus","/images/google.png"));
        tree.ChildNodes.Add(new TreeNode("Printrest", "Printrest", "/images/pintrest.png"));
        tree.ChildNodes.Add(new TreeNode("Twitter", "Twitter", "/images/twitter.jpg"));

Now lets add some child nodes under the created nodes. In this example the below would be the leaf nodes.

            foreach (TreeNode node in tree.ChildNodes)
            {
                node.ChildNodes.Add(new TreeNode("Sri Lanka", string.Concat(node.Value,"-","SL"), "/images/countries/SL-flag.jpg"));
                node.ChildNodes.Add(new TreeNode("Malaysia", string.Concat(node.Value,"-","ML"), "/images/countries/malaysia-flag.png"));
                node.ChildNodes.Add(new TreeNode("USA", string.Concat(node.Value,"-","USA"), "/images/countries/US-Flag.png"));
                node.ChildNodes.Add(new TreeNode("Britain", string.Concat(node.Value,"-","BRIT"), "/images/countries/Britain-flag.png"));
                node.ChildNodes.Add(new TreeNode("Australia", string.Concat(node.Value,"-","AUS"), "/images/countries/Australia-Flag.png"));
                node.ChildNodes.Add(new TreeNode("Netherlands", string.Concat(node.Value,"-","NL"), "/images/countries/netherlands-flag.png"));
                node.ChildNodes.Add(new TreeNode("Egypt", string.Concat(node.Value,"-","EG"), "/images/countries/Egypt-Flag.png"));
                node.ChildNodes.Add(new TreeNode("Greece", string.Concat(node.Value,"-","GR"), "/images/countries/greece_flag.png"));
                node.ChildNodes.Add(new TreeNode("Germany", string.Concat(node.Value,"-","GE"), "/images/countries/germany-flag.png"));
                node.ChildNodes.Add(new TreeNode("Canada", string.Concat(node.Value,"-","CA"), "/images/countries/canada_flag.png"));
                node.ChildNodes.Add(new TreeNode("Brazil", string.Concat(node.Value,"-","BR"), "/images/countries/brazil-flag.png"));
            }

 The TreeNode is then set to a TreeView to be displayed in the Form.

        TreeView view = new TreeView();
        view.ShowCheckBoxes = TreeNodeTypes.All;
        view.Nodes.Add(tree);
        view.TreeNodeCheckChanged += view_TreeNodeCheckChanged;
        view.Attributes.Add("onclick", "postBackByObject()");

        form1.Controls.Add(view);

Here, notice the JavaScript method postBackByObject() which does the job of auto postbacking on clicking on a Checkbox of a Node. For this purpose you need to add the following script in the ASPX page. Auto post backing comes in handy when you need to check or uncheck the set of child-nodes belonging to a selected node.


    <script type="text/javascript">
        function postBackByObject() {
            var o = window.event.srcElement;
            if (o.tagName == "INPUT" && o.type == "checkbox") {
                __doPostBack("", "");
            }
        }
    </script>

To programmatically check or uncheck child nodes of a node, use the TreeNodeCheckChanged event. A sample code would be:

    void view_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
    {
        if (e.Node.Checked)
        {
            CheckChildNodes(e.Node.ChildNodes);
        }
        else if (e.Node.Checked == false)
        {
            UncheckChildNodes(e.Node.ChildNodes);
        }
    }

    private void UncheckChildNodes(TreeNodeCollection children)
    {
        foreach (TreeNode child in children)
        {
            if (child.Checked)
                child.Checked = false;
            UncheckChildNodes(child.ChildNodes);
        }
    }

    private void CheckChildNodes(TreeNodeCollection children)
    {
        foreach (TreeNode child in children)
        {
            if (child.Checked == false)
                child.Checked = true;
            CheckChildNodes(child.ChildNodes);
        }
    }

Then you get the resulting tree as below. The data in this view is created merely for illustration purposes of the ASP.Net TreeView and has no actual meaning.




Saturday, January 17, 2015

Adding Custom Properties to a Visual Web Part

When the Visual web part is generated in Visual Studio (Eg; VS 2013). It contains mainly 3 components. The web part file, user control a ASCX file and the code behind for the user control

The web part is generated with the following code in the CreateChildControls() method

private const string _ascxPath = @"~/_CONTROLTEMPLATES/15/....../MyWebPartUserControl.ascx";

protected override void CreateChildControls()
{
  Control control = Page.LoadControl(_ascxPath);
  Controls.Add(control);
}

Here, the .ascx could not access the custom web part properties.
When adding custom properties to the Visual web part,  few changes are required.

1) Create a property in the user control, of the web part class type.

public MyVisualWebPart ParentWebPart { get; set; }

2) Set the web part to the user controls parent property

Inside the web part file's CreateChildControls() method change the code to:

MyVisualWebPartUserControl control = (MyVisualWebPartUserControl)Page.LoadControl(_ascxPath);
//Set the web part to the users controls parent property                                                                             
control.ParentWebPart = this;
Controls.Add(control);    

Now the custom web part properties are accessible from the user control !                                                                                                              

3) Add the required custom properties into the web part file

        private string customPropertyOne;                           
        [Category("My WebParts Custom Settings"),           
        Personalizable(PersonalizationScope.Shared),          
        WebBrowsable(true),                                              
        WebDisplayName("Custom Property One"),            
        WebDescription("This is my first custom property")] 
        public string CustomPropertyOne                             
        {                                                                             
            get { return customPropertyOne; }                      
            set { customPropertyOne = value; }                    

        }                                                                            

4) Access the property in the ASCX file

Now you can access the custom property via:

ParentWebPart.CustomPropertyOne