Wednesday, February 13, 2013

Start With MVC Application Part 1

Before we starting to create MVC Application we required customer table on which we create our application. So first create customer table as show in below


CREATE TABLE [dbo].[tblCustomer]
(
[Id] [int] IDENTITY(1,1) NOT NULL, [Name] [varchar](50) NOT NULL, [Address] [varchar](500) NOT NULL, [City] [varchar](50) NOT NULL,[State] [varchar](50) NOT NULL,[Country] [varchar](50) NULL, [Phone] [varchar](15) NULL, [EmailId] [varchar](50) NULL,
CONSTRAINT [PK_tblCustomer] PRIMARY KEY CLUSTERED 
( [Id] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]GO




We creating our MVC Application with Visual Studio 2010. Start your visual studio, from File menu select New Project as shown in below. Select ASP.NET MVC 2 Web Application template (other wise download template from http://www.asp.net/mvc) give name MyFirstApplication and click on Ok in next screen skip Unit Test Project Creation.


Right click on models folder and LINQ to SQL Classes with name Application, select database and drag n drop tblCustomer on design surface area with this step we completed our prerequisite of our application




Create customer folder under views folder in which we are going to store all customer related methods. Now we going to create CRUD methods for Customer using MVC. First we create controller for customer for this right click on Controllers folder and add controller with name CustomerController. This is one of the most important step while creating MVC Application.




When we create controller Index method created it contains Index method. We use this method to show list of all record from that controller. Add following code in Index method which returns list of customers.


 public ActionResult Index()
 {
       var Customers = from vcustomer in this.dbContext.tblCustomers 
                                      select vcustomer;
      return View(Customers);
}


Right click on Index method then select Add View menu from pop menu. In Add view window set parameter as shown in the picture below




After clicking on Add button Visual Studio create Index.Aspx page in Views/Customer folder which will be our landing page for Customers. Now we have to add customer menu in master page for this open Site.Master page from Shared folder.  In master page add Html.ActionLink for customer as shown below

                <ul id="menu">              

                    <li><%= Html.ActionLink("Home", "Index", "Home")%></li>
                    <li><%= Html.ActionLink("Customer", "Index", "Customer")%></li>
                    <li><%= Html.ActionLink("About", "About", "Home")%></li>
                </ul>


After Adding this compiled and run the web application. In next blog we going to study how to implement CRUD methods for customer object.






Monday, February 11, 2013

How to implement SPCache in SharePoint 2010 ?

Following code shows implementation of SPCache object in SharePoint 2010.

// Object for Cacheing

public class TestClass
    {
        public string someData { get; set; }
        public TestClass(string myData)
        {
            this.someData = myData;
        }

    }




// SPCache Object Settings Cache Parameters

 public class MyCache
    {
        public static SPCacheConfig cacheConfig = new SPCacheConfig();
        internal static CacheParameter[] CacheParameters = new CacheParameter[]
        {
          // DataCache
          new CacheParameter(ServiceName,
                                             DataCache,
                                             0xfffff,
                                             PriorityType.High,
                                             new TimeSpan(0,60,0))
        };
        internal const string ServiceName = "CacheAppStressTest";
        internal const string DataCache = "CacheAppStressTest.Data";
    }


Create Web part and add following code

 public class CustomCache : WebPart
    {
        Label lblMessage;
        Label lblCacheData;
        public CustomCache()
        {
            this.lblMessage = new Label();
            this.lblMessage.ID = "lblMessage";
            this.lblCacheData = new Label();
            this.lblCacheData.ID = "lblCacheData";
        }
        protected override void CreateChildControls()
        {
            try
            {
                byte priority = 0;              
           
                MyCache.CacheParameters[0].lifetime = new TimeSpan(0, 1, 0); //Set life time of parameter
                MyCache.CacheParameters[0].priority = (PriorityType)priority; // Set priority of paramater
                MyCache.cacheConfig.AddCaches(MyCache.CacheParameters);

                SPCache.Cache.Put(MyCache.DataCache, new SPCachedObject("Test", new TestClass("some data"), new TimeSpan(1, 0, 0)));  // Add cache object into SPCache Collection


                TestClass newClass = (TestClass)SPCache.Cache.Get(MyCache.DataCache, "Test");
                if (newClass != null)
                {
                    this.lblCacheData.Text = "<br /><b>" + newClass.someData + "</b>";
                }
                else
                {
                    this.lblCacheData.Text = "<br /><b> Null data</b>";
                }
// Remove cache object
                SPCache.Cache.Delete(MyCache.DataCache, "Test");
//Display Cache data
                this.lblMessage.Text = string.Format("CacheHits={0}\r\nReads={1}\r\nCount={2}\r\nSizeBytes={3}\r\nHitRatio={4}",
      SPCache.Cache.TotalCacheHits, SPCache.Cache.TotalReadAttempts, SPCache.Cache.Count, SPCache.Cache.UsedBytes, SPCache.Cache.HitRatio);
                MyCache.cacheConfig.RemoveCaches(MyCache.CacheParameters);
            }
            catch (Exception ex)
            {
                this.lblMessage.Text = ex.Message;
            }
            this.Controls.Add(this.lblMessage);
            this.Controls.Add(this.lblCacheData);

        }
    }



Monday, February 4, 2013

Access Business Connectivity Services object using Client Application


Business Connectivity Service (BCS), enables users to read and write data from external systems - from web services, database, and Microsoft .NET Framework.
Following code snippet shows, how to access BCS object using Client Object Model

We already have BCS list named "Customer", contains columns Name, Address


// Specify your SharePoint Web Url

 ClientContext clientContext = new ClientContext("http://contoso:3434");
             
// Specify SharePoint list name
                List list = clientContext.Web.Lists.GetByTitle("Customer");

                CamlQuery query = new CamlQuery();
             
                query.ViewXml =
                    @"  <View>
                            <ViewFields>
                                <FieldRef Name='Name'/>
                                <FieldRef Name='Address'/>
                            </ViewFields>
                            <Query>
                                <Where>
                                <Eq>
                                <FieldRef Name='Name'/>
                                <Value Type='Text'>Jhon</Value>
                                </Eq>
                                </Where>
                            </Query>
                            <RowLimit>100</RowLimit>
                        </View>";

                ListItemCollection listItems = list.GetItems(query);

// Specify which field required to include in list object other wise it throws exception
                clientContext.Load(
                listItems, items => items.Include(
                 item => item["Name"], item => item["Address"]));


                clientContext.ExecuteQuery();

                foreach (ListItem listItem in listItems.ToList())
                {
                    Console.WriteLine("{0} ==> {1}", listItem["Name"].ToString(), listItem["Address"].ToString());
                }