Unified Service Desk-Logging debugger content in excel

Hello Friends,

In this post, I’ll explain how you can get the content of debugger’s trace into your own excel file so that it can be scrutinized later, this is extremely helpful to find out production issues, when your users report of certain functionality not working correctly and you need to identify the root cause for the same.

 

Step -1 : Create a code based hosted control.

usd1

Step -2 : Override DoAction method. create a blank method “CreateAndOpenCsv“. You also have to create an action “GenerateLogs” in CRM for this hosted control. You can give any other name that you want. Replace that name in the if condition.

usd1

Step -3 : Now write following code for the method highlighted above.

/// <summary>
/// Creates the and open CSV.
/// </summary>
private void CreateAndOpenCsv()
{
if (!Directory.Exists(@”C:\Trace”))
{
Directory.CreateDirectory(@”C:\Trace”);
}

var filename = string.Format(@”C:\Trace\ActionLog_{0}.xls”, DateTime.Now.ToString(“MMddyyyyHHmmss”));
var sb = new StringBuilder();
var tableHeader = @”<table>
<th>Source</th>
<th>Name</th>
<th>Application</th>
<th>Action</th>
<th>Action Data</th>
<th>Parameter</th>
<th>Condition</th>
<th>Condition Result</th>
<th>Created</th>
<th>Duration</th>”;
sb.Append(tableHeader);

var tableRow = @”<tr border=’1′>
<td>{0}</td>
<td>{1}</td>
<td>{2}</td>
<td>{3}</td>
<td>{4}</td>
<td>{5}</td>
<td>{6}</td>
<td>{7}</td>
<td>{8}</td>
<td>{9}</td>
</tr>”;

foreach (var item in this.CRMWindowRouter.actionHistory)
{
sb.Append(string.Format(tableRow, item.Source, item.Name, item.Application, item.Action, item.ActionData, item.Parameters, item.Condition, item.ConditionResult, item.Created, item.Duration));
}

sb.Append(“</table>”);

try
{
File.WriteAllText(filename, sb.ToString());
MessageBox.Show(“File created successfully: ” + filename);
}
catch (Exception ex)
{
MessageBox.Show(“Error generating file: ” + ex.StackTrace);
}
}

 

Step -4 : Save this file and configure this Hosted control in CRM.

Step-5 : That’s all!! , now call you action (in this case CreateAndOpenCsv) from any button click etc. and you’ll have the entire trace copied to your C:\Trace directory.

 

Useful??

Watch out for more hacks :).

 

Writing on Unified Service Desk

Hello Friends,

It’s been 2 yrs since I wrote my last blog :(, anyways no point crying on split milk, I’ve decided to share my deep Unified Service Desk experience (gained in these 2yrs 😀 )  with the community. Hope it’ll be useful to many.

Thanks & Regards,

Shashank

CRM 2011 silverlight debugging on windows 7.

Hello Friends,

Debugging a silverlight control in CRM environment is quite easy, you need to follow these steps.

1. Make sure that you upload the latest xap file from your VS environment where you wan’t to debug the code.

2. Now, goto debug->attach to process -> find out the process where type is iexplore.exe,Silverlight (x86) and

 

THE PROBLEM :

What if you don’t find the iexplore.exe, Silverlight(x86) process, this might typically happen on a 64 bit windows 7 or any other OS.

Reason :

The reason is simple, you are running your code inside a 64bit IE , and not the 32bit IE.

Resolution :

The 32-bit IE can be found inside

“C:\Programe Files (x86)\ Internet Explorer\iexplore.exe”

now run your silverlight application inside this browser , and you can debug your silverlight code.

tfsobject.GetService<WorkItemStore> always returning null

Tags

, , , , , , ,

Hello Friends,

This blog is about an issue when you try to get the WorkItemStore of a tfs using the line mentioned above. following are the symptoms

The problem :

1. Code is run from a web environment (WCF / ASP.NET / ANOTHER WEB CONTEXT ).

2. The code runs fine  in a console/desktop app on the same environment .

The solution :

1. Replace the above code to get the WorkItemStore with this code.

WorkItemStore wi  = new WorkItemStore(“your tfs server url”);

This code line is the key, because if you put all other settings (which i’ll mention below) , but still use GetService<WorkItemStore> , it’s not gonna work.

2. If running through WCF make sure that

2.1 Enable 32bit apps setting is true.

applicationpool

applicationpool

2.2  :- also, make sure that the app pool is run from a more privileged account, you can set this from the identity property in the image above.

3. Add an entry in your web.config file with this appsetting.

<appSettings>

<add key=”WorkItemTrackingCacheRoot” value=”[C:|D:]\Some_folder” />

  </appSettings>

Your IIS appool should’ve write permissions on this folder.

4. you might also need this setting in your web.config under <configuration> element.

<startup useLegacyV2RuntimeActivationPolicy=”true”>
    <supportedRuntime version=”v4.0″ sku=”.NETFramework,Version=v4.0″/>
  </startup>

And bingo!!!! 🙂 , Now you should be able to work with TFS through your web service :).

Now CRM 2011 :D

Friends,

Now i’ve joined microsoft, and at the same time bidding bye to ASP.NET as MS has put me to work on dynamic CRM. I’m loving CRM , a really nice product but again i’m not loving the feeling of being a newbie in a new technology. ASP.NET was my area i had 360 degree view of it. But i believe you can easily work on MS CRM if you’ve worked previously on .NET.

Therefore, now onwards i’ll be posting my learning experiences on CRM 2011. Wish me good luck guyz!!

An interview at Microsoft.

Tags

, , , ,

Friends,

It wasn’t unlike the other days when i got this call from a job consultant about an opening in a company. She had just started detailing about the job when I gave her a point blank reply saying “Excuse me? I’m only looking for certain specific things in my next profile, do you have one which brackets at least a few of them?”, she interjected “It’s with Microsoft dear, and they’ve already shortlisted your profile!!!! hope you are interested, aren’t you??”, and then??……… Ohhh sure!!, why not!! okay!!, and slowly benevolence occupied me :).

The next ten minutes gone into understanding the expectations of Microsoft as they were looking for people who are quite at home in their core technology products’ skills and willing to migrate to a new product platform. Within those 10 minutes she also made it pretty clear that one should be ready for multiple rigorous grilling sessions at multiple levels coupled with tooth and nail competition making the final recruitment even more challenging.

Day 1 : Interview was scheduled at 10AM saturday morning, a time, when most of the time i’m either fat asleep or half awake and drooling 😀 :D. Nevertheless, the day being an important one i not only woke up early but reached the venue (bandra kurla complex, 20kms) on time.

No sooner than i entered the room i found at least more than a dozen people already in there waiting for their turn and i realized that by any means i’m not going to leave for home early today.

Believe it or not, it took an unfathomable 6 hours when i first heard my name getting called for the first round i.e around 4’O clock. I was further left agape too see the interview panel’s people’s morning fresh faces.

The guy didn’t take much time in explaining the requirement stuff again, and asked me to quickly brief him about myself. I too, at the other end didn’t take much time to brief him about me. I emphasized on important things like winning the Microsoft community contribution award last year , also how i feel more passionate about MS technologies, my blog on ASP.NET , etc..

Technical Rounds :

He started with his technical one on one session and posed a scenario before me.

1. FIRST QUESTION, How will you design a bi-directional WCF messaging server system where heterogeneous client types could connect to the server and exchange messaging, not limiting to MS suite.

Understanding the question took me some time, but i quickly sensed that he’s poiniting towards WCF and specifically WCF duplex communication. I started explaining him WCF duplex communication (with net.tcp binding, WsHttpdualBinding) when he played the master stroke, he said! if you design your WCF with this way will you be able to connect a silverlight client with a nice and cool UI which the customer wants??? the answer is no, because silverlight doesn’t support WsduplexHttpBinding.

refer to this thread. http://forums.silverlight.net/t/226033.aspx/1

Fortunately, my silverlight WCF experiments came for my rescue and i told him that this is definitely possible albeit not with any of the above mentioned bindings but with another different binding called pollingDuplexHttpBinding which has been dedicatedly created for silverlight and supports duplex communication over Http channel. I also didn’t forget to tell him there are other means accomplish this e.g. one framework called “SignalR” which supports virtually any client and is truly distributed in nature. I wasn’t fully sure about the veracity of my answer but knew that he isn’t in a position to argue on this :D. All in all, first impression is the last impression in any interview and MS interview is no exception.

Going further he asked me more WCF questions like WCF session management , reliability , exposing one service , over multiple endpoints etc..

Then he came down to C# and asked about implementing various OO concepts  in C#, entity data framework its deferred execution etc.., ODATA web services, difference b/w OData and SOAP services.

The first round concluded this way after they having me grilled for nearly 2hrs. aaichya gavaat!!

Finally, their HR guy quickly communicated to me that i’m through the first round, a moment of elation? :D, short lived though, as he went ahead saying that for the next rounds I’ve to come the very next day, sunday 😦 .

Next day again I reached on time and saw only four guyz sitting in the room and breathed a sigh of relief thinking that today i’ll save some sunday for myself.

My name got called in just half and hour today and i was taken to a room where there was a guy sitting with a laptop and a few papers and i realized that this is going to be the hands on round for which MS is infamous for 😀 and indeed it was the hands on round :D.

The assignment given to me was to create an ASP.NET/WPF application which is kind of an image gallery, the users should be able to upload images, the system should ask the user to provide a name for his album and then store the images in that directory, otherwise, it should create a folder by the name of the geographical location of the user e.g. if the user is sitting in London uploading images , the system should first create a folder inside the root folder with the name “London” and then store the images there.

At the retrieving side the user should be able to see the images in a treeview. It might look a not so very complex kindaa requirement but the challenge was to complete the assignment in 3HRSSSSSSSSSS. Now that was challenging, in addition to this they were going to look at the way you code , declare variables, naming conventions, and bla bla bla….

I somehow completed 70% of this task in those 3 hrs, and with the last clock tick the guy materialized into the room again :D. He said are you done?? I said, yes, i mean no, i mean partially, finally i said NO, it’s not complete.

He said no probs, lets see what you’ve done, i said i’ll show you the application , he said, no i’m not interested in that, i thought, what???, he said yes, let’s see how you code. I was like surrendered, how can you code as per the best practices and also complete something of this sort in just two hours?????

He looked at one of my entity classes declared , it had a syntax like this.

public sealed class User {}

///…. rest of the code

he said, what’s this sealed? i said, class is sealed from being inherited , he said, but why write that? i said if class is not going to be inherited this is the best practice and a thumb rule to create it sealed. He was kind of impressed.These small nitty gritty things can be found inside the book “CLR via C# 3rd edition” a must read book.

In the next 1 hour, he showed me at least 25 errors in my code and finally said that this is not an MS quality code :(. I defended myself by arguing against the time given to complete the assignment. The important thing was to accept your mistakes and speak less.

THE MAIN ISSUES DISCUSSED :

1. He was unhappy over a  lot of string concatenation that i had to do in order to hook the java script stuff with server code. If you are going for an MS interview after reading this article , make sure you work with a “StringBuilder” right from the outset.

2. He was also unhappy with long method bodies, coz this increases the cyclomatic complexity of a method.

In a nutshell, if you’ve not started yet, start using Fxcop and stylecop tools for code quality compliance. Initially you might feel like pulling your hair (if you’ve left :D), but once you become habitual of writing code with Fxcop and style cop, your coding style will improve vastly. particularly, Fxcop is a must to use tool. It’ll help you write optimized CLR code.

Beyond this point i wasn’t sure that i’m still in the fray. And as per my fears the HR guy came and said they need some time to think over my candidature and asked me to “Leave for the day” , a line which actually meant (in indian context) “you are rejected?” I could only speak “alright” that time and left the venue.

While driving back home the feelings and emotions was unarguably sullen. But honestly, i was happy at my attempt, i really wasn’t having that feeling of being rejected.

Not more than 15 minutes had elapsed when i suddenly felt my phone ringing. i picked up the call and it was from those MS guyz again. The HR guy said , Shashank, will it be possible for you to drive back again, I think there is still some scope left. I was like WTF :D, but sensing the opportunity i said OK boss, i’m coming.

When i reached back they said they wanted to have another round of technical discussion with me and if I cleared that I’ll be clearing all their technical rounds and will proceed to the HR round.

The next round was technical round taken by the same guy who took the hands on round. He again asked me a lot of questions like

1. How do you create Interfaces, inheritance in javascript?

2. How does method overriding work in javascript?

3. Silverlight discussion.

4. ASP.NET ajax framework, how is it different from other frameworks.

5. Difference b/w variables and properties, which to use when? etc..

This discussion was over in some 40 mins, i thought i did reasonably well, and quickly got the expected feedback, he said, shashank, you are through our technical rounds now you need to go through our hiring managers’ round but that will happen in Hyderabad, we’ll fly you down there and have those rounds finished.

THE HIRING MANAGER ROUND:

A week later I reached hyd, and saw the MS office at hyd, first sight of your workplace is always fantastic makes you fall in love with it. It’s like getting newly married lolzz.

I was ambling inside the MS campus enjoying the area around, big lawns , tennis court, cricket pitch , Xbox games on every floor, TT, carrom, pool tables, surreptitiously taking the photographs to show to my friends at Mumbai :D.

I met the first hiring manager who welcomed me in his cabin. We sat across the table and he started telling about MS and my expected work profile etc.. Then, he said now he’ll ask me questions to see how I carry myself, talk, attitude etc.. elsewhere you don’t see such an interview style.

He asked me about how you handle teams, how you resolve conflicts within team, how you handle pressure , giving honest answers worked for me like I said I’m bad at handling the pressure, whether @work or @home, sometimes i succumb to the pressure situation and seek help from others, we went on discussing these issues and he was kind of in agreement with me on most of the issues. As I said giving honest truthful answers works in these situations. You need not portray yourself as some superhuman guy. Tell them what you think are your limitations.

Now came the LAST round. It was called a director round. I found myself sitting in front of APAC geography director for that round. He carefully went through the feedback of the last round and started asking customer centric questions.

A summary is below.

1. What and how much do you know about the products which are in direct competition with MS products. Given a chance to showcase MS products before some client how will you make sure that the client shell out money out of his pocket for your products? in short, what makes MS products stand apart from others.

2. This is a mouse (he showed me a mouse) sell it for $500.

3. How will you design a house for Mark Zuckerberg? In other words, what type of home design concept you think mark would go for.

4. You’ve a client at your place, with a backpack full of $s, but who’s alrady made up his mind to buy a competitor’s product you are supposed to pull him towards buying an MS product. What will you do? this will also affect your appraisal :D.

5. What would you like to see yourself as , 5 yrs down the line.

6. Will you prefer to be a top rated employee who’s not in the good books of most of his peers or an average employee who bonds well with most of the people around.

He kept on asking me such questions, I also tried to keep my cool, it doesn’t matter what answer you give for such types of questions, i personally feel try to give a balanced answer, because after every answer given by you they’ll ask you to justify your answer. You need to justify the rationale behind your answer, which I feel is more difficult than simply answering the question.

Finally the final round came to an end, I left hyd for mumbai. Within a week I got the call from MS HR people on finally being selected in MS :D.

Developing a custom dependency injection framework.

Tags

, , , , , , ,

Dear Friends,

Dependency injection is the buzz word in asp.net world. There are lots of frameworks available today like Sprint.Net , Unity Framework , Pico , Avalon and lot others. A typical DI framework as certain components.

1. Container : This is a mapper object which helps in dependency resolution , A container is a compartment that houses some sort of abstraction within its walls. Typically, responsibility for object management is taken over by whatever container is being used to manage those objects.

2. Mapping Specifier : This is some kind of configurable resource which helps in dependency resolution.

3. Object Factory : This generally is a Factory method which uses the mapping specifier to fill the container and ultimately delivers the desired object to the client.

Benefits : DI frameworks offer a lot of benefits, some of them are listed below.

1. Less code : When you employ a DI framework, you save writing a lot of boilerplate code, its different components can be used to supply a lot of commonly required information.

2. Unit Testing : DI frameworks facilitate high degree of component decoupling, this helps in unit testing.

Developing a custom DI framework : It’s not difficult however to develop such a framework, and once done it really gives a nice design to our application. So in this article we’ll see how we can develop one such framework.

We’ll contemplate on the following aspects of our approach.

Abstraction : Abstraction is an important OOP’s concept and generally refers to the separation of common concerns from the overall logic.

Whether you work with an MVC application or an MVP,MVVP , MVVM application , you’ll always work with objects called as entities/models etc.. , they describe the actors within your applications.

So, our framework will abstractly define the notion of an entity.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Abstraction

{

    public abstract class EntityBase

    {

        public abstract bool ValidateEntity();       

    }

}

 

This base class will serve the purpose of defining and entity in a generalized way.

Abstraction of Operations :  This refers to the discrete operations in which an entity can participate. In typical service applications we can generalize them as CRUD operations.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace Interfaces

{

    public interface IEntityOperations

    {

        EntityBase Create(EntityBase e);

        EntityBase Update(EntityBase e);

        IEnumerable<EntityBase> GetAll();

        EntityBase Delete(EntityBase e);

    }

}

 

Putting the pieces together : Having defined the above basic skeleton , we are all set to put it to some real use. Let’s start by defining an entity (Person) for us to work.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Interfaces;

namespace Entities

{

    public class Person : EntityBase

    {

        public string Name { get; set; }

        public override bool ValidateEntity()

        {

            throw new NotImplementedException();

        }

    }

}

 

NOW, Let’s also define a business layer for our application.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using FrameWork;

using Entities;

using Interfaces;

 

namespace BusinessLogic

{

    [AssociatedEntity(typeof(Person))]

    public class PersonBl : IEntityOperations

    {


#region
IEntityOperations Members

 

        public EntityBase Create(EntityBase e)

        {

            return new Person { Name = “Jackie” };

        }

 

        public EntityBase Update(EntityBase e)

        {

            return new Person { Name = “Jackie” };

        }

 

        public IEnumerable<EntityBase> GetAll()

        {

            throw new NotImplementedException();

        }

 

        public EntityBase Delete(EntityBase e)

        {

            throw new NotImplementedException();

        }
#endregion

    }

}

 

The important point to note here is the attribute “AssociatedEntity , which helps in defining the mapping between an entity and its worker class. Here goes the implementation of this attribute.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Interfaces;

 

namespace FrameWork

{

    [AttributeUsage(AttributeTargets.Class)]

    public class AssociatedEntity: Attribute

    {

        Type _t;

        public AssociatedEntity(Type t)

        {
_t = t;

        }

        public Type AssociatedType

        {

            get

            {

                       return _t;

            }

        }

    }

}

The factory method Implementation : Now when we’ve the mapping defined , it’s the time to create a factory class which resolves our dependency at runtime to produce the desired object. This method takes the help of our attribute to establish the relationship between the entity/model and it’s corresponding BLL class.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Interfaces;

using System.Reflection;

using System.IO;

using System.Configuration;

 

namespace FrameWork

{

    public static class ServiceContext

    {

        public static IEntityOperations CreateService<T>(T desiredType) where T : EntityBase

        {

            Assembly asm = Assembly.LoadFile(ConfigurationManager.AppSettings[“BLLAssembly”]);

            foreach
(Type typ in asm.GetTypes())

            {

foreach (AssociatedEntity attrib in typ.GetCustomAttributes(typeof(AssociatedEntity), false))

{


if (attrib.AssociatedType == typeof(T))

                        return Activator.CreateInstance(typ) as IEntityOperations;
}

            }

            return null;

        }

    }

}

In this method, We are essentially looking for the business logic DLL to look for the BLL classes and their associated entities. This method can also be used to fill a container like a Dictionary to store the mapping of entity and BLL class.

Now we are ready to use it for a client application. Here’s a small console application which makes use of our framework.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Entities;

using FrameWork;

using Interfaces;

 

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {           

          Person p = new Person { Name = bruce };         

          IEntityOperations per=ServiceContext.CreateService<Person>(p);

              p.Name=”jackie”;

          p = per.Update(p) as Person;

        }

    }

}


Explanation & Benefits :


  1. Our console application (client) doesn’t know anything about which object is responsible for working with Person entity, all it knows is IEntityOperations , and expects the CRUD operations to have defined, which is exactly why “IEntityOperations” has been created for.
  1. Since there is no link b/w the client and the server, both can developed simultaneouy.

3. Testing can be done even before the actual implementation is provided.

Creating MS-Office files using the OpenXml SDK part-2

Hello Friends,

In this article we’ll explore the new OpenXml Productivity tool , and we’ll see how it can be used to generate complex office document.

This tool is incredibly simple yet powerful to use, we’ll see that in the following steps.

Step 1 : You should’ve installed the OpenXml SDK 2.0 and OpenXml Productivity tool as explained in first part.

Step 2 : Launch the tool, and open any office file.

OpenXML SDK productivity toolStep 3 : That’s all 🙂 , all you’ve to do now is just click on the magical “Reflect Code” button, and you’ll see the .NET code which is required for generating the office file.

Step 4: Copy this code in a .cs file , and modify the part that you want and you are done, this tool is capable of generating code for any office file which can contain any office content.

 

 

 

 

 

 

 

 

 

Creating MS-Office files using the OpenXml SDK part-1

Tags

, , , , , , , , ,

Hello Friends,

Office file generation has always been a pain in a developer’s neck. People have been resorting to ways like using Office Interop Assemblies which are very difficult to use because they need MS-Office to be installed on the server, then there are security issues like permissions , .net Code Access Security , Need of Impersonation and a hell lot more.

However, things have incredibly changed with the arrival of office-2007, thanks to Microsoft we now have complete freedom to use the new managed code which doesn’t require office to be installed at the server. This has become possible by a new SDK called OpenXml SDK. As we know that office files are now archieve packages hence in order to process them a whole new XML API has been published which is called OpenXml.

It is also so powerful that you can create almost any kind of Office document which contains images, charts , formulae etc……

In this first part i’ll show you the required softwares that need to be installed.

You need to install the binaries for OpenXml SDK 2.0 , and the Open XML 2.0 Productivity tool.

1. OpenXml SDK 2.0 : This is the managed framework library for working with Office files.

2. Open XML 2.0 Productivity tool : This is the incredible Swiss army’s knife, with this tool you instantly generate the .NET code required to generate any office file.

These installables can be downloaded from the following site

http://www.microsoft.com/download/en/details.aspx?id=5124

Once you download and install them, you can start using them. The following steps shows you how you can use this SDK to generate an empty excel file.

Step 1 : Create an ASP.NET web project.

Step 2 : Add the reference to “DocumentFormat.OpenXml” and “WindowsBase” as shown in the image below

referenceStep 3 : Add a new class and add following code to it.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using DocumentFormat.OpenXml.Packaging;

using DocumentFormat.OpenXml.Spreadsheet;

 

namespace ExcelPackage

{

    public class ExcelHelper

    {

 public static void CreateBlankExcel(string path=@”D:\samples\test.xlsx”)

 {

 using (SpreadsheetDocument doc = SpreadsheetDocument.Create(path,DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))

 {

 WorkbookPart workbook = doc.AddWorkbookPart();

 workbook.Workbook = new Workbook();

WorksheetPart worksheetpart= workbook.AddNewPart<WorksheetPart>();

SheetData sheetData = new SheetData();

worksheetpart.Worksheet = new Worksheet(sheetData);

Sheets sheets= doc.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());

Sheet sheet = new Sheet { Id = doc.WorkbookPart.GetIdOfPart(worksheetpart), Name = “Sheet1”, SheetId = 1 };

sheets.Append(sheet);              

}}}}

Now call this function and you get a beautiful excel file created on that path.

More how to turorials are available at the following location.

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