Thursday, July 5, 2012

Request for the permission of type "System.DirectoryServices failed"


I created a ssrs report with custom dll execution. The custom dll would retrieve the active directory groups of the report user. Code of custom dll function was:

// Get groups of user with specific prefix and extract the store information
public static List GetStoresSecurity(string groupprefix, string userName)
{
List result = new List();
// establish domain context
PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain);
// find your user
UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, userName);
// if found - grab its groups
if (user != null)
{
PrincipalSearchResult groups = user.GetAuthorizationGroups();
// iterate over all groups
foreach (Principal p in groups)
{
// make sure to add only group principals
if (p is GroupPrincipal)
{
if (p.Name.StartsWith(groupprefix))
{
result.Add(p.Name.Replace(groupprefix, ""));
}
}
}
}
return result;
}

When I deployed the report I added to rssrvpolicy.config the following permission assign (ReportFunctions.dll contains my function):

<CodeGroup>

class="UnionCodeGroup"
version="1"
PermissionSetName="FullTrust"
Name="Report Functions"
Description="This code group grants full permissions to directory functions ">
class="UrlMembershipCondition"
version="1"
Url="C:\Program Files\Microsoft SQL Server\MSRS10_50.R2\Reporting Services\ReportServer\bin\ReportFunctions.dll"
/>
</CodeGroup>

When I tried to execute the report I got the error: Request for the permission of type "System.DirectoryServices failed". This was a permission error and the way I found to overpass it was to give full trust to .net assemblies. The way to do this was to edit again rssrvpolicy.config and make the following change:

<CodeGroup>

class="UnionCodeGroup"
version="1"
PermissionSetName="FullTrust"
Name="Report_Expressions_Default_Permissions"
Description="This code group grants default permissions for code in report expressions and Code element. ">
class="StrongNameMembershipCondition"
version="1"
PublicKeyBlob="0024000004800000940000000602000000240000525341310004000001000100512C8E872E28569E733BCB123794DAB55111A0570B3B3D4DE3794153DEA5EFB7C3FEA9F2D8236CFF320C4FD0EAD5F677880BF6C181F296C751C5F6E65B04D3834C02F792FEE0FE452915D44AFE74A0C27E0D8E4B8D04EC52A8E281E01FF47E7D694E6C7275A09AFCBFD8CC82705A06B20FD6EF61EBBA6873E29C8C0F2CAEDDA2"
/>
</CodeGroup>

Tuesday, May 29, 2012

Remotely Working and Debugging SharePoint 2010 Solutions

How to remotely debug a custom webpart on sharepoint 2010? The task is not easy but if its absolutely necessary for your project then you should follow the steps analyzed in this article. If the solution provided for remote debugging is too hard then you can always install visual studio on the same machine as sharepoint, to avoid all the trouble...

Friday, May 25, 2012

Timeout expired on Dynamics CRM 4.0

Today I got a timeout expired error when calling a query to dynamic crm (from web service). I saw the query from trace and I when I executed it from sql server it elapsed 31 seconds. The problem was that the default timeout of sql queries in Microsoft Dynamics CRM 4.0 is 30 seconds.
This timeout can be overriden from registry by adding a DWORD value with the timeout time in seconds to the following registry key:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSCRM\OLEDBTimeout]

Good reference of timeout specifications can be found here

Tuesday, May 22, 2012

Pass multivalue parameter to drillthrough report


Recently I had a request to create a drillthrough report for an aging report (actually 5 reports). I had 2 choices. One to create 5 reports or two to make one with multivalue parameters (each one of the parent reports must pass different values witch were static). Of course I decided to follow the second option. In order to do that I created the desired parameter in the parent report and I set it as multivalue and as internal.



Next I set the available values, and I set the same values and as defaults




Finally on the textbox witch I wanted to trigger the drillthrough action I inserted the parameter (OrderStatus is a multivalue parameter of the drillthrough report)




The text exression of the parent parameter was



Running Unit Tests From Network Drive

I used visual studio 2010 to create some unit tests for a custom application and I got the following error message "Error loading U:\Visual Studio 2010\Projects\LoyaltyViewer\LoyaltyViewerTest\bin\Debug\LoyaltyViewerTest.dll: Could not load file or assembly 'file:///U:\Visual Studio 2010\Projects\LoyaltyViewer\LoyaltyViewerTest\bin\Debug\LoyaltyViewerTest.dll' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)". I googled the problem and what I found what the problem was. It appeared that visual studio could not load the assembly from a remote drive. To fix the problem, I followed the instructions from this post. The workaround is to create set COMPLUS_LoadFromRemoteSources=1.


Open a command prompt and type "setx COMPLUS_LoadFromRemoteSources 1"

or

Create an environment variable named COMPLUS_LoadFromRemoteSources
Set the value to 1

Tuesday, December 28, 2010

Custom Isv.Config behavior based on User Security Roles

In Microsoft Dynamics CRM we can embed our custom solution throw sitemap, isv.config and iframe. If we want to have a custom behavior in isv.config based on User Security Roles we can inject javascript to do that.

Here is a custom button on toolbar that has custom javascript inside isv.config:

 
<ToolBar ValidForCreate="0" ValidForUpdate="0">
  <Button Icon="/_imgs/ico_16_1013.gif" ValidForCreate="0" 
ValidForUpdate="0" PassParams="1" WinMode="0" JavaScript="…………">
    <Titles>
      <Title LCID="1033" Text="Export To CSV" />
    </Titles>
      <ToolTips>
      <ToolTip LCID="1033" Text="Export To CSV" />
    </ToolTips>
  </Button>
</ToolBar>


 
Inside javascript we want a function to return all roles of a specific user by creating s SOAP message request:

//*********************
function GetCurrentUserRoles()
{
 var xml = "" +
 "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
 "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
 " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
 GenerateAuthenticationHeader() +
 " <soap:Body>" +
 " <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
 " <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
 " <q1:EntityName>role</q1:EntityName>" +
 " <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
 " <q1:Attributes>" +
 " <q1:Attribute>name</q1:Attribute>" +
 " </q1:Attributes>" +
 " </q1:ColumnSet>" +
 " <q1:Distinct>false</q1:Distinct>" +
 " <q1:LinkEntities>" +
 " <q1:LinkEntity>" +
 " <q1:LinkFromAttributeName>roleid</q1:LinkFromAttributeName>" +
 " <q1:LinkFromEntityName>role</q1:LinkFromEntityName>" +
 " <q1:LinkToEntityName>systemuserroles</q1:LinkToEntityName>" +
 " <q1:LinkToAttributeName>roleid</q1:LinkToAttributeName>" +
 " <q1:JoinOperator>Inner</q1:JoinOperator>" +
 " <q1:LinkEntities>" +
 " <q1:LinkEntity>" +
 " <q1:LinkFromAttributeName>systemuserid</q1:LinkFromAttributeName>" +
 " <q1:LinkFromEntityName>systemuserroles</q1:LinkFromEntityName>" +
 " <q1:LinkToEntityName>systemuser</q1:LinkToEntityName>" +
 " <q1:LinkToAttributeName>systemuserid</q1:LinkToAttributeName>" +
 " <q1:JoinOperator>Inner</q1:JoinOperator>" +
 " <q1:LinkCriteria>" +
 " <q1:FilterOperator>And</q1:FilterOperator>" +
 " <q1:Conditions>" +
 " <q1:Condition>" +
 " <q1:AttributeName>systemuserid</q1:AttributeName>" +
 " <q1:Operator>EqualUserId</q1:Operator>" +
 " </q1:Condition>" +
 " </q1:Conditions>" +
 " </q1:LinkCriteria>" +
 " </q1:LinkEntity>" +
 " </q1:LinkEntities>" +
 " </q1:LinkEntity>" +
 " </q1:LinkEntities>" +
 " </query>" +
 " </RetrieveMultiple>" +
 " </soap:Body>" +
 "</soap:Envelope>" +
 "";
 
 var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
 xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
 xmlHttpRequest.setRequestHeader("SOAPAction"," http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
 xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
 xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
 xmlHttpRequest.send(xml);
 
 var resultXml = xmlHttpRequest.responseXML;
 return(resultXml);
}
//*********************

Then we need a function to check if specified user has specified role:

//*********************
function UserHasRole(roleName) {
    //get Current User Roles, oXml is an object
    var oXml = GetCurrentUserRoles();
    if (oXml != null) {
        //select the node text
        var roles = oXml.selectNodes("//BusinessEntity/q1:name");
        if (roles != null) {
            for (i = 0; i < roles.length; i++) {
                if (roles[i].text == roleName) {
                    //return true if user has this role
                    return true;
                }
            }
        }
    }
    //otherwise return false
    return false;
}
//*********************

Finally we have the actual code for button. Our intention is to check if a user has a specific security role (by name) and if he has it, to restrict him from making executing the action of button.
 
if(!UserHasRole("No CSV Export"))
{
  // OK pass and go to custom solution for making the export
  window.open('/ISV/CRMISVCustoms/ExportToCSV.aspx?orgname=' + ORG_UNIQUE_NAME,'ExportCSV','width=500,height=200,resizable=yes');
}
else
{
   // Not authorized
   alert('You are not authorized to Export in csv');
}


Monday, December 13, 2010

Microsoft Dynamics CRM limits export to 10000 rows to Excel

Our customer is making lists of contacts to send then in third parties for process. The number of contacts in those list can be larger than 50000. When we made an export to excel we saw that only 10000 contacts where exported. It turned out that there was a limitation in the organization database for exporting only 10000 rows from excel. The solution was easy. We changed the limit value from sql server (table OrganizationBase field MaxRecordsForExportToExcel). The query was:

update OrganizationBase set
      MaxRecordsForExportToExcel = 65500

After the query we made a restart of iis and everything worked.

Thursday, December 2, 2010

The E-mail Router service could not run the service main background thread

Well I found in a Microsoft Dynamics CRM 4.0 rollup 10 with email router (on-premise) deployment that the email router service was stopped. I tryed to start the service and I couldn' t. I looked at event viewer and I found this log:

#16192 - The E-mail Router service could not run the service main background thread. The E-mail Router service cannot continue and will now shut down. System.Configuration.ConfigurationErrorsException: The E-mail router service cannot access system state file Microsoft.Crm.Tools.EmailAgent.SystemState.xml. The file may be missing or may not be accessible. The E-mail Router service cannot continue and will now shut down. ---> System.Xml.XmlException: Root element is missing.
   at System.Xml.XmlTextReaderImpl.Throw(Exception e)
   at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
   at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
   at System.Xml.XmlDocument.Load(XmlReader reader)
   at System.Xml.XmlDocument.Load(String filename)
   at Microsoft.Crm.Tools.Email.Providers.ConfigFileReader..ctor(String filePath, ServiceLogger serviceLogger)
   at Microsoft.Crm.Tools.Email.Providers.SystemState.Initialize(ServiceLogger serviceLogger)
   at Microsoft.Crm.Tools.Email.Agent.ServiceCore.InitializeSystemConfiguration()
   --- End of inner exception stack trace ---
   at Microsoft.Crm.Tools.Email.Agent.ServiceCore.InitializeSystemConfiguration()
   at Microsoft.Crm.Tools.Email.Agent.ServiceCore.ExecuteService()

After some search I found here that file Microsoft.Crm.Tools.EmailAgent.SystemState.xml was corrupted. I deleted the file and started the email router service.

Tuesday, November 30, 2010

Change max publish duplicate detection rules

We have an on premise CRM 4.0 rollup 10 deployment, and our client have requested a number of duplicate detection rules upon leads. We started the development of the rules but when we tried to publish then the system informed us that only 5 rules where allowed per entity.

After some googling we found a solution to our problem. In MSCRM_CONFIG database table DeploymentProperties witch holds the constraint of max 5 rules per entity. With a simple query and a full restart of IIS – CRM Asynchronous Service we were able to publish more than 5 rules.

The query for max 7 duplicate detection rules was:

update DeploymentProperties set
      IntColumn = 7
where ColumnName = 'DupMaxPublishedRules'

The above solution is not supported by Microsoft and can cause serious performance issues, but in our case (the number of leads is relatively small) we didn’t have any problem.

Monday, November 8, 2010

Deserialization failed: The 'DataType' attribute is not declared

I faced the above problem when I tried to open a report in Visual Studio 2008. I had edited the report many times in the past and I don’t know what caused the problem. In my opinion it must be a bug of the report builder of Visual Studio 2008. I opened the xml definition of the report and compared it with a version of the report witch was working. The difference can be found below.

Working xml

      <ValidValues>
        <ParameterValues>
          <ParameterValue>
            <Value>-1</Value>
            <Label>Less Than</Label>
          </ParameterValue>
          <ParameterValue>
            <Value>0</Value>
            <Label>Equal</Label>
          </ParameterValue>
          <ParameterValue>
            <Value>1Value>
            <Label>Greater Than</Label>
          </ParameterValue>
        </ParameterValues>
      </ValidValues>

Not working xml

      <ValidValues>
        <ParameterValues>
          <ParameterValue>
            <Value DataType="Integer">-1</Value>
            <Label>Less Than</Label>
          </ParameterValue>
          <ParameterValue>
            <Value DataType="Integer">0</Value>
            <Label>Equal</Label>
          </ParameterValue>
          <ParameterValue>
            <Value DataType="Integer">1</Value>
            <Label>Greater Than</Label>
          </ParameterValue>
        </ParameterValues>
      </ValidValues>


I removed the DataType attribute and everything worked fine

Thursday, November 4, 2010

Sql2k8 (x64) fails on PassPidBackFromComponentUpdate 0x80070006 (E_HANDLE)

We were trying to install sql server 2008 from an MSDN subscription and we got an error message 0x80070006 (E_HANDLE). After some googling we found that is a MSDN bug and the solution to the problem was in the product key selection to simply select the "Specify a free edition" radio button without changing the shown PID, then reselect the "Enter the product key" radio button (again without changing the PID). That was crazy... The original post of the solution can be found here.

Monday, October 25, 2010

User ID assosiated with the current record is not valid

We had a CRM 4 rollup 10 installation in a on premise deployment and we tried to make an image of the deployment and change the name of the computer. At the end of the procedure we couldn’t login to the original server and the server returned the following message User ID associated with the current record is not valid.
Well the problem that caused this message was that the machine principal in active directory had become invalid. We fixed the problem be making the following steps:
1. We detached the server machine from the domain and we made sure that the principal of the server was deleted from AD.

2. We attached again the machine to AD.

3. We added the newly created machine principal to the following crm security groups: PrivReportingGroup, SQLAccessGroup and PrivUserGroup (CRM security groups of deployment)

After that we were able to login again:-)

Tuesday, June 1, 2010

How to iterate on Tablix rows?

I have implemented a custom renderer for sql server 2005 in order to send direct information from a report to Microsoft Dynamics CRM. When they announced me that I have to port the solution to sql server 2008 I encountered the following problems:

1. The namespace have been changed from

Microsoft.ReportingServices.ReportRendering;

to

Microsoft.ReportingServices.OnDemandReportRendering;

2. Control Table did not exist and had been replaced with Tablix. The iteration of table rows was easy, and I have implement it like this

Table table = reportItem as Table;

for (int j = 0; j < table.DetailRows.Count; j++)
{
    TableDetailRowCollection tableDetailRow = table.DetailRows[j];
    for (int k = 0; k < tableDetailRow.Count; k++)
    {
       
    }
}

But the Tablix control does not work like this. In order to iterate through the tablix rows I implemented the following code

Tablix table = reportItem as Tablix;                                               

int pos = -1;
foreach (TablixMember memberDef in table.RowHierarchy.MemberCollection)
{
    pos++;
    if (memberDef.IsStatic)
        continue;
    TablixDynamicMemberInstance instance = (TablixDynamicMemberInstance)memberDef.Instance;
    instance.ResetContext();
    while (instance.MoveNext())
    {
        foreach (TablixCell tableCell in table.Body.RowCollection[pos])
        {
            if (tableCell.CellContents.ReportItem is TextBox)
            {
                ...
            }
        }                               
    }
}

Tuesday, May 11, 2010

Finally Microsoft Dynamics NAV 2009 sp1 released for Greece

Finally the long waited greek localization of Microsoft Dynamics NAV 2009 sp1 has been released. It can be found at microsoft partnersource:

https://mbs.microsoft.com/partnersource/downloads/releases/microsoftdynamicsnav2009sp1.htm?printpage=false

For existing installations you have to look at the localized folder of dvd. The path is

DVD\Installers\GR\

and contains all the localized versions of the clients, servers, documentation, and outlook plug-in.

Saturday, April 24, 2010

installation of cab was unsuccessful on HP 214

Well I was trying to install a simple cab in my pocket pc hp 214 and I was getting the annoying message installation of cab was unsuccessful. I searched in google for hours, I found some intresting articles about security and deployment in pocket pc devices like http://www.codeproject.com/KB/mobile/signcode.aspx, but my problem was not solved. So I started building the cab from the ground up, and I noticed that even empty it couldn' t be deployed. After a lot I found the source of the problem. The property value of Manufacturer was http://www.netserve.gr (as I originally wanted) but this name was not valid for deployment (I still dont know why).

I changed property to www.netserve.gr and the cab deployed successfully to the device.

Thursday, April 15, 2010

Crm Integration Using SSIS

A common situation in Microsoft Dynamics CRM is to integrate data from a foreign system. In order to do that we must read data from the external source and import then using custom rules inside CRM using the webservice. An easy approach is to use SQL integration services. The tricky part of this approach is how to consume the CRM web service inside Ingration Services. The article below shows an easy way to do that.

http://blogs.msdn.com/crm/archive/2008/05/07/integrating-crm-using-sql-integration-services-ssis.aspx

Tuesday, April 6, 2010

How to retrieve GUID of current Active Directory user

If you want to find the guid of current active directory user write the code below to a windows host file and execute it

' NameTranslate constants
Const ADS_NAME_INITTYPE_GC = 3
Const ADS_NAME_TYPE_NT4    = 3
Const ADS_NAME_TYPE_GUID   = 7




' Determine the NetBIOS name of the domain and the NT name of the current user.
Set objNet = WScript.CreateObject("WScript.Network")
strNT4Name = objNet.UserDomain & "\" & objNet.UserName


' Use the NameTranslate object to convert the NT user name to the GUID
Set objNameTranslate = WScript.CreateObject("NameTranslate")


' Initialize NameTranslate by locating the Global Catalog.
objNameTranslate.Init ADS_NAME_INITTYPE_GC, ""


' Use the Set method to specify the NT format of the object name.
objNameTranslate.Set ADS_NAME_TYPE_NT4, strNT4Name


' Use the Get method to retrieve the GUID string.
WScript.Echo objNameTranslate.Get(ADS_NAME_TYPE_GUID)

Problem after deleting Active Directory User Account

I found my self in a strange situation after disabling a user from Microsoft Dynamics CRM 4.0 and the deleting the user from Active Directory. I couldn’t enable again the user because there was no Active Directory User associated with it. I tried many solutions to bypass this problem but they did not worked for me. The only solution that worked was to remove the company from the deployment (I made a backup first, just in case) and then I import the same company. When importing a company Microsoft Dynamics CRM 4.0 make new associations of crm users with active directory users, so I matched the disabled user with a new account of active directory.

Tuesday, March 30, 2010

Different sorting on Temporary and Normal Tables in Navision

Last week I had a problem with a client witch was that the export of dimensions on analysis view was wrong. After a lot of research I found the following detail. Navision sorting on Code field is different when the table is normal and when the table is temporary.

Lets say that we have a table with a key field (ID => Code 10). If we insert into table values ‘1000’, ‘1000-1’, ‘1001’ and we open the table we will see the following sorting

1000
1000-1
1001








If we create then a form with SourceTableTemporary = Yes on form properties









and insert the same values, the sorting will be like this

1000
1001
1000-1


Friday, March 26, 2010

Error Reinstalling CRM 4.0

The following error occurred when trying to reinstall MS Dynamics CRM 4.0. The problem is that the uninstall process of CRM does not make a complete removal of all the security principals from the system.



In order to make a proper uninstall of Microsoft Dynamics CRM 4.0 product, I followed the steps below:


1. I made the uninstall of all crm products from add/remove programs


2. I deleted all contents of crm directory. Mine was ‘C:\Program Files\Microsoft Dynamics CRM’


3. From Active Directory I removed all the crm principals




Principals in you deployment may be placed on other folder in Active Directory depending of the installation you have made


4. From Sql Server I made a backup and then a delete of all crm databases (*_MSCRM, *_CONFIG)
5. From Sql Server I removed all the crm principals





6. I deleted CRM registry settings HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSCRM (I had a trace flag on, and a language pack)

After all this I made a brand new installation without any problem.


This post help me to come with this solution