System.Net.WebException the request failed with HTTP status 401: Unauthorized.” Source=”System.Web.Services”

Hi,

I was gettng this error when trying to call the crm’s webservice from my asp.net page

The resolution for this is putting the following code in the web.conig

i.e. enable impersonation and deny anonymous access

<authentication mode=”Windows” />
<identity impersonate=”true”/>
<authorization>
<!–Deny all unauthenticated users–>
<deny users=”?”/>
</authorization
>

Bye

Advertisements

Programmatically uploading and setting permission to a document in a document library in SharePoint

We can use the following code for uploading a document to document library.

// create a filestream object and open an existing file for reading its contents

FileStream oFileStream = File.OpenRead(@”C:\G.doc”);

byte[] content = new byte[oFileStream.Length];

// store the contents in a byte array

oFileStream.Read(content, 0, (int)oFileStream.Length);

oFileStream.Close();

// create an SPSIte object

using (SPSite objSite = new SPSite(“http://d-1246&#8221;))

{

// get reference to the web application or web site

using (SPWeb objWeb = objSite.OpenWeb())

{

// get reference to the document library. Proposal – name of the document library

SPFolder mylibrary = objWeb.Folders[“Proposal”];

objWeb.AllowUnsafeUpdates = true;

// add the file to the document library and update it

SPFile myFile = mylibrary.Files.Add(“MyProposal.doc”, content, true);

mylibrary.Update();

// get the reference to the file just uploaded as a SPListItem for setting permissions

SPListItem myListItem = myFile.Item;

// HasUniqueRoleAssignments – returns false if it inherits permission from parent else true

myListItem.HasUniqueRoleAssignments.ToString());

// BreakRoleInheritance – breaking role inheritance so that we can define our own permissions

myListItem.BreakRoleInheritance(false);

// webroledefinitions – Full Right, Design, Contribute and Read

SPRoleDefinitionCollection webroledefinitions = objWeb.RoleDefinitions;

// group – different groups created in that site

SPGroup group = objWeb.SiteGroups[“MyGroup”];

SPRoleAssignment roleassignment = new SPRoleAssignment(group);

roleassignment.RoleDefinitionBindings.Add(webroledefinitions[“Design”]);

myListItem.RoleAssignments.Add(roleassignment);

// same for the user as well

SPUser user = objWeb.SiteUsers[@”domainname\username”];

SPRoleAssignment roleassignment1 = new SPRoleAssignment(user);

roleassignment1.RoleDefinitionBindings.Add(webroledefinitions[“Full Control”]);

myListItem.RoleAssignments.Add(roleassignment1);

}

}

Bye

Delete a SSP (Shared Service Provider)

To delete a SSP we need to do the following in the cmd prompt

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN> stsadm -o deletessp -title “shared service name” -deletedatabases

For deleting default ssp first we need to delete all the web application associated with it or associate them with some other shared services !!

CRM 4.0 – Exception: Unhandled Exception: System.Net.WebException: The request failed with HTTP status 401: Unauthorized.

Hi,

I was facing this error when i was writing a plugin that was using CrmService.

After searching on internet i found out this

The problem was because Friendly name and Organization name were different.

The solution for it was

1. Launch Deployment Manager on the Web server
2. Select the Organization, Right Click -> Disable
3. RightClick Again and Click Edit Organization
4. Change the Organization Name and FriendlyName to be the same
5. Click Next and Finish.

solution

Bye

Invalid action error-Microsoft Dynamics CRM 4.0

I was getting the Invalid Action error when trying to open Microsoft CRM 4.0.

And in the event log i could see the following entry.

Event Type:    Error
Event Source:    MSCRMKeyGenerator
Event Category:    None
Event ID:    18949
Date:        6/11/2008
Time:        4:59:35 PM
User:        N/A
Computer:    D-4526
Description:
Current active key (KeyType : CrmWRPCTokenKey) is expired.  This can indicate that a key is not being regenerated properly.  Current Active Key : CrmKey(Id:6e254808-b21d-dd11-9041-001d7d22e1af, ScaleGroupId:00000000-0000-0000-0000-000000000000, KeyType:CrmWRPCTokenKey, Expired:True, ValidOn:05/09/2008 10:23:58, ExpiresOn:06/11/2008 10:23:58, CreatedOn:05/09/2008 10:23:58, CreatedBy:NT AUTHORITY\NETWORK SERVICE.  Key Setting :

Starting the Microsoft CRM Asynchronous Processing Service on the server solved the problem for me!!!

There was an error downloading ‘http://localhost/…./Service.asmx’. The request failed with HTTP status 503: Service Unavailable.

I was receiving this error when I was trying to add web reference to the webservice which was deployed in our server from inside our Visual Studio.

 

But putting the same url in the IE, everything seemed to work fine. So there was no issue of IIS not running.

 

Later I realized that the issue was because of the a software that I was using Ultrasurf (UltraSurf is the flagship software product from UltraReach Internet Corp. for Internet anti-censorship. It enables users inside countries with heavy Internet censorship to visit any public web sites in the world safely and freely.)

 

But even after closing the UltraSurf the problem persisted. I restarted the system, cleared my system using CCleaner but wasn’t able to solve the problem.

 

Finally this is something I tried and it worked for me

 

I went to Tools Internet Options Connections (tab) LAN Settings for IE

 

In the LAN settings dialog box, checkbox Bypass Proxy Server for local addresses was checked so I unchecked it than clicked OK two times to close both the dialog boxes.

 

Then again went to Tools Internet OptionsConnections (tab) LAN Settings

And in the LAN setting dialog box again checked it.

 

This way I was able to resolve the issue of not being able to add web reference to web services from inside Visual Studio.

 

 

 

 

 

 

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly ‘Microsoft.Crm.Sdk….’

I created a simple plugin and when I was trying to register the plugin through the plugin registration tool I was getting the follwing error

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly ‘Microsoft.Crm.Sdk, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ or one of its dependencies. The system cannot find the file specified.

at System.Reflection.Assembly._GetExportedTypes()

at System.Reflection.Assembly.GetExportedTypes()

at PluginRegistrationTool.AssemblyReader.RetrievePluginsFromAssembly(String path) in C:\Documents and Settings\arvinds1\Desktop\PluginRegistration\AssemblyReader.cs:line 59

at PluginRegistrationTool.AssemblyReader.RetrievePluginsFromAssembly(String path)

at PluginRegistrationTool.RegistrationHelper.RetrievePluginsFromAssembly(String pathToAssembly) in C:\Documents and Settings\arvinds1\Desktop\PluginRegistration\RegistrationHelper.cs:line 49

at PluginRegistrationTool.PluginRegistrationForm.btnLoadAssembly_Click(Object sender, EventArgs e) in C:\Documents and Settings\arvinds1\Desktop\PluginRegistration\PluginRegistrationForm.cs:line 127

 

The way I resolved the issue was by adding the microsoft.crm.sdk.dll to my machine’s GAC !!

I hope it works for others as well !!!

Many to many relationship in CRM 4.0 and Fetch XML

We have a custom entity called line of business (lob) for different line of business’s in our organization.

In CRM 3.0 there was no way we could have associated the lob custom entity with the system entity Team as there was no way of creating relationship between them.

But in CRM 4.0 we can now create a many to many relationship between the two.

Creating a many to many relationship between the two creates a new entity

new_team_new_lineofbusiness

Now say we want to write a custom code to retrieve all the teams associated with a given line of business, we can write something like below ( If we use query expression and retrieve multiple request it gives the error message saying that RetrieveMultiple is not supported on this entity)

This is the custom code for that

// setting the authentication token

CrmAuthenticationToken token = new CrmAuthenticationToken();

// 0- refers active directory

token.AuthenticationType = 0;

token.OrganizationName = “organizationname”;

 

CrmService crmService = new CrmService();

crmService.Url = http://servername/mscrmservices/2007/CrmService.asmx&#8221;;

crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;

crmService.CrmAuthenticationTokenValue = token;

 

string fetch2= @”<fetch mapping=’logical’>

<entity name=’new_team_new_lineofbusiness’>

<attribute name=’teamid’ />

<filter>

<condition attribute=’new_lineofbusinessid’ operator=’eq’ value=’C4BE129E-9B3C-DB11-8CBA-001185E68627′ />

</filter>

</entity>

</fetch>”;

 

// Fetch the results.

try

{

String result2 = crmService.Fetch(fetch2);

MessageBox.Show(result2);

XmlDocument doc = new XmlDocument();

doc.LoadXml(result2);

XmlNodeList xnodlist = doc.GetElementsByTagName(“teamid”);

string teamID = “”;

if (xnodlist.Count != 0)

{

for (int i = 0; i < xnodlist.Count; i++)

{

XmlNode xnodRoot = xnodlist.Item(i);

teamID = xnodRoot.InnerText;

}

}

}

catch (SoapException ex)

{

MessageBox.Show(ex.Detail.InnerText);

}

Bye

Only the owner of an object can revoke the owner’s access to that object

Hi,

We had written a callout for auto sharing and unsharing of opportunity’s record for postassign event.

On creation of the record we were auto sharing the record with the owner’s manager.

On change of the owner we are first unsharing the record with the owner’s manager and sharing it with new owner’s manager.

While doing this the error we are receiving  is  this

“Only the owner of an object can revoke the owner’s access to that object “

This error is  coming in this particular scenario

say we have a record shared with a particular user say A

now when we are trying to set the new owner as A what the code is trying to do is that,

it is trying to unshare the record with A  this is the point where we receiving this  error!!!

For e.g.

Lead record is owned by User A and is Shared with User A.

Now the Revoke code is running in context of User B and tries to run Revoke for User A who is the owner. We will get this error message.

Bye..

Microsoft Dynamics CRM 3.0 and Microsoft Dynamics CRM 4.0 differences

Multiple organizations can now be hosted and WSDL APIs are now unique per organization.

 

The metadata API service has been extended to retrieve language information.

 

Plug-ins (callouts) and workflow now use the same event framework, allowing for even more extensibility.

 

The SDK has been expanded to include offline access.

 

Now we can programmatically create, read, update and delete the metadata such as entities, attributes and relationship.

 

There are three services instead of two which we used to have in previous version

 

CrmService – http://<crmserver>/mscrmservices/2007/crmservice.asmx

MetadataService – http://<crmserver>/mscrmservices/2007/metadataservice.asmx

DiscoveryService – http://<crmserver>/mscrmservices/2007/ad/crmdiscoveryservice.asmx

 

Previously to write callout we had to reference the follwing assembly

 

Microsoft.Crm.Platform.Callout.Base.dll

 

Instead now we have to reference these assemblies

 

  • Micorsoft.Crm.Sdk.dll
  • Micorsoft.Crm.SdkTypeProxy.dll
  • Micorsoft.Crm.Outlook.Sdk.dll

 

 

Now we can to settings and can then select customizations there we have the option of

Download Web Service Description File.

 

There we can find wsdl files for both CrmService and MetadataService which we can download to our machine and can the simply add web reference to them.

 

 

Previously to access and use the CrmService following lines of code were enough

 

CrmService service=new CrmService();

service.Url=// url for the CrmService

service.Credentials=System.Net.CredentialCache.DefaultCredentials;

 

But now because of the multiple organization support we need to write the following lines of code to identify the organization for which we are writing our custom solution.

 

CrmAuthenticationToken token = new CrmAuthenticationToken();

token.AuthenticationType = 0;

            // 0- Active Directory

            // 1- Microsoft Dynamics CRM Live

            // 2- Internet-Facing deployment (IFD)

token.OrganizationName=“”;// name of the organization

 

CrmService service=new CrmService();

service .Url=// url for the CrmService            service.Credentials=System.Net.CredentialCache.DefaultCredentials;

service.CrmAuthenticationTokenValue = token;

 

 

We have to access the Metadataservice in the similar manner i.e. creating CrmAuthenticationToken and assigning it to CrmMetadataService’s CrmAuthenticationTokenValue.

 

In 3.0 version we could use Metadataservice to access metadata information about any specific entity however in the new version following things are possible

 

  • Creating a customentity.
  • Add or update an attribute for an entity.
  • Create or delete a relationship between two entities.
  • Add or remove an option from a picklist attribute and few others.

 

 

  // CrmDiscoveryService Web service can provide a list of organizations and their corresponding Web service

 // endpoints URL’s. We will use it to configure the CrmService and MetadataService Web service proxies.

           

  CrmDiscoveryService discService = new CrmDiscoveryService();

  discService.UseDefaultCredentials = true;

  discService.Url = http://localhost/MSCRMServices/2007/AD/CrmDiscoveryService.asmx&#8221;;

 

  // Retrieve the list of organization

RetrieveOrganizationsRequest orgRequest = new    RetrieveOrganizationsRequest();

RetrieveOrganizationsResponse orgResponse =(RetrieveOrganizationsResponse) discService.Execute(orgRequest);

 

// Loop through the list to locate the target organization

 

OrganizationDetail orgInfo = null;

foreach (OrganizationDetail orgDetail in orgResponse.OrganizationDetails)

{

if (orgDetail.OrganizationName == “OurOrganizationName”)

    {

          orgInfo = orgDetail;

          break;

    }

}

 

After obtaining the organization details, we can then access the CrmService and MetadataService Web Services to perform our business logic.

 

 

References :

Working with Microsoft Dynamics CRM 4.0 (Microsoft Press)