Thursday, November 17, 2011

The list is too large to save as a template. The size of a template cannot exceed 524288000 bytes.

Error:         The list is too large to save as a template. The size of a template cannot exceed 524288000 bytes. 

Limitation: There is Soft limit for List Template is 50 MB.
                 You can modify using below command :
                 stsadm -o setproperty -propertyname max-template-document-size -propertyvalue 50000000 
                 But this is hard limit to 500MB so we can't save list template more then 500MB size.

Resolution: You can move document using Explorer window but there is also one limitation (can't move metadata) 


Happy SharePointing...!!!

Tuesday, November 15, 2011

SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER

Requirement:  Migrate Data from Access to SQL Server.

So I have to create SSIS Package in SQL Server and I developed on SSIS Package in SQL Server.
All connection managers are fine but when I try to deploy its give me below error.

Error: [OLE DB Source [43]] Error: SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER. The AcquireConnection method call to the connection manager "Access Source Database1" failed with error code 0xC0209303. There may be error messages posted before this with more information on why the AcquireConnection method call failed.


Resolution: Open SSIS Package in Visual Studio > Right Click on Project > Click on Property of your project > Then select "Debugging" node from left side > See the "Run64bitRuntime" property it will be "True" so change it to "False"
Then Deploy again... it will be work...


Happy Migrating...!!!

Thursday, November 10, 2011

Cannot serialize interface System.Collections.Generic.IEnumerable in Web Service

I have faced this problem in one of my project.

I have to create WebMethod that will get some data from CRM 2011 and return that to the client.
My code is return generic types in WebMethods but I couldn't use non-generic IEnumerable as well.
So I have to change this IEnumerable to Array as below.

Older Code which is not working 
[WebMethod]
public List ReadEntityList()
{
     List lstCRMEntity = new List();
     //Write code here
     return lstCRMEntity;
 }
Working code is below
[WebMethod]
public CRMEntity[] ReadEntityList()
{
     List lstCRMEntity = new List();
     //Write code here
     return lstCRMEntity.ToArray();
 }

Happy Coding...!!!

Microsoft SharePoint is not supported with version 4.0.30319.239 of the Microsoft .Net Runtime

SharePoint 2010 does not support access from .NET Framework 4 or being run in a .NET Framework 4 app domain.

Solution :
If you must support the .NET Framework 4, we recommend that you develop a web service that uses the .NET Framework 4 and then connect to it from SharePoint.

Limitation:
All server-side customizations directly for SharePoint 2010 still need to be either the .NET Framework 3.5 or the .NET Framework 3.5 SP1.

You can't directly give the reference of assembly which has run time framework is 4.0.


Happy SharePointing...!!!

Tuesday, October 25, 2011

Using HTTPContext object Redirect Page from EventHandler

We need to display custom page redirection after adding list item.
We have to implement Synchronous event handler for above list because we can get HttpContext in Synchronous event handler & redirect to custom page using SPUtility.Redirect method.
See the below code for redirect custom page after adding list item. 
public class SyncEventReceiver : SPItemEventReceiver
    {
        HttpContext current;

        public SyncEventReceiver() { current = HttpContext.Current; }

        /// 
        /// An item is being added.
        /// 
        public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);

            SPSite oSite = new SPSite(properties.SiteId);
            SPWeb oWeb = oSite.OpenWeb(properties.RelativeWebUrl);
            SPList oList = oWeb.Lists[properties.ListId];

            //Set Enable Event Firing to False for disable reoccurence of events.
            this.EventFiringEnabled = false;
            
            SPListItem newItem = oList.Items.Add();
            //add item to list (you can add custom code here)
            newItem["Title"] = properties.AfterProperties["Title"].ToString();
            newItem.Update();

            //Set Enable Event Firing to True
            this.EventFiringEnabled = true;

            //redirect it to your new destination like newly provisioned sub site or any other page you want.
            SPUtility.Redirect("http://localhost/pages/default.aspx", SPRedirectFlags.Default, current);

        }

}
Happy Coding...!!!

Difference between Synchronous and Asynchronous events

Synchronous Events

  - Fire “before” the actual events
  - You can get HttpContent
  - You can display error message
  - You can cancel the event.
  - Synchronous methods ending with “ing” like itemadding, itemupdating itemdeleting.




Asynchronous Events
  - Fire “after” the actual events
  - You cannot get HttpContent
  - You cannot display error message
  - You cannot cancel the event
  - Asynchronous methods ending with “ed” like itemadded, itemupdated, itemdeleted etc.


Happy Coding...!!!

Thursday, October 20, 2011

Size limitation in MOSS 2007

SharePoint Object's Size limitation in MOSS 2007  

SharePoint Object                                                     Limits   
Site collections in a web application                      50,000

Sites in a Site collection                                    250,000
Sub-sites nested under a Site                                2,000
Lists on a Site                                                     2,000
Items in a List                                              10,000,000
Items in View                                                      2,000
Field Type in a list                                                  256
Documents in a Library                                    2,000,000
Documents in a Folder                                           2,000
Maximum document file size              2GB (by default 50MB)
Documents in an Index                                   50,000,000
Search Scopes                                                     1,000
Search Scopes in a Site                                           200
User Profiles                                                   5,000,000
Template size                                   10,000,000 (default)


Happy SharePointing...!!

Thursday, October 13, 2011

Identify Worker Process (w3wp.exe) in IIS 6.0 and IIS 7.0 for Debugging in SharePoint

It is very deficult to identify perticular SharePoint web application's worker process in IIS 6.0 and 7.0 because there are somy web aplication running on SharePoint Farm.


How to attach worker process?
we can go to Tools > Attach Process or use shortcut key Ctrl +P.
 Identify Worker Process in IIS 6.0

  • Start > Run > Cmd
  • Go To Windows > System32
  • Run cscript iisapp.vbs
You will get the list of Running Worker ProcessID and the Application Pool Name in IIS 6.0.


Identify Worker Process in IIS 7.0
From IIS 7.0 you need you to run IIS Command Tool ( appcmd ) .
  • Start > Run > Cmd
  • Go To Windows > System32 > Inetsrv
  • Run appcmd list wp
This will show you list worker process that is running on IIS 7.0 in the similar format of IIS 6.0

Happy Debugging...!!!

Sunday, September 18, 2011

SharePoint Security Trimming Control

SPSecurityTrimmedControl is very useful to security trimming on page’s control level not a whole page.
So using this control you can trim security as per below



// Your control here








Member name


Description
EmptyMaskHas no permissions on the Web site. Not available through the user interface.
ViewListItemsView items in lists, documents in document libraries, and view Web discussion comments.
AddListItemsAdd items to lists, add documents to document libraries, and add Web discussion
comments.
EditListItemsEdit items in lists, edit documents in document libraries, edit Web discussion comments
in documents, and customize Web Part Pages in document libraries.
DeleteListItemsDelete items from a list, documents from a document library, and Web discussion
comments in documents.
ApproveItemsApprove a minor version of a list item or document.
OpenItemsView the source of documents with server-side file handlers.
ViewVersionsView past versions of a list item or document.
DeleteVersionsDelete past versions of a list item or document.
CancelCheckoutDiscard or check in a document which is checked out to another user.
ManagePersonalViewsCreate, change, and delete personal views of lists.
ManageListsCreate and delete lists, add or remove columns in a list, and add or remove public
views of a list.
ViewFormPagesView forms, views, and application pages, and enumerate lists.
OpenAllow users to open a Web site, list, or folder to access items inside that container.
ViewPagesView pages in a Web site.
AddAndCustomizePagesAdd, change, or delete HTML pages or Web Part Pages, and edit the Web site using
a SharePoint Foundation–compatible editor.
ApplyThemeAndBorderApply a theme or borders to the entire Web site.
ApplyStyleSheetsApply a style sheet (.css file) to the Web site.
ViewUsageDataView reports on Web site usage.
CreateSSCSiteCreate a Web site using Self-Service Site Creation.
ManageSubwebsCreate subsites such as team sites, Meeting Workspace sites, and Document Workspace
sites.
CreateGroupsCreate a group of users that can be used anywhere within the site collection.
ManagePermissionsCreate and change permission levels on the Web site and assign permissions to users
and groups.
BrowseDirectoriesEnumerate files and folders in a Web site using Microsoft Office SharePoint Designer
2007 and WebDAV interfaces.
BrowseUserInfoView information about users of the Web site.
AddDelPrivateWebPartsAdd or remove personal Web Parts on a Web Part Page.
UpdatePersonalWebPartsUpdate Web Parts to display personalized information.
ManageWebGrant the ability to perform all administration tasks for the Web site as well as
manage content. Activate, deactivate, or edit properties of Web site scoped Features
through the object model or through the user interface (UI). When granted on the
root Web site of a site collection, activate, deactivate, or edit properties of
site collection scoped Features through the object model. To browse to the Site Collection Features page and activate or deactivate site
collection scoped Features through the UI, you must be a site collection administrator.
UseClientIntegrationUse features that launch client applications; otherwise, users must work on documents
locally and upload changes. 
UseRemoteAPIsUse SOAP, WebDAV, or Microsoft Office SharePoint Designer 2007 interfaces to access
the Web site.
ManageAlertsManage alerts for all users of the Web site.
CreateAlertsCreate e-mail alerts.
EditMyUserInfoAllows a user to change his or her user information, such as adding a picture.
EnumeratePermissionsEnumerate permissions on the Web site, list, folder, document, or list item.
FullMaskHas all permissions on the Web site. Not available through the user interface.

Click here for more detail. 

Happy Coding !!!

Thursday, July 7, 2011

Visual Upgrade in SharePoint 2010

There so many ways to Visual Upgrade Migrated SharePoint Site.
One of this is run power shell script from SharePoint 2010 Management Shell.

All Site Collection Upgrade under Single Web Application as below command
    $webapp = Get-SPWebApplication http://UIVersion3WebApps/
    foreach ($s in $webapp.sites)
    {$s.VisualUpgradeWebs() }


Site Collection Upgrade including All Sub Webs as below command
    $site = Get-SPSite http://UIVersion3SiteCollection/
    foreach ($web in $site.AllWebs){$web.UIVersion = 4;$web.Update();}

Only Site Collection Web Upgrade without All Sub Webs as below command
    $site = Get-SPSite http://UIVersion3SiteCollection/
    $site.VisualUpgradeWebs()

Only Single Web Upgrade as below command
    $web = Get-SPWeb http://UIVersion3SiteCollection/site
    $web.UIVersion = 4;
    $web.Update();


Happy Upgrading !!!

Friday, July 1, 2011

MOSS 3.0 to SharePoint 2010 Migration

MOSS 3.0 to SharePoint 2010 Migration

  1. Take a Content Database backup from MOSS 3.0 DB Server.
  2. Restore it in SharePoint 2010 DB Server.
  3. Add Restored Database in SP 2010 existing Web Application.
  4. Remove older Content Database (which created with web application creation time)
  5. Move all related files from MOSS 3.0 to SP 2010 farm. Ex. – Customization (Features, User Controls, Web Parts, Custom Application Pages, and Timer Jobs etc.), Third Party controls etc.
  6. Run PreUpgradeCheck Power Shell script from SharePoint 2010 Management Shell (I will we back with new post)
  7. After successfully run this command browse you site it should be working with UI Version 3.0.
  8. For SharePoint 2010 look & feel you have to change UI Version 4.0 (Visual Upgrade see my new post).

Happy Migration !!!

Wednesday, June 29, 2011

Free PDF Viewer for Microsoft SharePoint 2010 Content Editor Web Part

You can configure PDF Viewer in you Content Editor Web Part easily.
1. Add Content Editor Web Part in you Page.
2. Add Below HTML code in this
 
3. Save Page then Display like below.

Happy Coding !!!

Friday, April 29, 2011

Access FBA SharePoint site using web service

You can access any site collection programmatically   as below code 
You have to use Authentication.asmx web service for authenticate any user.
Then you can access any lists of this site.

// /_vti_bin/Authenticate.asmx web service's Object
            Authentication.Authentication objAuthentication = new Authentication.Authentication();
            objAuthentication.CookieContainer = new System.Net.CookieContainer();
            LoginResult loginResule = objAuthentication.Login("username", "password");

            if (loginResule.ErrorCode == LoginErrorCode.NoError)
            {
                CookieCollection objCookieCollection = objAuthentication.CookieContainer.GetCookies(new Uri(objAuthentication.Url));
                Cookie authCookie = objCookieCollection[loginResule.CookieName];
                
                // /_vti_bin/Lists.asmx web service's Object
                Lists.Lists objLists = new Lists.Lists();
                objLists.CookieContainer = new CookieContainer();
                objLists.CookieContainer.Add(authCookie);

                System.Xml.XmlNode objListXMLNode = objLists.GetList("Shared Documents");
            }

Happy Coding !!!

Wednesday, March 16, 2011

The request failed. The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

I tried to retrive data from Exchange Server 2010 using Exchange API 1.0 but below error fire

Error:
The request failed. The underlying connection was closed: Could not establish trust relationship  for the SSL/TLS secure channel.

Solution:
Add below code before access web service
ServicePointManager.ServerCertificateValidationCallback += delegate(object sender,
                X509Certificate certificate,
                X509Chain chain,
                SslPolicyErrors sslPolicyErrors)
            {
                return true;
            };
This Error occur when you access Secure Web Service.

Happy Coding !!!

Friday, March 11, 2011

Begin/End Async WebService Proxy Methods Not Generated in Web Application Projects

Last week I worked with Web Method's Async call from Application page on button click.


One more interesting thing, this web method takes more than 15 min to complete migrate data so End User will not sit front off screen.

Due to that reason I had to implement Async web service call.

As per my knowledge I can call Async web method using Begin-End Proxy method but this is limited for Web Site and SharePoint's application page is create using Web Application Project.

So it is difficult to implement in my Web Application Project. Then after some research & googling I found one solution from Microsoft Team.

Solution:
Open Web Application Project's .csproj file in note pad & Add below property in PropertyGroup Tag





... 

true





Then save .csproj file & update you web service in Web Application Project.


Now you can see the Begin/End Proxy methods in web application Project.

Reference here.

Happy Coding !!!

Thursday, March 10, 2011

Using SharePoint Feature Receiver create Virtual Directory in IIS

As per my previous post you create virtual directory from command line.
Here another way to create virtual directory in IIS site.
Everything is possible programmatically.
I created one SharePoint Feature to create virtual directory in IIS’s SharePoint site.




string _serverName = string.Empty;
string _userName = string.Empty;
string _password = string.Empty;
string _webSiteName = string.Empty;
string _physicalPath = string.Empty;

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
try
{
SPWeb tempweb;
SPSite tempsite;

if (properties.Feature.Parent is SPWeb)
{
tempweb = properties.Feature.Parent as SPWeb;
tempsite = tempweb.Site;
}
else
{
tempsite = properties.Feature.Parent as SPSite;
tempweb = tempsite.RootWeb;
}

GetWebServiceParamFromConfig(tempweb.Url);
if (!_serverName.Equals(string.Empty) && !_userName.Equals(string.Empty) && !_password.Equals(string.Empty) && !_webSiteName.Equals(string.Empty) && !_physicalPath.Equals(string.Empty))
{
string webSiteId = GetIISWebsiteID(_serverName, _webSiteName);

String strRootSubPath = "/W3SVC/" + webSiteId + "/Root";

String strSchema = "IIsWebVirtualDir";

DirectoryEntry objRootDirectoryEntry = new DirectoryEntry("IIS://" + _serverName + strRootSubPath);
objRootDirectoryEntry.Username = _userName;
objRootDirectoryEntry.Password = _password;
objRootDirectoryEntry.RefreshCache();
DirectoryEntry objNewVDir = objRootDirectoryEntry.Children.Add("CustomWebService", strSchema);
objNewVDir.Properties["Path"].Insert(0, _physicalPath);
objNewVDir.CommitChanges();
deRoot.CommitChanges();

objNewVDir.Invoke("AppCreate", true);

objNewVDir.CommitChanges();
objRootDirectoryEntry.CommitChanges();
objNewVDir.Close();
deRoot.Close();
}
else
{
Utility.ErrorLog("During WebService Vir. Dir. Create in IIS - Param. Empty", System.Diagnostics.EventLogEntryType.Error, "CreateWebServiceVirDir - FeatureActivated()");
}
}
catch (Exception ex)
{
Utility.ErrorLog("Error during WebService Vir. Dir. Create in IIS - " + ex.Message, System.Diagnostics.EventLogEntryType.Error, "CreateWebServiceVirDir - FeatureActivated()");
}
}

public void GetWebServiceParamFromConfig(string webUrl)
{
DataSet ds = GetDataFromList(webUrl);
DataTable dtWebServiceParam = ds.Tables["WebService"];

if (dtWebServiceParam != null && dtWebServiceParam.Rows.Count > 0)
{
_serverName = dtWebServiceParam.Rows[0]["ServerName"].ToString();
_userName = dtWebServiceParam.Rows[0]["Username"].ToString();
_password = dtWebServiceParam.Rows[0]["Password"].ToString();
_webSiteName = dtWebServiceParam.Rows[0]["WebSiteName"].ToString();
_physicalPath = dtWebServiceParam.Rows[0]["PhysicalPath"].ToString();
}
}

public string GetIISWebsiteID(String server, String websiteName)
{
DirectoryEntry w3svc = new DirectoryEntry("IIS://" + server + "/w3svc");
String webId = "";
foreach (DirectoryEntry de in w3svc.Children)
{
if (de.SchemaClassName == "IIsWebServer" && de.Properties["ServerComment"][0].ToString() == websiteName)
{
webId = de.Name;
}
}
return webId;
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
try
{
SPWeb tempweb;
SPSite tempsite;

if (properties.Feature.Parent is SPWeb)
{
tempweb = properties.Feature.Parent as SPWeb;
tempsite = tempweb.Site;
}
else
{
tempsite = properties.Feature.Parent as SPSite;
tempweb = tempsite.RootWeb;
}

GetWebServiceParamFromConfig(tempweb.Url);

if (!_serverName.Equals(string.Empty) && !_userName.Equals(string.Empty) && !_password.Equals(string.Empty) && !_webSiteName.Equals(string.Empty) && !_physicalPath.Equals(string.Empty))
{
string webSiteId = GetIISWebsiteID(_serverName, _webSiteName);
String strRootSubPath = "/W3SVC/" + webSiteId + "/Root";
String strSchema = "IIsWebVirtualDir";
DirectoryEntry objRootDE = new DirectoryEntry("IIS://" + _serverName + strRootSubPath);
objRootDE.Username = _userName;
objRootDE.Password = _password;
objRootDE.RefreshCache();
DirectoryEntry deChild = new DirectoryEntry("IIS://" + _serverName + strRootSubPath + "/CustomWebService");
objRootDE.Children.Remove(deChild);
}
else
{
Utility.ErrorLog("During WebService Vir. Dir. Delete from IIS - Param. Empty", System.Diagnostics.EventLogEntryType.Error, "CreateWebServiceVirDir - FeatureDeactivating()");
}
}
catch (Exception ex)
{
Utility.ErrorLog("Error during WebService Vir. Dir. Remove from IIS - " + ex.Message, System.Diagnostics.EventLogEntryType.Error, "CreateWebServiceVirDir - FeatureDeactivating()");
}

}


Happy Coding !!!

Create virtual directory using command prompt

If you can’t access IIS Manager (INet Manager) & want to create virtual directory then run below command for create virtual directory.
There is one Window Script File for Manage Virtual Directory IISVDir.vbs located in C:\Windows\System32\iisVdir.vbs
To Create Virtual Directory run below
Iisvdir /create “IIS Web Site Name” VirtualDirName C:\PhysicalLocation


Wednesday, February 16, 2011

Access web.config in SharePoint timer job

I want to access the web application configuration (web.config) file in the SharePoint timer job. But, the limitations in SharePoint can't access the configuration files in timer job.

SharePoint web application or site will run with the help of process 'W3WP.EXE'.
SharePoint timer job is running in different process named 'OWSTIMER.EXE'.
So, the application configuration file is associated with the W3WP.EXE, so there is no way to access the web.config file in the owstimer.exe process at all. The context is completely different and out of domain. So, we need to call or access the web.config file explicitly in timer job.

So add below code in Execute() method to access ConnectionString in Timer JOB.


SPWebApplication webApplication = this.Parent as SPWebApplication;
Configuration config = WebConfigurationManager.OpenWebConfiguration("/", webApplication.Name);
_ConnString = config.ConnectionStrings.ConnectionStrings["ConnectionName"].ConnectionString.ToString();


Happy Coding !!!

Tuesday, February 1, 2011

The Report Viewer Web Control HTTP Handler has not been registered in the application's web.config file.

The Report Viewer Web Control HTTP Handler has not been registered in the application's web.config file.




Add below TAG in web.config's HttpHandler




Remove below TAG from AppSettings




Happy Coding !!!

Wednesday, January 19, 2011

Save multiple choice values in SharePoint ListItem

You will find that your checkbox list is populated with the selected value.
Save selected checkboxes in the list item as below



SPFieldMultiChoiceValue multiValue = new SPFieldMultiChoiceValue();
foreach (ListItem item in multiValueInputFormCheckBoxList.Items)
{
if (item.Selected) multiValue.Add(item.Value);
}
item["multivalued choice field name"]= multiValue;


Happy Coding !!!

Display multiple choice value of saved Listitem

Show those values which was stored in the SharePoint ListItem.
For display selected value use previous post’s “InputFormCheckBoxList”
Select listitem for display choice field’s multiple value as below



if (item["multivalued choice field name"] != null)

{

SPFieldMultiChoiceValue multiValue = new SPFieldMultiChoiceValue(item["multivalued choice field name"]);

for (int i=0; i<= multiValue.Count; i++) multiValueInputFormCheckBoxList.Items.FindByText(multiValue[i]).Selected = true; }


Happy Coding !!!

Bind SharePoint multiple choice field in custom form

Bind SharePoint multiple choice field in custom form.

You can bind sharepoint multiple choice value in sharepoint check box list control for display Choice field values.
Add SharePoint “InputFormCheckBoxList” and bind as below code.


ASPX Design Code:




Use below code to populate the choice column values in above control.
Server Side CS Code:

// -------------- Populate CheckBox List
SPField multiValueCheckBoxField = objSPList.Fields["multivalued choice field name"];
SPFieldMultiChoice multiValueCheckBoxChoicesField = (SPFieldMultiChoice) multiValueCheckBoxField ;

// for each loop for values add in checkbox list
foreach (string choiceValue in multiValueCheckBoxChoicesField.Choices)
{
this.multiValueInputFormCheckBoxList.Items.Add(new ListItem(choiceValue, choiceValue));
}


Happy Coding!!!

Tuesday, January 18, 2011

Error occurred in deployment step 'Add Solution': Failed to extract the cab file in the solution.

Error Message: Error occurred in deployment step 'Add Solution': Failed to extract the cab file in the solution.

One day I tried to deploy Images in _layouts folder using VS 2010. But I couldn't deploy Images because above error message fired in VS2010's error window. After half and hour I found one file named with blue_button (2).gif and renamed with blue_button.gif and deploy solution. Its working fine.

Resolution: To work around this problem, remove any parentheses in the names of SharePoint project items.

This link help me to solve the problem http://msdn.microsoft.com/en-us/library/ee330922.aspx.

Happy Coding !!!

Saturday, January 8, 2011

Programmatically set Picklist Option value in CRM Entity Item

In my older post I have collect Picklist options in DropDownList.
So now I save this DropDown’s selected value in CRM’s Entity Item’s Attribute.
You can’t save option in Entity Item, without picklist’s Value & Text. Means you have to provide Option’s Value & Options Text.
Also you have to create a new instance of the picklist before setting the value.
See the below sample code snippet for set the picklist option value.


CrmSdk.new_customentity newcustomentity = new CrmSdk.new_customentity();//Custom Entity's obj

newcustomentity.new_entityattribute = new CrmSdk.Picklist();//Creating New Instance before assign Value & Text
newcustomentity.new_entityattribute.Value = Convert.ToInt32(objDropDownList.SelectedItem.Value); //Set DropDownList's Value
newcustomentity.new_entityattribute.name = objDropDownList.SelectedItem.Text;//Set DropDownList's Text


Happy Coding!!!

Programmatically Getting CRM Entiry Picklist Option value

Whenever use picklist in CRM Entity’s Attribute you have to collect all picklist options in any collections like ArrayList, HashTable OR controls like DropDownList, ListBox etc. for display Options in UI.
For collecting Picklist Options you have to use CRM’s MetaDataService.asmx as older Post.
See the below sample code snippet for collect picklist options.




RetrieveAttributeRequest request = new RetrieveAttributeRequest();//Create Obj for RetrieveAttributeRequest

request.EntityLogicalName = CrmSdk.EntityName.new_crmcustomentity.ToString();//Assign CRM's Custom Entity

request.LogicalName = "new_customattribute";//Set Obj's Picklist Attribute Name



//Now collect entity's response using Metadataservice execution

RetrieveAttributeResponse response = (RetrieveAttributeResponse)service.Execute(request);//service is MetaDataService.asmx's object

//collect Picklist Attribute Metadata value

PicklistAttributeMetadata picklist = (PicklistAttributeMetadata)response.AttributeMetadata;



//here I use DropDownList for collecting PickList Options

foreach (Option o in picklist.Options)

{

objDropDownList.Items.Add(new ListItem(o.Label.UserLocLabel.Label, o.Value.Value.ToString()));

}


In my Next Post you will see how to set Picklist Option in CRM Entity Item from Custom UI.

Happy Coding !!!

Thursday, January 6, 2011

Programmatically Create MS CRM Account

Using CRM SDK4.0 you can customize CRM programmatically.
Download CRMSDK 4.0 from here
http://www.microsoft.com/downloads/en/confirmation.aspx?FamilyID=82e632a7-faf9-41e0-8ec1-a2662aae9dfb&displaylang=en
Then add web service reference in your project
Example:
http://CrmApplicationUrl/MSCRMServices/2007/CrmService.asmx
Also you have to pass below Items in CRM Code.
- Organization Name

- Username, Password & Domain (CRM Credential)
See the below function code for CRM Account Creation.




public static void createAccount(string NewAccountName)
{
CrmSdk.CrmService myCrm = new CrmSdk.CrmService();
myCrm.Url = "http://CrmApplicationUrl/MSCRMServices/2007/CrmService.asmx";

CrmSdk.CrmAuthenticationToken myCrmToken = new CrmSdk.CrmAuthenticationToken();
myCrmToken.AuthenticationType = 0;
myCrmToken.OrganizationName = GetCrmOrganization();//"OrganizationName";

myCrm.CrmAuthenticationTokenValue = myCrmToken;

System.Net.NetworkCredential nc = new System.Net.NetworkCredential();
nc.UserName = "Username";//Pass Username of CRM
nc.Password = "Password";//Pass Password of above CRMAccount
nc.Domain = "Domain";//Pass Domain name

myCrm.Credentials = nc;
CrmSdk.account newAccount = new CrmSdk.account();

newAccount.name = NewAccountName;
Guid newAccountId = myCrm.Create(newAccount);
}



Happy coding !!!