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());
                }


Wednesday, January 16, 2013

An exception occurred when trying to issue security token


Security Token Service Application Error:
Problems:  Unable to Login with Claim base authentication to SharePoint 2010 Site
Errors
An exception occurred when trying to issue security token: The requested service, 'http://localhost:32843/SecurityTokenServiceApplication/securitytoken.svc' could not be activated. See the server's diagnostic trace logs for more information.
Or
WebHost failed to process a request.
 Sender Information: System.ServiceModel.ServiceHostingEnvironment+HostingManager/15688314
 Exception: System.ServiceModel.ServiceActivationException: The service '/SecurityTokenServiceApplication/securitytoken.svc' cannot be activated due to an exception during compilation.  The exception message is: Method not found: 'System.String System.ServiceModel.Activation.Iis7Helper.ExtendedProtectionDotlessSpnNotEnabledThrowHelper(System.Object)'.. ---> System.MissingMethodException: Method not found: 'System.String System.ServiceModel.Activation.Iis7Helper.ExtendedProtectionDotlessSpnNotEnabledThrowHelper(System.Object)'.
   at System.ServiceModel.WasHosting.MetabaseSettingsIis7V2.WebConfigurationManagerWrapper.BuildExtendedProtectionPolicy(ExtendedProtectionTokenChecking tokenChecking, ExtendedProtectionFlags flags, List`1 spnList)
   at System.ServiceModel.WasHosting.MetabaseSettingsIis7V2.WebConfigurationManagerWrapper.GetExtendedProtectionPolicy(ConfigurationElement element)
   at System.ServiceModel.WasHosting.MetabaseSettingsIis7V2.ProcessWindowsAuthentication(String siteName, String virtualPath, HostedServiceTransportSettings& transportSettings)
   at System.ServiceModel.WasHosting.MetabaseSettingsIis7V2.CreateTransportSettings(String relativeVirtualPath)
   at System.ServiceModel.Activation.MetabaseSettingsIis.GetTransportSettings(String virtualPath)
   at System.ServiceModel.Activation.MetabaseSettingsIis.GetAuthenticationSchemes(String virtualPath)
   at System.ServiceModel.Channels.HttpChannelListener.ApplyHostedContext(VirtualPathExtension virtualPathExtension, Boolean isMetadataListener)
   at System.ServiceModel.Channels.HttpTransportBindingElement.BuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BindingContext.BuildInnerChannelListener[TChannel]()
   at System.ServiceModel.Channels.MessageEncodingBindingElement.InternalBuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BinaryMessageEncodingBindingElement.BuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BindingContext.BuildInnerChannelListener[TChannel]()
   at System.ServiceModel.Channels.Binding.BuildChannelListener[TChannel](Uri listenUriBaseAddress, String listenUriRelativeAddress, ListenUriMode listenUriMode, BindingParameterCollection parameters)
   at System.ServiceModel.Description.DispatcherBuilder.MaybeCreateListener(Boolean actuallyCreate, Type[] supportedChannels, Binding binding, BindingParameterCollection parameters, Uri listenUriBaseAddress, String listenUriRelativeAddress, ListenUriMode listenUriMode, ServiceThrottle throttle, IChannelListener& result, Boolean supportContextSession)
   at System.ServiceModel.Description.DispatcherBuilder.BuildChannelListener(StuffPerListenUriInfo stuff, ServiceHostBase serviceHost, Uri listenUri, ListenUriMode listenUriMode, Boolean supportContextSession, IChannelListener& result)
   at System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost)
   at System.ServiceModel.ServiceHostBase.InitializeRuntime()
   at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceHost.InitializeRuntime()
   at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(String normalizedVirtualPath)
   at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)
   --- End of inner exception stack trace ---
   at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)
   at System.ServiceModel.ServiceHostingEnvironment.EnsureServiceAvailableFast(String relativeVirtualPath)
 Process Name: w3wp
 Process ID: 4780

Solution: Uninstall Security Update No. - KB2756920