Wednesday, December 7, 2011

MVC 3 Razor And Partial View

MVC 3 Razor And Partial View

How do I use partial view in MVC 3?
Great!! Sometime, I don’t know why, I stuck for small things. I was trying to load two partial views(MVC 3). But, after spending 6 hours I got to know how to load.
This retards my brain. I have searching for good articles on MVC 3 & Partial views. But, I failed to get it.
So, Let us go in dept on MVC3 & Partial Views.
Partial view and User Controls are somewhat same in purpose of usage. But the way in which they is totally different. I will explain about these in detail.

Step 1
Create ASP.Net MVC 3 project using VS 2010. I have named it as ARVPartialView.
Add one partiaview and name it as PartialIndex












Step2
I have created one module like PartialModel as given bellow.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ARVPartialView.Models
{
public partial class PartialModel
{
public string Name { get; set; }
public int Actual { get; set; }
public int Target { get; set; }
public int Score { get; set; }
}

public partial class PartialModel
{
public List lstPartialModel { get; set; }

}
}




Step 3

Now the time to add some values to this list. The solution structure looks like as given bellow.




Since I like render partial view over Home/Index, So, I have written one function in HomeController.

public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
///
/// TODO:To get data and returning result to the index view..
///

///
return View(new PartialModel() { lstPartialModel = GetSampleData() });

}

public ActionResult About()
{
return View();
}


///
/// TODO:Function to add some data to list.
///

///
private List GetSampleData()
{
List model = new List();

model.Add(new PartialModel()
{

Name = "Aravind",
Actual = 10000,
Target = 12000,
Score = 83
});

model.Add(new PartialModel()
{

Name = "Ram",
Actual = 8000,
Target = 14000,
Score = 57
});
model.Add(new PartialModel()
{
Name = "Ajay",
Actual = 50000,
Target = 35000,
Score = 143
});

return model;
}
}


Step 4

In Index view, I have included partial view as given bellow. As like web usercontrol, partial view doest initiate any events while loading Just like initializecomponet etc. So, we have to pass the list to partial view in the parent page.







Step 5
Render partial view on Index view.




Step 6


Run the application.



Have a nice time & enjoy..
aravindbenator@gmail.com
http://silverlightarvind.blogspot.com







Monday, December 5, 2011

What is Silverlight Application Library Caching?

What is Silverlight Application Library Caching?


I was just working with one Silverlight application that has too many 3rd party assemblies (Excel, theme, charts etc).

Also it was taking long time while downloading first time. Obviously, this is because of large XAP size. So, I thought to divide entire application in multiple projects which will create multiple XAP’s and then use it by on demand load.

But, I have used more third party dll’s. In this case it is too hectic to store them on separate XAP and then load it on demand. Then, I came to know about new concept (for me) about “ Application Library Caching”



So, What is Assembly caching? We all know about the on demand download of XAP file. To do this, we need to write code for downloading the external xap files using WebClient. Application Library caching does the similar thing for you very easily. Suppose, if you have a bigger application and used a huge 3rd party libraries, this easy step will help you make a separate zip file with them which can be downloaded on demand without writing any additional code.



Step 1.

Create one Silverlight 3 or 4 application(its available in SL 3 also). I have named it as ARVApplicationLibraryCaching.

If you see in the solution-references, you will find the assemblies ,those have been added to the project.





Once you build the app, you can find XAP file in the client bin directory.

To see the contents inside the XAP, go to the ClientBin folder. There you will find the XAP output of your Silverlight application. Rename it with zip and extract then, you can find as given bellow.




To see all the assembly references, open appmanifest file using notepad.




You will notice that, it has all the referenced dll information as Assembly part, entry point and required runtime version. Assembly parts tells to load the referred assembly directly from the XAP.





Step 2.

Adding more third party Assemblies.

Go to add reference and add some third party dll’s. I have added here some dll’s related to theme.





Once you build the app and unzip the XAP. Then you will find as given bellow.




You will see that all the new referenced dlls are now part of your XAP. If you open AppManifest.xmal,






it contains all those additional dll entries as AssemblyPart and tells to load them from the XAP itself.

This actually increases the XAP size and makes your application little bulky. Thus increases initial loading time of your application.



Step 3.

Use application library caching.

To overcome this, there is a setting project property window as shown bellow.






Now, build the project. You will find zip files as per you have been added third party dll’s.




Then, go to AppManifest file, then see






Here a single AssemblyPart pointing to your original project output and rest of the dll references are now moved to ExternalParts. They are now pointing to the Zip files instead of the actual dlls.

Now, when you run your application, it will only download the XAP file which contains only the main resources. Rest of the dll ZIP will be downloaded on demand whenever require by your application.

Enjoy the concept!!!!!!!



Aravind

Thursday, November 10, 2011

Making Offline MVC 3 Application.

Offline App




Hi Guys!! I never thought, building offline MVC 3 app could be this much simple.

I had a question in mind for a long time that Why this offline application? How it works? Etc...

As per my knowledge, In Silverlight there is smart client concept. So that, Even we can see and work when there is no network available (flight mode or in remote area). Whenever device/app detects network, then either user can invoke saving operation into server or application can automatically triggers event to save data.

Silverlight did a great job in this aspect. But, in case of asp.net/html application, how it can be done?.

For the same purpose, HTML 5 introduces a MIME type manifest and local storage.

It mainly adds one manifest file to load all required recourses.

This walkthrough is to demonstrate the how we can create/develop offline/online application using MVC 3.

I will first create ASP.Net MVC 3 empty app using VS 2010 and I will add offline htm page to the project.



The htm page will look like:















The first line uses the Html5 doctype and the header links to jQuery. We uses two buttons, one to create the profiles in the browser local storage and another the send the profiles to the server.

To create red boxes arround our input boxes when jQuery detects some validation we need to add these few lines of css to stylesheet:

input.error {

border: 2px solid red;

}

Now it’s time to implement our UI logic with javascript. By creating a separate file for our javascript we keep the html page clean.

Add a “offline.js” to the script folder:

var root = '/Offline;//Controller name.


var subscriptionsUploaded = 0;






//jQuery on document ready handler


$(function () {


//Show the busy indicator during ajax calls


$("#busy").hide();


$("#busy").ajaxStart(function () { $("#busy").show(); })


$("#busy").ajaxStop(function () { $("#busy").hide(); })


var x = $("#createSubscription");


//When the createSubscription button is clicked create a subscription


$("#create_subscription").click(createSubscriptionClick);






//When the sendData button is clicked retrieve the subscriptions stored in the local storage and send the data to the server


$("#send_data").click(sendDataClick);






//Define jQuery validation rules and execute the validation when the form is validated


$("#sub_form").validate({


rules: {


firstname: {


required: true,


minlength: 2


},


lastname: {


required: true,


minlength: 2


},


email: {


required: true,


email: true


},


phone: {


required: true,


number: true,


minlength: 9,


maxlength: 9


}


},


messages: {


firstname: "",


lastname: "",


email: "",


phone: ""


}


});


});






function sendDataClick() {


//Iterate over the subscriptions stored in the local storage


for (var i = 0; i < window.localStorage.length; i++) {


//Retrieve the serialized subscription


var json = window.localStorage.getItem(window.localStorage.key(i));


try {


//Send the subscription to the server


sendData(


json,


//On success remove the subscription from the local storage


function (data) {


window.localStorage.removeItem(window.localStorage.key(data.Message));


subscriptionsUploaded++;


$("#resultmessage").html(subscriptionsUploaded + " subscriptions uploaded!");


},


//On error


function (xhr) {


alert(xhr.responseText);


});


}


catch (e) { alert(e); }


};


}






//Stores a subscription into the local storage


function createSubscriptionClick() {


//check the jQuery validation rules


if ($("#sub_form").valid()) {


var person = getSubscription();


//seialize the subscription


var jsData = JSON.stringify(person);


//store the subscription


window.localStorage.setItem($("#email").val(), jsData);


//update the resultMessage


$("#resultmessage").html($("#email").val() + " stored in local storage");


clearAll();


}


}






//Create a subscription object and bind to the input boxes values


function getSubscription() {


var firstname = $("#firstname").val();


var lastname = $("#lastname").val();


var email = $("#email").val();


var phone = $("#phone").val();


return { Firstname: firstname, Lastname: lastname, Email: email, Phone: phone };


}






//Clear the input boxes values


function clearAll() {


$("#firstname").attr("value", "");


$("#lastname").attr("value", "");


$("#email").attr("value", "");


$("#phone").attr("value", "");


}






//Ajax: post the json serilized subscriptions


function sendData(json, success, error) {


$.ajax({


url: root + '/save',


type: 'POST',


dataType: 'json',


data: json,


contentType: 'application/json; charset=utf-8',


success: success,


error: error


});


}



To get data from controller side we can use JSON format as given bellow.

In js file we can use

$.getJSON(

//controller name.

root + '/GetDataFromServer',

"",

function (data) {

});



When the user click on the create button the createSubscription function is called, this function is responsible for serializing the data into a Json object and to store it in the isolated storage. Isolated storage is a feature defined in the Html5 spec. For each domain the browser provide access to private key/value pair collection where data can be stored and retrieved. The sendData button is attached with an anonymous function that iterate over the key/value pair collection that contains the JSON serialized subscriptions and post the JSON serialized subscription object.

The MVC 3 includes built-in JSON binding support that enables action methods to receive JSON-encoded data and model-bind it to action-method parameters. We will now create our Model to bind to, add a OfflineModel class to the models of the MVC app:

public class OfflineModel

{

[Required]

[Display(Name = "Firstname")]

public string Firstname { get; set; }



[Required]

[Display(Name = "Lastname")]

public string Lastname { get; set; }



[Display(Name = "Phone")]

public string Phone { get; set; }



[Required]

[DataType(DataType.EmailAddress)]

[Display(Name = "Email address")]

public string Email { get; set; }



public void Save()

{

//store the object in db

//...

}

}





In controller, I have written sample code for returning some data.



public ActionResult GetDataFromServer()

{

List lstscores = new List();

try

{

//Return format to the client side.

return Json(

new { message = lstscores },

JsonRequestBehavior.AllowGet);



}

catch

{

throw;

}

}





In case, we need to bind these data to any controller like table/list etc, then we can create item list dynamically.

Here “data” is the JSON array of data. Here I am creating rows and adding it into existing table.

for (var i = 0; i < data.message.length; i++) {






$("table#lst_info").find('tbody')


//Column Agency


.append($(' ')


.append($('')


.append($('


.text(data.message[i].Agency)






)


)


//Column Actual


.append($('')


.append($('


.text(data.message[i].Actual)






)


)


//Column Target


.append($('')


.append($('


.text(data.message[i].Target)






)


)


//Column Score


.append($('')


.append($('


.text(data.message[i].Score)






)


)










);






}



Now, we can test the application.

To be able to load the application when we are offline we need to use a new feature available in the latest browser like IE9, the Html5:”offline application.

Add Offline.manifest file to the root of the application.

CACHE MANIFEST


/Offline.htm


/Content/Site.css


/Scripts/Offline.js


/Scripts/jquery-1.5.1.min.js


/Scripts/jquery.validate.min.js


/Content/wait.gif



Change the Doctype of the Offline.htm

////







So, now even when network is not available also, can display the page.

Let’s have a fun!!!!!!

Storing data over local storage:

As of you all knows, there are two types of web storage's.

1.localstorage .


2.Session storage.



But, In this article, we will discuss about localstorage.

In simple, we can add data to local storage as like this..

window.localStorage.setItem("data",”Hi this is Aravind”);



Retrieving data from localstorage…



var datadt = window.localStorage.getItem("data");



Suppose, if I want to save list or array, then what can be done?.



Then, we have to convert list/array into JSON format.



window.localStorage.setItem("data", JSON.stringify(data));



Retrieving it as..

var frequentdatadt = window.localStorage.getItem("data");


var data = JSON.parse(frequentdatadt);

Regards
Aravind













Thursday, October 6, 2011

CRM 2011 Online Vs On-Premise.

In my previous article http://silverlightarvind.blogspot.com/2011/09/crm-online-2011-with-odata-and-wcf.html. I have explained about CRM online and establishing connection with CRM 2011 online.

Now, I am going to explain about, Establishing connection with CRM 2011 On-Premise.

There is only one difference is that, here no need to pass device id credentials while creating proxy. Also instead of passing windows live credentials, we have to pass domain login id and password.

So, I have listed some of the basic differences between CRM 2011 online  Vs CRM 2011 On-Premise.




                                            Microsoft Dynamics CRM 2011 Online    Microsoft Dynamics CRM 2011 On-Premise

Robust marketing, sales,
 and
customer service features         Yes                                                   Yes

Integration with MS Office         Yes                                                   Yes

Customizations                        Yes                                                    Yes

Storage limit                            5 GB                                                  Unlimited

Database restore to
 certain date                           Not available                                       Allowed

Full Database export                No                                                     Yes

Offline synchronization with
 Outlook                                Yes                                                     Yes


Mobile device GUI support       Yes                                                     Yes

Maximum amount of custom
entities                                  200                                                  Unlimited

Maximum amount of custom
 workflows                            200                                                   Unlimited


Login Must use                     Windows LiveID                                  Domain Login


Minimal commitment            12 months                                         No

Payment method Monthly by
                                         credit card                                        Based on agreement



aravindbenator@gmail.com

Wednesday, October 5, 2011

Claims based authentication(Basic details)

In this article, I am trying to explain some basics about new claims based authentication with live scenario.

Fisrt of all,  What are authentication methods are available?

ASP.NET when launched supported 3 types authentications namely: Windows Authentication(better for Intranet scenarios and credentials are stored inside Active Directory), Passport Authentication (Now Live ID Authentication, can be used via Claims Based Authentication) & FBA(where user data is maintained inside SQL Database). ASP.NET 2.0 provided some tools and classes and made FBA much more simpler. It automatically created required tables, stored procs, UI to manage Users (Membership Providers), their access rules by their roles (Role Provider) and store some more data about users (Profile Provider).


In the Microsoft world, authentication is usually performed by Active Directory. I claim to be Arvind, and i prove this to Active Directory by providing my password. Other systems don’t trust me, they trust Active Directory. Active Directory gives systems a bit of data that says “yeah, I personally know this person. It really is Aravind.”

In single environment Claims based authentication is not needed.

But, Privacy regulations are impacting what kind of information capture and store about user. Because, in some case user don’t want to give his personal info.

And one more case is that, In case of merging two sites, then if both are having different authentication type, then it becomes a mess.

In this case, if claims based authentication has implemented, then it can handle both with a common method.

Scenario:


Suppose, I am having liquor online shop purpose to sell liquor direct to the customer. So my company service is to provide imported liquor to customer’s hand without any intermediate. I am having one website called myliquor.com. So customer can place his order over the net. But According to Law of Indian government, liquor should not sell to the people whose age is lesser than 18.


But, I don’t know whether the person who is placing order is eligible or not. So what I will do is, I will ask to government to provide some identity (token) that will ensure about customers age. Consider I will use the voter id login service from the government. So that it can tell the age of a customer.

By doing this, No need to maintain customer’s personal information for me. Also No need to check the age eligibility for me.


Best Example: while using the CRM 2011 online, we have use windows live id. Here CRM online get tokens from windows live.



There are several components to claims authentication. The STS(identity provider) that issues the tokens to entities. An application makes decision by consuming these tokens.


In between, identity provider and application there is a federation provider manages trusts for application and translates token containing claims in such a way that application can understand.

In next article, i will explain how do we set claims based authentication.

Tuesday, October 4, 2011

Style for HTML file control( making fake)



It is very easy to change the HTML  file control.  It is bit difficult make changes  input control style. So i achieved by making fake control inside the div as shown bellow.

div.fileinputs {


position: relative;

}



div.fakefile {

position: absolute;

top: 0px;

left: 0px;

z-index: 1;

}



input.file {

position: relative;

text-align: right;

-moz-opacity:0 ;

filter:alpha(opacity: 0);

opacity: 0;

z-index: 2;

}

Implementation is here...................................




 
You can set either image  or even button control to invoke click operation.

Thursday, September 29, 2011

CRM online 2011 with Odata and WCF

Hi guys, I have strugled a lot with working on CRM 2011 online. It has killed my two day's. Oh!!  It might be beacause of my low brain or subject :) :)
Any how I am able to manage to get data from CRM 2011 online.  In my previous blog, I have explained about basics about CRM 2011.

Now, I am going to explain how do we access CRM 2011 online data using services.

CRM 2011 Online


1. Register for CRM 2011 Online using Windows Live ID.
You can get it here: http://crm.dynamics.com/en-us/home

Available services in CRM 2011.

CRM can allow multiple Organizations to be created on 1 CRM installation.

Each Organization can be for a different company/purpose. So, users may want to access one of the Organizations on CRM installation. If the user/code already knows the Organization URL OR Organization Service URL then fine he can directly use organization service.

If not known, then he needs to write code to connect Discovery Service URL, then browse through all Organizations available and get Organization service URL for respective/required Organization.
In short, whatever Data/Metadata operations we want to do, we will need to use Organization Service URL.
If we want to find Organization Service URL for an Organization, then we need to do that using Discovery Service URL.

https://dev.crm.dynamics.com/XRMServices/2011/Discovery.svc (North America)


https://dev.crm4.dynamics.com/XRMServices/2011/Discovery.svc (EMEA)


https://dev.crm5.dynamics.com/XRMServices/2011/Discovery.svc (APAC)


The following URLs should be used to access the Organization service(SOAP endpoint):


https://{Organization Name}.api.crm.dynamics.com/XrmServices/2011/Organization.svc (North America)

https://{Organization Name}.api.crm4.dynamics.com/XrmServices/2011/Organization.svc (EMEA)

https://{Organization Name}.api.crm5.dynamics.com/XrmServices/2011/Organization.svc (APAC)

Where {Organization Name} refers to the Organization that you specify in the URL when accessing the Web application. For example, for Contoso.crm.dynamics.com, the {Organization Name} is Contoso.

The following URLs should be used to access the Organization Data service(OData REST endpoint)

https://{Organization Name}.api.crm.dynamics.com/XrmServices/2011/OrganizationData.svc (North America)


https://{Organization Name}.api.crm4.dynamics.com/XrmServices/2011/OrganizationData.svc (EMEA)


https://{Organization Name}.api.crm5.dynamics.com/XrmServices/2011/OrganizationData.svc (APAC)



For CRM On-premises customers:



http://{server}/XRMServices/2011/Discovery.svc for the Discovery service endpoint


http://{server}/{OrgName}/XRMServices/2011/Organization.svc for the Organization Service endpoint (SOAP)


http://{server}/{OrgName}/XRMServices/2011/OrganizationData.svc for the Organization Data Service endpoint (REST)


http://{server}/XRMDeployment/2011/Deployment.svc for the Deployment Service endpoint



2.Install Microsoft Dynamics CRM 2011 SDK.

You can get it here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=eb9c345f-e830-40b8-a5fe-ae7a864c4d76&displaylang=en

3. Run the DeviceRegistration.exe utility to generate a device id and password.

There are two methods to get device id and password.

1.Using DiviceMAnager class available in SDK folder. So that we can generate device id and password.

2.By Commandline.

Once you download SDK from above given link, Inside tools, there will deviceregistration directory. Run it with command line /operation:Register.

Then you will get device id and password. Copy these credentials for further use.

4.Making context class for the organization.svc or discovery service.

C:\Users\aravinda.sheshadri\Desktop\ToolkitGestureDemo\sdk\bin\crmsvcutil.exe /codeCustomization:"Microsoft.Xrm.Client.CodeGeneration.CodeCustomization, Microsoft.Xrm.Client.CodeGeneration" /url:https://<>.crm5.dynamics.com/XRMServices/2011/Organization.svc /o:crm.cs /n:XXXCRM2011 /domain:<>.crm5.dynamics.com /u:<> /p:<>/serviceContextName:XXXcontext /di:116bohmbs2iupfaxp07bp5mhrp /dp:GYfG8LSo%_+3H2H+mpT~w=IG

On run this command, class will be generated containing all entities(context). Here, I have given context name as XXXcontext. So I can access all entities using XXXcontext name.

While running this command, make sure that time in both server and local machine will be same(Time and Timezone).

5. Add this class file to your visual studio 2010 project.



6.Add a reference to the dll’s in there as necessary from SDK folder bin directory:



Microsoft.XRM.sdk

System.ServiceModel

Microsoft.Crm.Sdk.Data.Services;

System.Data.Services.Client;

System.ServiceModel.Description;

Microsoft.Xrm.Sdk;

Microsoft.Xrm.Sdk.Client;

Microsoft.Crm.Services.Utility;

7. How do I access CRM 2011 online wcf service over .net client?



If we are using organization.svc, then we have to use



OrganizationServiceProxy _serviceProxy;

IOrganizationService _service;

ClientCredentials Credentials = new ClientCredentials();

ClientCredentials devivceCredentials = new ClientCredentials();

CRMContext context;



Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;



//This URL needs to be updated to match the servername and Organization for the environment.





Uri OrganizationUri = new Uri("https://{organization name}.crm5.dynamics.com/XRMServices/2011/Organization.svc");



Uri HomeRealmUri = null;



//To get device id and password.



devivceCredentials= DeviceIdManager.LoadDeviceCredentials();





using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, devivceCredentials))

{

serviceProxy.ClientCredentials.UserName.UserName = "username";

serviceProxy.ClientCredentials.UserName.Password = "password";

serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

IOrganizationService service = (IOrganizationService)serviceProxy;

_service = (IOrganizationService)serviceProxy;

context = new CRMContext(_service);

var querry = context.CreateQuery("LeadSet");

var querry1 = from itm in context.LeadSet

select itm;





}


8. Odata(OrganizatationData.svc) is not supported outside the CRM application.

Currently CRM 2011 does not support for Odata(organizationdata.svc) to do any operation from outside the CRM application. So If we make it as web resources, then we can use Odata services.







Proof:

http://mscrmblogger.com/2011/05/12/crm-2011-supported-vs-unsupported/
http://mscrmblogger.com/2011/05/12/crm-2011-supported-vs-unsupported/

http://msdn.microsoft.com/en-us/library/gg334279.aspx

“The REST Endpoint for Web resources provides an alternative interface to work with Microsoft Dynamics CRM data. You can use the REST endpoint to execute HTTP requests by using a service that is based on a Uniform Resource Identifier (URI). The REST endpoint is only available for use by JScript and Silverlight Web resources.”

Thanks


Aravind
aravindbenator@gmail.com