# Search Results

• ### SSAS: Using fake dimension and scopes for dynamic ranges

##### - by DigiMortal
In one of my BI projects I needed to find count of objects in income range. Usual solution with range dimension was useless because range where object belongs changes in time. These ranges depend on calculation that is done over incomes measure so I had really no option to use some classic solution. Thanks to SSAS forums I got my problem solved and here is the solution. The problem – how to create dynamic ranges? I have two dimensions in SSAS cube: one for invoices related to objects rent and the other for objects. There is measure that sums invoice totals and two calculations. One of these calculations performs some computations based on object income and some other object attributes. Second calculation uses first one to define income ranges where object belongs. What I need is query that returns me how much objects there are in each group. I cannot use dimension for range because on one date object may belong to one range and two days later to another income range. By example, if object is not rented out for two days it makes no money and it’s income stays the same as before. If object is rented out after two days it makes some income and this income may move it to another income range. Solution – fake dimension and scopes Thanks to Gerhard Brueckl from pmOne I got everything work fine after some struggling with BI Studio. The original discussion he pointed out can be found from SSAS official forums thread Create a banding dimension that groups by a calculated measure. Solution was pretty simple by nature – we have to define fake dimension for our range and use scopes to assign values for object count measure. Object count measure is primitive – it just counts objects and that’s it. We will use it to find out how many objects belong to one or another range. We also need table for fake ranges and we have to fill it with ranges used in ranges calculation. After creating the table and filling it with ranges we can add fake range dimension to our cube. Let’s see now how to solve the problem step-by-step. Solving the problem Suppose you have ranges calculation defined like this: CASE WHEN [Measures].[ComplexCalc] < 0 THEN 'Below 0'WHEN [Measures].[ComplexCalc] >=0 AND  [Measures].[ComplexCalc] <=50 THEN '0 - 50'...END Let’s create now new table to our analysis database and name it as FakeIncomeRange. Here is the definition for table: CREATE TABLE [FakeIncomeRange] (     [range_id] [int] IDENTITY(1,1) NOT NULL,     [range_name] [nvarchar](50) NOT NULL,     CONSTRAINT [pk_fake_income_range] PRIMARY KEY CLUSTERED      (         [range_id] ASC     ) ) Don’t forget to fill this table with range labels you are using in ranges calculation. To use ranges from table we have to add this table to our data source view and create new dimension. We cannot bind this table to other tables but we have to leave it like it is. Our dimension has two attributes: ID and Name. The next thing to create is calculation that returns objects count. This calculation is also fake because we override it’s values for all ranges later. Objects count measure can be defined as calculation like this: COUNT([Object].[Object].[Object].members) Now comes the most crucial part of our solution – defining the scopes. Based on data used in this posting we have to define scope for each of our ranges. Here is the example for first range. SCOPE([FakeIncomeRange].[Name].&[Below 0], [Measures].[ObjectCount])     This=COUNT(            FILTER(                [Object].[Object].[Object].members,                 [Measures].[ComplexCalc] < 0          )     ) END SCOPE To get these scopes defined in cube we need MDX script blocks for each line given here. Take a look at the screenshot to get better idea what I mean. This example is given from SQL Server books online to avoid conflicts with NDA. :) From previous example the lines (MDX scripts) are: Line starting with SCOPE Block for This = Line with END SCOPE And now it is time to deploy and process our cube. Although you may see examples where there are semicolons in the end of statements you don’t need them. Visual Studio BI tools generate separate command from each script block so you don’t need to worry about it.

• ### Exam 70-448 - TS: Microsoft SQL Server 2008, Business Intelligence Development and Maintenance

##### - by DigiMortal
The another exam I passed was 70-448 - TS: Microsoft SQL Server 2008, Business Intelligence Development and Maintenance. This exam covers Business Intelligence (BI) solutions development and maintenance on SQL Server 2008 platform. It was not easy exam, but if you study then you can do it. To get prepared for 70-488 it is strongly recommended to read self-paced training kit and also make through all examples it contains. If you don’t have strong experiences on Microsoft BI platform and SQL Server then this exam is hard to pass when you just go there and hope to pass somehow. Self-paced training kit is interesting reading and you learn a lot of new stuff for sure when preparing for exam. Questions in exam are divided into topics as follows: SSIS – 32% SSAS – 38% SSRS – 30% Exam 70-448 gives you Microsoft Certified Technology Specialist certificate.

• ### Code Contracts: Hiding ContractException

##### - by DigiMortal
It’s time to move on and improve my randomizer I wrote for an example of static checking of code contracts. In this posting I will modify contracts and give some explanations about pre-conditions and post-conditions. Also I will show you how to avoid ContractExceptions and how to replace them with your own exceptions. As a first thing let’s take a look at my randomizer. public class Randomizer {     public static int GetRandomFromRange(int min, int max)     {         var rnd = new Random();         return rnd.Next(min, max);     }       public static int GetRandomFromRangeContracted(int min, int max)     {         Contract.Requires(min < max, "Min must be less than max");           var rnd = new Random();         return rnd.Next(min, max);     } } We have some problems here. We need contract for method output and we also need some better exception handling mechanism. As ContractException as type is hidden from us we have to switch from ContractException to some other Exception type that we can catch. Adding post-condition Pre-conditions are contracts for method’s input interface. Read it as follows: pre-conditions make sure that all conditions for method’s successful run are met. Post-conditions are contracts for output interface of method. So, post-conditions are for output arguments and return value. My code misses the post-condition that checks return value. Return value in this case must be greater or equal to minimum value and less or equal to maximum value. To make sure that method can run only the correct value I added call to Contract.Ensures() method. public static int GetRandomFromRangeContracted(int min, int max) {     Contract.Requires(min < max, "Min must be less than max");       Contract.Ensures(         Contract.Result<int>() >= min &&         Contract.Result<int>() <= max,         "Return value is out of range"     );       var rnd = new Random();     return rnd.Next(min, max); } I think that the line I added does not need any further comments. Avoiding ContractException for input interface ContractException lives in hidden namespace and we cannot see it at design time. But it is common exception type for all contract exceptions that we do not switch over to some other type. The case of Contract.Requires() method is simple: we can tell it what kind of exception we need if something goes wrong with contract it ensures. public static int GetRandomFromRangeContracted(int min, int max) {     Contract.Requires<ArgumentOutOfRangeException>(         min < max,         "Min must be less than max"     );       Contract.Ensures(         Contract.Result<int>() >= min &&         Contract.Result<int>() <= max,         "Return value is out of range"     );       var rnd = new Random();     return rnd.Next(min, max); } Now, if we violate the input interface contract giving min value that is not less than max value we get ArgumentOutOfRangeException. Avoiding ContractException for output interface Output interface is more complex to control. We cannot give exception type there and hope that this type of exception will be thrown if something goes wrong. Instead we have to use delegate that gathers information about problem and throws the exception we expect to be thrown. From documentation you can find the following example about the delegate I mentioned. Contract.ContractFailed += (sender, e) => {     e.SetHandled();     e.SetUnwind(); // cause code to abort after event     Assert.Fail(e.FailureKind.ToString() + ":" + e.DebugMessage); }; We can use this delegate to throw the Exception. Let’s move the code to separate method too. Here is our method that uses now ContractException hiding. public static int GetRandomFromRangeContracted(int min, int max) {     Contract.Requires(min < max, "Min must be less than max");       Contract.Ensures(         Contract.Result<int>() >= min &&         Contract.Result<int>() <= max,         "Return value is out of range"     );     Contract.ContractFailed += Contract_ContractFailed;       var rnd = new Random();     return rnd.Next(min, max)+1000; } And here is the delegate that creates exception. public static void Contract_ContractFailed(object sender,     ContractFailedEventArgs e) {     e.SetHandled();     e.SetUnwind();       throw new Exception(e.FailureKind.ToString() + ":" + e.Message); } Basically we can do in this delegate whatever we like to do with output interface errors. We can even introduce our own contract exception type. As you can see later then ContractFailed event is very useful at unit testing.

• ### Interface contracts – forcing code contracts through interfaces

##### - by DigiMortal
Sometimes we need a way to make different implementations of same interface follow same rules. One option is to duplicate contracts to all implementation but this is not good option because we have duplicated code then. The other option is to force contracts to all implementations at interface level. In this posting I will show you how to do it using interface contracts and contracts class. Using code from previous example about unit testing code with code contracts I will go further and force contracts at interface level. Here is the code from previous example. Take a careful look at it because I will talk about some modifications to this code soon. public interface IRandomGenerator {     int Next(int min, int max); }   public class RandomGenerator : IRandomGenerator {     private Random _random = new Random();       public int Next(int min, int max)     {         return _random.Next(min, max);     } }    public class Randomizer {     private IRandomGenerator _generator;       private Randomizer()     {         _generator = new RandomGenerator();     }       public Randomizer(IRandomGenerator generator)     {         _generator = generator;     }       public int GetRandomFromRangeContracted(int min, int max)     {         Contract.Requires<ArgumentOutOfRangeException>(             min < max,             "Min must be less than max"         );           Contract.Ensures(             Contract.Result<int>() >= min &&             Contract.Result<int>() <= max,             "Return value is out of range"         );           return _generator.Next(min, max);     } } If we look at the GetRandomFromRangeContracted() method we can see that contracts set in this method are applicable to all implementations of IRandomGenerator interface. Although we can write new implementations as we want these implementations need exactly the same contracts. If we are using generators somewhere else then code contracts are not with them anymore. To solve the problem we will force code contracts at interface level. NB! To make the following code work you must enable Contract Reference Assembly building from project settings. Interface contracts and contracts class Interface contains no code – only definitions of members that implementing type must have. But code contracts must be defined in body of member they are part of. To get over this limitation, code contracts are defined in separate contracts class. Interface is bound to this class by special attribute and contracts class refers to interface through special attribute. Here is the IRandomGenerator with contracts and contracts class. Also I write simple fake so we can test contracts easily based only on interface mock. [ContractClass(typeof(RandomGeneratorContracts))] public interface IRandomGenerator {     int Next(int min, int max); }   [ContractClassFor(typeof(IRandomGenerator))] internal sealed class RandomGeneratorContracts : IRandomGenerator {     int IRandomGenerator.Next(int min, int max)     {         Contract.Requires<ArgumentOutOfRangeException>(                 min < max,                 "Min must be less than max"             );           Contract.Ensures(             Contract.Result<int>() >= min &&             Contract.Result<int>() <= max,             "Return value is out of range"         );           return default(int);     } }   public class RandomFake : IRandomGenerator {     private int _testValue;       public RandomGen(int testValue)     {         _testValue = testValue;     }       public int Next(int min, int max)     {         return _testValue;     } } To try out these changes use the following code. var gen = new RandomFake(3);   try {     gen.Next(10, 1); } catch(Exception ex) {     Debug.WriteLine(ex.Message); }   try {     gen.Next(5, 10); } catch(Exception ex) {     Debug.WriteLine(ex.Message); } Now we can force code contracts to all types that implement our IRandomGenerator interface and we must test only the interface to make sure that contracts are defined correctly.

• ### Quick example: why coding standards must be in place

##### - by DigiMortal
One quick example why coding standards must be in place. Take a look at the following code – property names are changed but not anything else. public string Property1 { get; set; }   public string Property2 {     get;     set; }   public string Property3 {     get; set; } And yes – it is real-world example.

• ### Invariant code contracts – using class-wide contracts

##### - by DigiMortal
It is possible to define invariant code contracts for classes. Invariant contracts should always hold true whatever member of class is called. In this posting I will show you how to use invariant code contracts so you understand how they work and how they should be tested. This is my randomizer class I am using to demonstrate code contracts. I added one method for invariant code contracts. Currently there is one contract that makes sure that random number generator is not null. public class Randomizer {     private IRandomGenerator _generator;       private Randomizer() { }       public Randomizer(IRandomGenerator generator)     {         _generator = generator;     }       public int GetRandomFromRangeContracted(int min, int max)     {         Contract.Requires<ArgumentOutOfRangeException>(             min < max,             "Min must be less than max"         );           Contract.Ensures(             Contract.Result<int>() >= min &&             Contract.Result<int>() <= max,             "Return value is out of range"         );           return _generator.Next(min, max);     }       [ContractInvariantMethod]     private void ObjectInvariant()     {         Contract.Invariant(_generator != null);     } } Invariant code contracts are define in methods that have ContractInvariantMethod attribute. Some notes: It is good idea to define invariant methods as private. Don’t call invariant methods from your code because code contracts system does not allow it. Invariant methods are defined only as place where you can keep invariant contracts. Invariant methods are called only when call to some class member is made! The last note means that having invariant method and creating Randomizer object with null as argument does not automatically generate exception. We have to call at least one method from Randomizer class. Here is the test for generator. You can find more about contracted code testing from my posting Code Contracts: Unit testing contracted code. There is also explained why the exception handling in test is like it is. [TestMethod] [ExpectedException(typeof(Exception))] public void Should_fail_if_generator_is_null() {     try     {         var randomizer = new Randomizer(null);         randomizer.GetRandomFromRangeContracted(1, 4);     }     catch (Exception ex)     {         throw new Exception(ex.Message, ex);     } } Try out this code – with unit tests or with test application to see that invariant contracts are checked as soon as you call some member of Randomizer class.

• ### Code Contracts: Unit testing contracted code

##### - by DigiMortal
Code contracts and unit tests are not replacements for each other. They both have different purpose and different nature. It does not matter if you are using code contracts or not – you still have to write tests for your code. In this posting I will show you how to unit test code with contracts. In my previous posting about code contracts I showed how to avoid ContractExceptions that are defined in code contracts runtime and that are not accessible for us in design time. This was one step further to make my randomizer testable. In this posting I will complete the mission. Problems with current code This is my current code. public class Randomizer {     public static int GetRandomFromRangeContracted(int min, int max)     {         Contract.Requires<ArgumentOutOfRangeException>(             min < max,             "Min must be less than max"         );           Contract.Ensures(             Contract.Result<int>() >= min &&             Contract.Result<int>() <= max,             "Return value is out of range"         );           var rnd = new Random();         return rnd.Next(min, max);     } } As you can see this code has some problems: randomizer class is static and cannot be instantiated. We cannot move this class between components if we need to, GetRandomFromRangeContracted() is not fully testable because we cannot currently affect random number generator output and therefore we cannot test post-contract. Now let’s solve these problems. Making randomizer testable As a first thing I made Randomizer to be class that must be instantiated. This is simple thing to do. Now let’s solve the problem with Random class. To make Randomizer testable I define IRandomGenerator interface and RandomGenerator class. The public constructor of Randomizer accepts IRandomGenerator as argument. public interface IRandomGenerator {     int Next(int min, int max); }   public class RandomGenerator : IRandomGenerator {     private Random _random = new Random();       public int Next(int min, int max)     {         return _random.Next(min, max);     } } And here is our Randomizer after total make-over. public class Randomizer {     private IRandomGenerator _generator;       private Randomizer()     {         _generator = new RandomGenerator();     }       public Randomizer(IRandomGenerator generator)     {         _generator = generator;     }       public int GetRandomFromRangeContracted(int min, int max)     {         Contract.Requires<ArgumentOutOfRangeException>(             min < max,             "Min must be less than max"         );           Contract.Ensures(             Contract.Result<int>() >= min &&             Contract.Result<int>() <= max,             "Return value is out of range"         );           return _generator.Next(min, max);     } } It seems to be inconvenient to instantiate Randomizer now but you can always use DI/IoC containers and break compiled dependencies between the components of your system. Writing tests for randomizer IRandomGenerator solved problem with testing post-condition. Now it is time to write tests for Randomizer class. Writing tests for contracted code is not easy. The main problem is still ContractException that we are not able to access. Still it is the main exception we get as soon as contracts fail. Although pre-conditions are able to throw exceptions with type we want we cannot do much when post-conditions will fail. We have to use Contract.ContractFailed event and this event is called for every contract failure. This way we find ourselves in situation where supporting well input interface makes it impossible to support output interface well and vice versa. ContractFailed is nasty hack and it works pretty weird way. Although documentation sais that ContractFailed is good choice for testing contracts it is still pretty painful. As a last chance I got tests working almost normally when I wrapped them up. Can you remember similar solution from the times of Visual Studio 2008 unit tests? Cannot understand how Microsoft was able to mess up testing again. [TestClass] public class RandomizerTest {     private Mock<IRandomGenerator> _randomMock;     private Randomizer _randomizer;     private string _lastContractError;       public TestContext TestContext { get; set; }       public RandomizerTest()     {         Contract.ContractFailed += (sender, e) =>         {             e.SetHandled();             e.SetUnwind();               throw new Exception(e.FailureKind + ": " + e.Message);         };     }       [TestInitialize()]     public void RandomizerTestInitialize()     {         _randomMock = new Mock<IRandomGenerator>();         _randomizer = new Randomizer(_randomMock.Object);         _lastContractError = string.Empty;     }       #region InputInterfaceTests     [TestMethod]     [ExpectedException(typeof(Exception))]     public void GetRandomFromRangeContracted_should_throw_exception_when_min_is_not_less_than_max()     {         try         {             _randomizer.GetRandomFromRangeContracted(100, 10);         }         catch (Exception ex)         {             throw new Exception(string.Empty, ex);         }     }       [TestMethod]     [ExpectedException(typeof(Exception))]     public void GetRandomFromRangeContracted_should_throw_exception_when_min_is_equal_to_max()     {         try         {             _randomizer.GetRandomFromRangeContracted(10, 10);         }         catch (Exception ex)         {             throw new Exception(string.Empty, ex);         }     }       [TestMethod]     public void GetRandomFromRangeContracted_should_work_when_min_is_less_than_max()     {         int minValue = 10;         int maxValue = 100;         int returnValue = 50;           _randomMock.Setup(r => r.Next(minValue, maxValue))             .Returns(returnValue)             .Verifiable();           var result = _randomizer.GetRandomFromRangeContracted(minValue, maxValue);           _randomMock.Verify();         Assert.AreEqual<int>(returnValue, result);     }     #endregion       #region OutputInterfaceTests     [TestMethod]     [ExpectedException(typeof(Exception))]     public void GetRandomFromRangeContracted_should_throw_exception_when_return_value_is_less_than_min()     {         int minValue = 10;         int maxValue = 100;         int returnValue = 7;           _randomMock.Setup(r => r.Next(10, 100))             .Returns(returnValue)             .Verifiable();           try         {             _randomizer.GetRandomFromRangeContracted(minValue, maxValue);         }         catch (Exception ex)         {             throw new Exception(string.Empty, ex);         }           _randomMock.Verify();     }       [TestMethod]     [ExpectedException(typeof(Exception))]     public void GetRandomFromRangeContracted_should_throw_exception_when_return_value_is_more_than_max()     {         int minValue = 10;         int maxValue = 100;         int returnValue = 102;           _randomMock.Setup(r => r.Next(10, 100))             .Returns(returnValue)             .Verifiable();           try         {             _randomizer.GetRandomFromRangeContracted(minValue, maxValue);         }         catch (Exception ex)         {             throw new Exception(string.Empty, ex);         }           _randomMock.Verify();     }     #endregion        } Although these tests are pretty awful and contain hacks we are at least able now to make sure that our code works as expected. Here is the test list after running these tests. Conclusion Code contracts are very new stuff in Visual Studio world and as young technology it has some problems – like all other new bits and bytes in the world. As you saw then making our contracted code testable is easy only to the point when pre-conditions are considered. When we start dealing with post-conditions we will end up with hacked tests. I hope that future versions of code contracts will solve error handling issues the way that testing of contracted code will be easier than it is right now.

• ### List of Microsoft training kits (2012)

##### - by DigiMortal
Some years ago I published list of Microsoft training kits for developers. Now it’s time to make a little refresh and list current training kits available. Feel free to refer additional training kits in comments. Sharepoint 2010 Developer Training Kit SharePoint 2010 and Windows Phone 7 Training Kit SharePoint and Windows Azure Development Kit Visual Studio 2010 and .NET Framework 4 Training Kit (December 2011) SQL Server 2012 Developer Training Kit SQL Server 2008 R2 Update for Developers Training Kit (May 2011 Update) SharePoint and Silverlight Training Kit Windows Phone 7 Training Kit for Developers - RTM Refresh Windows Phone 7.5 Training Kit Silverlight 4 Training Web Camps Training Kit Identity Developer Training Kit Internet Explorer 10 Training Kit Visual Studio LightSwitch Training Kit Office 2010 Developer Training Kit - June 2011 Office 365 Developer Training Kit - June 2011 Update Dynamics CRM 2011 Developer Training Kit PHP on Windows and SQL Server Training Kit (March 2011 Update) Windows Server AppFabric Training Kit Windows Server 2008 R2 Developer Training Kit - July 2009

• ### Using ExcelPacke to create Excel sheets on server

##### - by DigiMortal
In one of my community projects I needed to output some listings as Excel file. As installing Excel to server is non-sense that I was easily able to avoid I found simple solution for Excel 2007 files – open-source project called ExcelPackage. In this posting I will show you hot to create simple event attendees report in Excel 2007 format using ExcelPackage. Cautions Although ExcelPackage works well for me here are some things you should be aware of. ExcelPackage needs file system access because compression library it uses is designed so. There is only very old source code available and it is published under GPL. So if you are writing application to your customers then you cannot use this library unless you make your whole application open-source. ExcelPackage has also some technical problems and it is not very easy to use in simple cases. Authors have not provided any new releases since the beginning of 2007 so I have good reason to consider this project as abandoned. You may find the extensive package EPPlus also useful as there are new versions coming over time. EPPlus is also published under GPL (because ExcelPackage is under GPL), so you can use it only on very limited manner. If you don’t afraid some s*itfight with technology and GPL is okay for your system then let’s go on. Exporting event attendees list to Excel Suppose we have list with event attendees and we want to export it to Excel. We are behaving normally and we don’t install Excel desktop software to our web server. Here is the code. void ExportToExcel(Event evt) {     var fileInfo = new FileInfo(Path.GetTempPath() + "\\" +                                  DateTime.Now.Ticks + ".xlsx");       using (var xls = new ExcelPackage(fileInfo))     {         var sheet = xls.Workbook.Worksheets.Add(evt.Title);           sheet.Cell(1, 1).Value = "First name";         sheet.Cell(1, 2).Value = "Last name";         sheet.Cell(1, 3).Value = "E-mail";         sheet.Cell(1, 4).Value = "Phone";         sheet.Cell(1, 5).Value = "Registered";         sheet.Cell(1, 6).Value = "Live Meeting";           var i = 1;         foreach(var attendee in evt.Attendees)         {             i++;               var profile = attendee.Profile;             sheet.Cell(i, 1).Value = profile.FirstName;             sheet.Cell(i, 2).Value = profile.LastName;             sheet.Cell(i, 3).Value = profile.Email;             sheet.Cell(i, 4).Value = profile.Phone;             sheet.Cell(i, 5).Value = att.Created.ToString();             sheet.Cell(i, 6).Value = att.LiveMeeting.ToString();         }           xls.Save();      }       Response.Clear();     Response.ContentType = "application/vnd.openxmlformats";     Response.AddHeader("Content-Disposition",                        "attachment; filename=" + fileInfo.Name);     Response.WriteFile(fileInfo.FullName);     Response.Flush();       if (fileInfo.Exists)         fileInfo.Delete(); } And here is the result. Although it is possible to make this list more effective and nice it works and users can start using it until all the nice bells and whistles are coming. Conclusion After some fighting with technology it was not very hard to get nice Excel 2007 sheets coming out from our server. We used ExcelPackage library to create list of event attendees and our event organizers can now simply download data to Excel if they need to contact with attendees or manage their data using Excel tools.

• ### ASP.NET MVC: MVC Time Planner is available at CodePlex

##### - by DigiMortal
I get almost every week some e-mails where my dear readers ask for source code of my ASP.NET MVC and FullCalendar example. I have some great news, guys! I ported my sample application to Visual Studio 2010 and made it available at CodePlex. Feel free to visit the page of MVC Time Planner. NB! Current release of MVC Time Planner is initial one and it is basically conversion sfrom VS2008 example solution to VS2010. Current source code is not any study material but it gives you idea how to make calendars work together. Future releases will introduce many design and architectural improvements. I have planned also some new features. How MVC Time Planner looks? Image on right shows you how time planner looks like. It uses default design elements of ASP.NET MVC applications and jQueryUI. If I find some artist skills from myself I will improve design too, of course. :) Currently only day view of calendar is available, other views are coming in near future (I hope future will be week or two). Important links And here are some important links you may find useful. MVC Time Planner page @ CodePlex Documentation Release plan Help and support – questions, ideas, other communication Bugs and feature requests If you have any questions or you are interested in new features then please feel free to contact me through MVC Time Planner discussion forums.