Friday, May 10, 2013

Updating an existing worksheet in Microsoft Dynamics NAV

In our last week’s blog we went through the process of generating a report into a new excel file. Click here to view on how to print reports in excel
The article below will show us on how to export values into an existing worksheet/workbook. This case is mostly applicable in scenarios where we don’t want to create new files every time when we generate a report.
The following scenario explains us where we already have a worksheet and we need to use the same excel workbook and use the worksheet that was previously used
A Sample image below indicates the existing excel book with existing sheet has some values:

How can we achieve this?
1.       Open the excel file by specifying the file path.
2.       Specify the excel sheet name.
3.       Clear the already existing contents.
4.       Export the values in the same worksheet
The following code drives the above steps:
//xlapp – Automation – Microsoft Excel 12.0 Object Library. Application
//xlbook – Automation – Microsoft Excel 12.0 Object Library. Workbook
//xlsheet – Automation – Microsoft Excel 12.0 Object Library. WorkSheet
//filepath – Text [1024]
 
Filepath:=’<Your Filepath>’; //Specify the location where the excel file is stored locally
IF ISCLEAR(xlapp) THEN
  CREATE(xlapp);
 
xlapp.visible(true);
 
//1. Opening the excel file
xlbook:=xlapp.Workbooks.Open(filepath);//specify your file path with the filename.xls(x)
 
xlbook:=xlapp.ActiveWorkbook;
 
//2. Specify the excel sheet name
xlsheet := xlbook.Worksheets.Item(‘<your Work Sheet Name>’);
 xlsheet.Activate();
 
//the below code will be useful when the excel sheet is already filtered based on some condition
// if it is filtered then we need to show all the data in the excel sheet.
 IF xlsheet.FilterMode THEN
    xlsheet.ShowAllData;
 
//3. Clearing the existing contents within worksheet
 xlsheet.Range(‘A1:C1048576’).ClearContents;
// Note: In this scenario we have specified C because we have only 3 columns and 1048576 denotes the max no of rows in excel 2007 and later
 
//4. Exporting the new values
xlsheet.Range(‘A1’).value:=’No.’; //1st Column Name
xlsheet.Range(‘B1’).value:=’Customer No; //2nd column Name
xlsheet.Range(‘C1’).value:=’Sales Person Code’; //3rd Column Name
 
//Exporting the sales header values
reccount:=2;   //where variable reccount - Integer
salesheader.RESET;  //where variable salesheadaer - Record - Sales Header var
IF salesheader.FINDSET THEN
REPEAT
  xlsheet.Range('A'+FORMAT(reccount)).Value:=salesheader."No.";
  xlsheet.Range('B'+FORMAT(reccount)).Value:=salesheader."Sell-to Customer No.";
  xlsheet.Range('C'+FORMAT(reccount)).Value:=salesheader."Salesperson Code";
  reccount:=reccount+1;
UNTIL salesheader.NEXT=0;
 
Xlbook.save;
 
After executing the code, the existing excel file will be opened automatically so that we can view the excel sheet with new/replaced values. The below image refers the values exported from a Sales Header table.
 
 

Thursday, May 9, 2013

Retrieve Linked Entity Data using Query Expression using MS CRM 2011 SDK


Most often you need to retrieve data from primary and related entity. This data can be retrieved using CRM SDK either with FetchXML or Query Expression.  In this blog, QueryExpression is used to retrieve primary and related entity data with a single database retrieve.
Below is the syntax of how related entity columns are retrieved.

Query Syntax:-

Parent Entity:-
var query = new QueryExpression(Entityname);
var columnNames = new[] { Columns to be Added };
query.ColumnSet = new ColumnSet(columnNames);

Linked Entity:-
var colsAccount = new[] { LinkEntity Columns to be Added }; // Related Entity Fields
LinkEntity linkentity = new LinkEntity() {
LinkFromEntityName = EntityName,
LinkFromAttributeName = EntityFieldName,
LinkToEntityName = LinkEntityName,
LinkToAttributeName = LinkEntityFieldName,
JoinOperator = JoinOperator.Inner,                        
Columns = new ColumnSet(colsAccount),
EntityAlias = AliasName
                        };
query.LinkEntities.Add(linkentity);
This sample shows how to retrieve related entities data using the RetrieveMultiple method using QueryExpression. The code returns columns from the primary entity Account as well as the firstname and lastname from associated Contact record.
Parent Entity:-

 var query = new QueryExpression("account");


 var columnNames = new[] { "fullname", "accountid" };


 query.ColumnSet = new ColumnSet(columnNames);


 query.Criteria.AddCondition("accountid", ConditionOperator.Equal, new Guid(<<ENTER GUID HERE>>));
Linked Entity:-

var colsAccount = new[] { "firstname", "lastname" };


                        LinkEntity linkEntityAccount = new LinkEntity()

                        {


                            LinkFromEntityName = "account",


                            LinkFromAttributeName = "primarycontact",


                            LinkToEntityName = "contact",


                            LinkToAttributeName = "contactid",


                            JoinOperator = JoinOperator.Inner,


                            Columns = new ColumnSet(colsAccount),


                            EntityAlias = "Contacts"


                        };


 query.LinkEntities.Add(linkEntityAccount);     
// Execute Query using RetrieveMultiple
//The RetrieveMultipleRequest is for returning multiple instances of a particular type of entity.
EntityCollection _results = _serviceproxy.RetrieveMultiple(query);
        if (_results != null)
             {
                foreach (var ent in _results.Entities)
               {
     // Display “First Name” along with Alias
     Console.WriteLine((ent.Attributes["Contacts.firstname"] as AliasedValue).Value);
     // Display “Last Name” along with Alias
     Console.WriteLine((ent.Attributes["Contacts.lastname"] as AliasedValue).Value);
                           
}
                        }
 
Hope, this is helpful!

Thanks!






Friday, May 3, 2013

How to Close Accounting Periods (Fiscal Year) In NAV 2013?


Closing Accounting Period in NAV 2013

Follow the Steps below to close a Fiscal Year/Accounting Period in NAV
  • Open the Accounting Periods window (Financial Management --> Setup--> Accounting Periods).

Click Close Year. If more than one fiscal year is open, the program assumes that the earliest one should be closed. It displays a message identifying the year it will close and explains the consequences of closing it.
 
  • To close the year, click Yes.
Now the fiscal year is closed, and the program places a check mark in the Closed and Date Locked fields for all the periods in the year. Now the fiscal year cannot be opened again and you cannot remove the check mark from the Closed or Date Locked fields.

 
The following are the most important points we need to follow on closing a Fiscal Year in NAV
  • You cannot close a fiscal year before you create a new fiscal period.
  • When a fiscal year is closed, you cannot change the starting date of the following fiscal year.
  • Even when a fiscal year has been closed, you are allowed to post G/L entries to it. When you do this, the entries will be marked as posted to a closed fiscal year - the Prior-Year Entry field will contain a check mark.
  • Once a fiscal year is closed, make sure you close the income statement accounts and transfer the year's results to an account in the balance sheet. You must repeat the process every time you post to the closed fiscal year.
 

How to configure Management Reporter reports to Sharepoint library???

In Management reporter 2012, we can deploy the reports directly to Sharepoint library. Below are the steps to configure the Management Reporter reports to Sharepoint library.

1. Open Sharepoint site in Internet Explorer.
2. In Home Page, click View All Site Content.
3. Click Create option.


4. Click Document Library.
5. Create a library.


6. Go to Library page and Click Settings.
7. Click Document Library settings.
8. Click Advanced settings in General settings section.


9. Select ‘Yes’ in Allow Management option.


10. Click Ok to save.
11. In Document Library setting page, Click Add from existing site content types (In content Types section).


12. Select "Link to a Document" in available Site Content Types.
13. Click Add and click OK.
14. Open SharePoint Central Administration.
15. Click Operations.
16. In Security Configuration section, click Blocked file types.


17. Remove the "Url" type in the list (Only if exists).


18. Close Central Administration.
19. Open Management Reporter report definitions in Report designer.
20. Go to Output and Distribution tab.
21. Type your Sharepoint library URL (Ex: http://servername/library name).
Note: If you select Generate to multiple report library locations then you have to enter library URL in Related Report link Location.


22. Click Save.
23. Now generate and check the reports in Sharepoint library.

Hope this helps!!!

Printing reports to Excel in Dynamics NAV

Generally we use reports to view the data and print the necessary information. There are cases wherein we will be required to export the report da into an Excel file and do a comparative study.

The steps below will take us through on how to export a report into an excel sheet
Consider the scenario wherein you already have a built in report (Ex: GL Transactions), now you need to export the data for a particular period to an excel sheet

What should I do ?
1.       Create a new Boolean Variable against the report you want to work with
2.       Design a request form like the below image

3.       Assign the Boolean Variable to the “SourceExpr” of the Check box.
4.       Save and Close the report.

The request page provides you an option like Print to Excel. If the Option is checked, the report will be printed to excel and if it is unchecked excel report will not be generated.
Note:               
Consider, if there is no need of previewing the report.  Then there is no need of request form. You can directly make the section’s visibility as False (“CurrReport.Showoutput(False)”) and “processingOnly” property of the report as “Yes”.
This enables the user to print the report to excel instead of previewing.


Coding:
We can use both excel buffer and automation server for exporting/print the report to excel.
·         The Report 108 in the standard NAV will guide you on using Excel Buffer functions.
·         For Automation Server I have given a sample code below for reference. This code will be executed when the Check Box (Boolean variable) in the request form is checked or selected

<SAMPLE CODE>

IF PrinttoExcel THEN //PrinttoExcel – Boolean variable

BEGIN

  IF ISCLEAR(xlapp) THEN  //xlapp – Automation – Microsoft Excel 12.0 Object Library.Application

    CREATE(xlapp);

  //Window – Dialog variable

  window.OPEN(Text001+'@1@@@@@@@@@@@@@@@@@@@@\');

  window.UPDATE(1,0);

  //xlbook – Automation – Microsoft Excel 12.0 Object Library.Workbook

  xlbook:=xlapp.Workbooks.Add;

  //xlsheet – Automation – Microsoft Excel 12.0 Object Library.WorkSheet

  xlsheet:=xlbook.Worksheets.Add;

  xlsheet.Name:='Budget Analysis';

  RowNo:=1; // Where RowNo as integer 

//Printing report Header – Specify the report column headers here

xlsheet.Range('A'+FORMAT(RowNo)).Value:= ‘Column XXXX’

xlsheet.Range('B'+FORMAT(RowNo)).Value:= ‘Column YYYY’

xlsheet.Range('C'+FORMAT(RowNo)).Value:= ‘Column ZZZZ’

  …….

//Printing report header

END;

Note: When using automation Server, we need to increment the Row no for each record in the data item.
Hope the information was useful.
 

Dynamics SL - 32 & 64 bit OS Support

Since Dynamics SL is a 32 bit code, running Dynamics SL from the program files of a 64-bit OS is not supported from earlier versions of SL till Dynamics SL 7.0 (both SP1 & SP2). However, the following versions of Dynamics SL are supported when program files are run on 64-bit OS.
  • Microsoft Dynamics SL 7.0 Feature Pack 1 (FP1)
  • Microsoft Dynamics SL 2011
  • Microsoft Dynamics SL 2011 Feature Pack 1 (FP1)
The below article explains the Dynamics SL compliance issues with the 32 & 64 bit OS machines during the various situations and given the workarounds.

1.      Fresh SL installation

  • C:\Program files (x86)\ is the location for 32-bit programs. Dynamics SL program files should be installed in this folder of 64 bit OS machine.
  • C:\Windows\SysWOW64\ is the location for the operating system's 32-bit binaries.  The Dynamics SL Swimapi.dll file and other necessary 32 bit *.dll files of Dynamics SL should be available in this folder.
2.      Server upgrade from 32 bit to 64 bit OS & Dynamics SL:

Need to copy the 32-bit dlls from C:\Windows\System32 of the 32 bit machine to C:\Windows\Syswows64 of 64 bit machine. Also the dll’s needs to be registered using the Regsvr64 command.

                     Regsvr64 "C:\windows\system64\xxxxxx.dll"

3.      Custom SL screen development in VS 2010 64 bit

If the SL custom form is developed in VS 2010 64 bit OS and running in 32 bit OS machine, the system will throw the “Stopped working” error message. Given below are the steps to correct this.
  1. Open Project in Visual Studio
  2. Select the Project Level in Project Explorer
  3. Right click mouse and select properties -> Click on Compile -> Advanced Compile Options
  4. Change Target CPU to x86 and click OK button.

Build the executable again and run in Dynamics SL.

Hope the post helps!! 

Thursday, May 2, 2013

How to map existing SharePoint folder link to other MS CRM records:


Microsoft Dynamics CRM 2011 has the capability of uploading documents to SharePoint from within MS CRM record. In SharePoint a folder gets created when a document is clicked in CRM record and the URL is saved within CRM. But we can also use the same URL path to link more CRM records such that single SharePoint folder can be mapped with many records in CRM

In some scenario, the user would like to main documents from CRM Parent/Child records into a same folder in SharePoint. This can be programmatically achieved by linking the records to a single path to SharePoint.

Microsoft Dynamics CRM internally uses the URL of the parent object to determine the absolute URL for the child object. In this example we are not going to create any folder to child record when documents is clicked but going to link an existing path to Child records.

Once you have the Parent record created in CRM and corresponding record has a folder in SharePoint. Then the following SDK code is used to create a SharePoint document location record.

 SharePointDocumentLocation spLocation = new SharePointDocumentLocation();

        spLocation.Name = "location1";

        spLocation.Description = "SharePoint Document Location created for storing documents related to accounts";
        
         //Specify integrated SharePoint information below.

  String sharePointDocumentUrl = "http://<<sharepointserverUrl>>:<<portnumber>>/<<sitename>>/<<existing folder path>>";

        //Set the Absolute URL as above defined valid path

        spLocation.AbsoluteURL = sharePointDocumentUrl;

        //set the RegardingobjectId in which record would like to show the existing SharePoint folder 

        spLocation.RegardingObjectId = new EntityReference(<<Entitylogicalname>>, <<entityId>>);

        _service.Create(spLocation);


Hope this was helpful!!!!