Welcome to weblogs.com.pk Sign in | Join | Help

Knowing the counts of table entries in SQL Server

Here's the query to know the counts of the table entries in SQL Server

select object_name(object_id), row_count
from sys.dm_db_partition_stats
where index_id < 2
order by row_count desc

Posted by khurram | 0 Comments
Filed under:

Simple Accounting Software

Being in Software Industry; I am often contacted by people who are looking for a “simple accounting software” (or some time simple retail software) and often say they need very simple thing which might need 1 to 2 developer month time of development…Some even try this; and then come back after 3-6 months blaming software developers that they could not deliver what they wanted. Problem lies that they are not putting up enough requirements and not defining the scope well enough.

For all these people I suggest to look for some entry level accounting or retail software and evaluate them. If you come across with some package that full fill the requirements; its better to pay the vendors and get such off the self product. You will save your time and can start using something right away.

If budget is the concern; with a simple search on Google you can find many open source “Accounting Software” “Retail Software” or some “mini ERP”. Its not a bad idea to try them out; you might expereince some issues in setting up these packages; you can hire or find someone in family or social circle who is well versed with setting up such desktop / web applications with databases (usually mySQL or SQL Server).

If you need customization, you can even try to engage some mid level developer to go through the code of such open source package. You can Google such free launce developers in your area or can find them on sites like Rent A Coder or oDesk. If you able to find a developer who has listed your preferred package in his resume / online profile; it might cost you less as such developer already know your package and can guide you quickly what's possible and how much time / money it will cost you for the customizations you might be looking for.

Posted by khurram | 0 Comments
Filed under: ,

Sharepoint–File Not Found

If you have created your custom ASPX and getting “File Not Found” exception; here are few possible reasons and solutions

Place the assembly (DLL) containing the code behind code into the sharepoint web application’s bin folder. If it resolves the issue but you don’t want to keep the DLL into web application’s bin folder and instead want to have it in Global Assembly Cache (GAC) only then you need to make sure that in the @Page directive you are giving the full name including its public key of your assembly. More details are on my earlier post.

The other reason can be that you are using some third party assembly; either using some third party control or have dependency on some assembly which is not registered as “SafeControl”. Make sure that all such referenced assemblies are added into the sharepoint web site’ web.config file.

If you need to troubleshoot or need to find out which assembly you are getting error with; you can do two things; simplest is that you set CallStack to true in sharepoint web application’ web.config file. Its in configuration\Sharepoint\SafeMode section in that file. Setting this to true and also setting the famous customErrors mode to Off (configuration\system.web\customErrors section in web.config) you will get the complete details of the exception including the call stack. This can help you understand where this error is getting generated. The second thing you can try is FUSLOGVW tool which is in %ProgramFiles%\Microsoft SDKs\Windows\v6.0A\Bin. This tool shows the Fusion logs. You can copy this tool from the development machine to the server. You need to be careful; if you try to use v7.0 exe; it shows .NET v4 FUSLOGs. You might also need to forcefully enable the Fusion logs by issuing the following command

>reg add HKLM\Software\Microsoft\Fusion /v EnableLog /t REG_DRWORD /d 1

More details about Assembly Probing, Fusion and FUSLOGVW can be found here.

Posted by khurram | 0 Comments
Filed under:

ASP.NET MVC 2 Strongly Typed HTML Helpers

ASP.NET MVC 2 is released lately, and I was fascinated by the ASP.NET MVC 2’s strongly typed HTML helper; where you can tell the library the field name in compiler friendly fashion like

<% Html.TextBoxFor( m => m.FirstName) %>

MVC’s Html helper class magically outputs the correct tag having necessary stuff like id of the textbox based on the field name you have just passed. For MVC its beneficial in a way that when you are editing/creating the ASCX/ASPX file in Visual Studio; Visual Studio gives proper IntelliSence. The real benefit of such an API is not very meaningful in ASCX/ASPX file. Its greater maintainability i-e instead of passing the name of certain fields or something as string (red colored code) you are providing it in strongly typed way and if you rename the field name the compiler will warn you. I was hooked instantly and wanted to know what's happening behind the scene. So to learn this trick; I setup a small project where I wanted to code a simple method GiveMeFieldNameAndItsValue which takes a similar lambda and returns a string having the field name I passed and the value of that field from the instance of some model. I defined my Model as

class Model
{
    public string FirstName = string.Empty;
    public string LastName = string.Empty;
}

My target was that I can use my method something like

class Program
{
    static void Main(string[] args)
    {
        Model khurram = new Model() { FirstName = "Khurram", LastName = "Aziz" };
        var processor = new LambdaProcessor<Model>(khurram);
        Console.WriteLine(processor.GiveMeFieldNameAndItsValue(m => m.FirstName));
        Console.ReadLine();
    }
}

The LamdbaProcessor class needed to be using Generics so that I can use it with any Model. The instance of our model is passed in the constructor which the class keeps as an instance variable. I also needed some infrastructure in place through which I can return the value of this instance variable’ certain field which I will pass as an argument. GetProperty<T>(string name) method here is for this purpose. This method will be called by the magic extension method to which the field name will be passed through the lambda.

class LambdaProcessor<TModel>
{
    public TModel model;
 
    private LambdaProcessor() { }
 
    public LambdaProcessor(TModel model)
    {
        this.model = model;
    }
 
    public TProperty GetProperty<TProperty>(string name)
    {
        FieldInfo[] fields = this.model.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
        foreach (FieldInfo field in fields)
        {
            if (field.Name.Equals(name))
                return (TProperty)field.GetValue(this.model);
        }
 
        return default(TProperty);
    }
}

Our magic extension method that does the actual trick uses System.Linq.Expressions.Expression. This class provides us API through which we can access to the lambda being provided and can retrieve interesting information about it. Here is the code of the extension method

static class Extensions
{
    public static string GiveMeFieldNameAndItsValue<TModel, TProperty>(this LambdaProcessor<TModel> processor,
        Expression<Func<TModel, TProperty>> expression)
    {
        string fieldName = ((MemberExpression)expression.Body).Member.Name;
        TProperty value = processor.GetProperty<TProperty>(fieldName);
        return string.Format("{0} : {1}", fieldName, value);
    }
}

If you are not getting this lambda and delegate; try my earlier posts on Delegates and Generics and Delegates and Lambda

Posted by khurram | 4 Comments

Active Directory Application Mode

From the Wikipedia

Active Directory Application Mode (ADAM) is a light-weight implementation of Active Directory. ADAM is capable of running as a service, on computers running Microsoft Windows Server 2003 or Windows XP Professional. ADAM shares the code base with Active Directory and provides the same functionality as Active Directory, including an identical API, but does not require the creation of domains or domain controllers.

Like Active Directory, ADAM provides a Data Store, which is a hierarchical datastore for storage of directory data, a Directory Service with an LDAP Directory Service Interface. Unlike Active Directory, however, multiple ADAM instances can be run on the same server, with each instance having its own and required by applications making use of the ADAM directory service.

In Windows Server 2008, ADAM has been renamed AD LDS (Lightweight Directory Services)

Sometimes you need to store certain configurations at the central place which are required by different applications running at different places or might be different users need to access this information. For instance hard coding passwords of network devices into scripts deployed at different monitoring machines; this configuration information can be stored centrally. Support of LDAP exists in almost every platform; from PERL to .NET!

Adam

When you install ADAM; no ADAM instance is configured; rather you get the option to create ADAM instance. ADSI Edit is the MMC based tool through which you can access the ADAM instances. One hidden tool is ADAM Schema which is MMC Snap-in that you can add after firing MMC. Lets go through a scenario in which we want to store information about certain network devices; say routers and want to access this information from the PERL script running in *nix.

UniqueInstance

First we will create an ADAM instance choosing a unique instance, and naming the instance Apps. We have to create an application directory partition giving it proper distinguished name.

PartionName

While setting it up; we need to import the available LDIF (Lightweight Directory Interchange Format) files; these available schema files will later be used when we will be creating users and giving them roles to access our directory partition.

ImportingLDIF

Then using ADSI Edit; connect to the three well known naming contexts of your configured ADAM instance. Using RootDSE context; LDAP client can learn more about your directory partition like whats its name etc. With Schema context you can extend the partition schema and with Configuration schema you can access and manage the data.

Adsi-Connecting

Next we need to use ADAM Schema Snapin to extend the schema of our partition. Fire up MMC and and from File > Add/Remove Snapin add the ADAM Schema Snapin and connect to your configured ADAM instance. You will see Classes and Attributes. Next we need OIDGEN.exe; which is Windows 2000 Resource Kit tool (Google it) through which we can generate X500 OIDs for our new Attributes and Classes.

ChangeAdamServer

For our scenario; I created three attributes; IpAddress, Login and Password. If we dont want Min/Max configs; simply leave them blank!

Attribute Base OID:
1.2.840.113556.1.4.7000.233.28688.28684.8.281218.1.640586.1573940.517016
    1    IpAddress
    2    Login
    3    Password

CreatingAttribute

For our scenario we need one class; NetworkDevice

Class Base OID:
1.2.840.113556.1.5.7000.111.28688.28684.8.304224.1.845399.1625543.239673
    1    NetworkDevice

CreatingClass

And we need to add our attributes as Mandatory!

MandatoryFieldsofClass

Our schema is now ready; next we need to create a Container in our application partition and couple of instances of our newly defined class. For this we will use ADSI Edit. Stay tuned for the next part in which I will cover how to add data; and access that from the PERL script!

Posted by khurram | 0 Comments

Why Microsoft Dynamics GP 10 Workflow is Joke?

Most of the things in Microsoft Dynamics GP are Dexterity based; which is a RAD scripting like environment with rich support for Forms, Tables etc; something like PL/SQL. Dynamics GP also supports .NET based clients assemblies that you can load against GP forms; for that you need to create form factories according to the Dynamics GP expectations. You specify these form factories in Dynamics.exe.config file (a typical .NET form app looking config). You create the form, their windows and controls on them in Dexterity and to access these controls etc in the .NET client assembly you use GP Visual Studio Tools app to generate an assembly from your Dexterity Dictionary Changes and then reference this assembly in your client assembly. Unfortunately GP thin client is old days VB6 like two tier app; you need to deploy your dictionary changes, changes in .config and the two client assemblies to each workstation! (whenever you make any changes and want to release some update). The story does more complicated when we involve the server part!

At the server side; Dynamics GP uses Microsoft Office SharePoint Server. It needs full MOSS (for apparently no reason; I think what it provides can be done in plain WSS). It needs GP Web Services; which unfortunately you need to setup separate to MOSS. I guess they decided to keep it separate so that if you just need GP Web Services without Workflow or Business portal; you may…..but I think they should had used WSS for workflow and this GP Web Service component should be implemented on WSS…I explain why…..The GP Web Services needs “Dynamics Security” component against which GP Web Services does security checking. This Dynamics Security component I guess is shared across their Dynamics product line and its implemented as web service (one more web service) and in the back end it uses Active Directory Application Mode; this makes sense but its over engineering…why because as said before if they have implemented GP Web Services on WSS they could have used WSS Security Infrastructure….and things could have become much cleaner to maintain…The server side story doesn't end here….

You need to code a server side workflow assembly through which you basically exposes the entity fields that you want the rules to run on. This assembly is not a typical Windows Workflow assembly or typical SharePoint Workflow assembly; instead its an addon like assembly which “SharePoint GP Workflow” uses. This assembly is bit tricky to code….I think the simpler solution must have been to make available some Windows Workflow Activities; so that one could use it the way they wanted to…either in Visual Studio to develop some SharePoint Workflow; or through Sharepoint Designer…

The overall experience of bringing the system online and start coding some real thing…and then coding something….is all messy….it could have much simpler….I am not sure if they are improving it in the upcoming GP 2010 or not….but till then GP Workflow is really a joke!!!

Posted by khurram | 0 Comments

UserVoice – ASP.NET and Silverlight Teams are listening!

Posted by khurram | 0 Comments
Filed under: ,

Recreate “Show Desktop” icon in Quick Launch

Simply save the following content using Notepad at %userprofile%\Application Data\Microsoft\Internet Explorer\Quick Launch as a file having extension scf; like Show Desktop.scf; it will not appear right away; you can then enable disable the Quick Launch toolbar to force it to reload the icons!

[Shell]
Command=2
IconFile=explorer.exe,3
[Taskbar]
Command=ToggleDesktop

Posted by khurram | 0 Comments

Windows Phone 7 - The Real Smart Phones?

Few weeks back I was in process of choosing my new smart phone. I figured out that iPhone is just a buzz and has become sort of status symbol. Symbian is dying; Nokia is left behind alone and others have moved away to Android. S60v5 is the latest and I guess the last release as Nokia is positioning to use Maemo (Linux underneath) for its next smart phones. Nokia’s N900; the first Maemo powered Smart Phone is still expensive and not very good as a phone (my opinion). Android looks promising..but I picked Nokia’ N97 (S60v5) knowing that it might become obsolete soon…but who cares :) Its Nokia; it will keep working and there’s so much already out there for S60v5 in particular and S60 in general…that I dont mind it becoming obsolete soon! Symbian is not very developer friendly especially for developers like us who have become addicted to DOT…DOT and I wished that Net60; the .NET CF runtime for S60 from Red Five Labs, was donated to community before Red Five Labs closed itself down :(

Lately I have become addicted to PodCasts and VideoCasts and my N97 for some weird reasons don't play High Quality WMVs :( I want to get some device with Wi-fi support and which can download / play podcasts / videocasts through RSS/Atom feeds. ZuneHD has become the preferred one; but haven't yet got it as its not available in local market! While surfing around comparing ZuneHD and iPod Touch; and was surprised why the heck Microsoft don't simply add GSM/GPRS support in ZuneHD and it can become a kick ass iPhone killer (ZuneHD has two CPU and dedicated GPU); and I think this is exactly what Microsoft is doing; enhancing Zune’ OS to support phone capabilities and have made it generalized to support different hardware vendors. Windows Phone 7 is announced yesterday and I think it has enough juice to strike back and it will become a real competitor when the devices will be available late this calendar year. I still think that Microsoft should release hardware of their own for Windows Phone 7; might be as a successor of ZuneHD and as a reference hardware for Windows Phone 7 just like Google is doing with NexusOne even though it may not liked by its partner!

Another interesting aspect I listened about on one podcast is that mobile devices is becoming powerful; LG / Toshiba etc already has released devices running at 1GHz; devices with large memory is becoming common…two to three years down the road; will there be need of special mobile OS? The trimmed down versions of normal desktop OS like Windows or Apple might be running on mobile devices. Anyways I am tuned to Mix10 (next month) where more development related details will become available for Windows Phone and hopefully Silverlight for Mobile. I guess 2010 will be good for mobile development.

Posted by khurram | 2 Comments
Filed under: , ,

Sharepoint and SQL Server Reporting Services

SQL Server 2005 Reporting Services SP2 or later can be integrated with Sharepoint. Setting it up is bit tricky. http://msdn.microsoft.com/en-us/library/ee384252.aspx URL is must read to troubleshoot the issues. For me following worked

  • Ensure only Windows Integrated Authentication is checked on http://server/ReportServer
  • DisableLoopBackCheck using http://support.microsoft.com/kb/896861
  • Use Windows Authentication in SQL Server Reporting Services Integration option of Central Administration
  • Make sure your login is Central Administration’ Site Collection Administrator; activate the Reporting Feature from Site Collection Features of Central Administration
  • Using the same Web site’ IIS Pool for Report Server and Sharepoint site
  • Using the same login to run the Report Server’ Windows Service which is used for IIS Pool
  • Giving the Site Owner role to the same login; also making this login part of local Administrators group

While publishing from Visual Studio; use the following:

Target Data Source Folder: http://sharepoint-site/Reports/Documents/Data Sources
Target Report Folder: http://sharepoint-site/Reports/Documents/TheReports
Target Server Url: http://sharepoint-site/reports

I had Sharepoint Portal Server; sharepoint-site/reports is Report Centre url; and I wanted to deploy my reports into its Documents document library!

VSeWSS – Sharepoint Event Receivers

Coding Event Receivers with Visual Studio Extensions for Windows Sharepoint Services (VSeWSS) is easy; you add it into your project using Add New Item –> Sharepoint / Event Receiver. You dont need to add “EventReceiver” in the name; as it will automatically post fix; ItemEventReceiver and ListEventReceiver names to the two classes that it generates. It also generates two associated XML files for events which VSeWSS uses and when deploying/packaging the VSeWSS generates two feature.xml files under PKG folder. Simply uncomment the event you need in the generated CS files and write your code into it. And instance of SPItemEventProperties is passed to each event.

  • Dont forget to call this.DisableEventFiring() before updating any list item; and this.EnableEventFiring() before exiting. Use try/finally for this!
  • You can use the display names of the field when using properties.ListItem, but you need to use the (Internal)Name of the field with properties.AfterProperties and properties.BeforeProperties
  • Usually the internal name of fields having spaces is different; the spaces are replaced with _x0020_
  • properties.ListItem always contain the current data of the list item for which event has been received; the BeforeProperties get populated for “ed” events; (Added, Updated, Deleted etc) and AfterProperties get populated for “ing” events; (Adding, Updating, Deleting etc)
  • There is some bug in Sharepoint List Eventing due to which properties.AfterProperties.ChangedProperties and/or properties.BeforeProperties.ChangedProperties doesnt give correct values; I didnt checked it myself; I just read it somewhere!

Deploying to plain Windows Sharepoint Services (WSS) works fine; but if you deploy your work to Sharepoint Portal Server (SPS); it doesnt; thats because in the ItemEventReceiver.xml file; the VSeWSS makes only the class entry and write the Guid of your class. For SPS; you need to enter not only assembly name but also the class name in .NET way. A sample entry is given below. Issue is whenever you create WSP file from VSeWSS; it will always append the entries of its format; so to have your WSP ready for SPS; you will need to edit the WSP file manually. The WSP file is basically a CAB file and you can use third party CAB tool to extract / replace the files in it.

<?xml version="1.0" encoding="utf-8"?>
<Elements Id="bd6deaa8-bb29-4c8f-8441-73ff0ea23007" xmlns="http://schemas.microsoft.com/sharepoint/">
  <Receivers ListTemplateOwner="fbcf9ee9-6883-4443-8049-3d7c15de2dee">
    <Receiver>
      <Name>ItemAdded</Name>
      <Type>ItemAdded</Type>
      <SequenceNumber>1</SequenceNumber>
      <Class>MySharepointArtifacts.ExpenseQueueItemEventReceiver</Class>
      <Assembly>MySharepointArtifacts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=81c24f946f8d399f</Assembly>
    </Receiver>
  </Receivers>
</Elements>

Tips

  1. The wizard picks the lists in the VSeWSS project; if you havnt imported your list into VSeWSS using the solution generator (the tip I gave in my earlier post); its the good time to do it before adding your event receiver. 
  2. You can move the ItemEventReceiver.xml/cs and ListEventReceiver.xml/cs files to the folder hosting schema.xml and *.aspx files of your list; its good to have coupled things together under single folder
  3. You can remove the ItemEventReceiver.xml and ListEventReceiver.xml files all together; and instead of using VSeWSS for creating a feature for your Event Receiver; can use third party app to register your event receivers later once your assembly is on server.
    • u2u’ Event Handler Explorer is highly recommended; its WinForms app with source; you can even extract the event registering code from it and write it into some ASPX file if you already have FixMyList.aspx file for fixing Lookup fields; the tip I gave in my earlier post!
Posted by khurram | 2 Comments

Sharepoint Lists and Visual Studio 2008 Extensions for Windows Sharepoint Services

From the BB13 video you must have learned that you can create Sharepoint Custom Lists from Visual Studio is quite easy. The experience over all is not very great; as you have to edit the XML files. The easiest way however is that you create your Custom List using the Sharepoint web interface; and once the list is well established; script it out to Visual Studio Extensions for Windows Sharepoint Services (VSeWSS) format using the VseWss’ Solution Generator.

image

Through this; you will get a VseWss PROJ file and if you open it side by side with your main project; you can copy/paste the Meta Data portion in schema.xml file of List to your project List’ schema.xml

image

  • Use some source control to track the changes being made in the schema.xml; always check from the previous before committing to ensure some field is not accidentally deleted. The Solution Generator sometime gets screwed and don't include all the fields.
  • Watch out for the “Version” attribute of the Fields\Field; if you already have deployed your project to the production server and you have change something like column type; don't forget to increment the version number.

 

image

  • The solution generator also don't include any Lookup field; the reason is quite logical; as the list instance gets generated later and at the time of design/development you don't know the GUID of the list instance; if you google/bing around you will find reason details and how people have proposed to use Feature Activation event to fix the lookup field source id. My suggestion will be to simply uncomment the lookup field xml and let it create with wrong source/field id when the feature gets activated or list instance gets generated from your list definition, and create a simple ASPX file with some code behind having the code that fixes the lookup field source/field ids; a sample code is given below

image

public class FixExpenseQueueListPage : Page
{
    protected override void OnLoad(EventArgs e)
    {
        SPWeb web = SPContext.Current.Web;
        bool previousValue = web.AllowUnsafeUpdates;
        try
        {
            web.AllowUnsafeUpdates = true;
            SPList lookupList = web.Lists["Expense Queue"];
            SPList mainList = web.Lists["Expense Groups"];
            string fieldName = "Expense Group";

            /*
             * <Field Type="Lookup" DisplayName="Expense Group" Required="TRUE" List="%LIST%" ShowField="Title" UnlimitedLengthInDocumentLibrary="FALSE" ID="{299e9129-cd4c-4f4f-bfe6-00f895ab5a99}" StaticName="Expense_x0020_Group" Name="Expense_x0020_Group" ColName="int1" RowOrdinal="0" SourceID="%FIELD%" Version="1" Group="" />
             */
            lookupList.Fields[fieldName].SchemaXml = @"<Field Type=""Lookup"" DisplayName=""Expense Group"" Required=""TRUE"" List=""{0}"" ShowField=""Title"" UnlimitedLengthInDocumentLibrary=""FALSE"" ID=""{299e9129-cd4c-4f4f-bfe6-00f895ab5a99}"" StaticName=""Expense_x0020_Group"" Name=""Expense_x0020_Group"" ColName=""int1"" RowOrdinal=""0"" SourceID=""{1}"" Version=""1"" Group="""" />".Replace(
                "{0}", mainList.ID.ToString()).Replace("{1}", mainList.Fields["Title"].Id.ToString());
            this.Response.Write("Lookup Field Fixed..<br />");

        }
        catch (Exception ex)
        {
            this.Response.Write(ex.ToString());
        }
        finally
        {
            web.AllowUnsafeUpdates = previousValue;
        }
    }
}
Posted by khurram | 1 Comments

Sharepoint Development with Visual Studio

Sorry for not posting regularly lately; I was away busy learning/using/preaching and coaching about Silverlight and Sharepoint. All in all, it was great learning expereince!

Sharepoint development is bit tricky to start with. Sharepoint is flexible and thus bit complicated to deal with. There are number of ways for Sharepoint Development. I opted to use Visual Studio Extensions for Windows Sharepoint Services (VseWss) whose latest version is v1.3 March 2009 CTP (Note its CTP; and has some issues) for Visual Studio 2008. They didn't finalized it; instead Visual Studio 2010 Beta 2 came recently which has these extensions built into it.

VseWss only works where Sharepoint itself is running; therefore you need Windows 2003 (atleast) as your OS (which by the way I already use and prefer over XP and Vista as development OS; I RDP to my desktop machine running Win2k3 from my notebook which runs Windows 7). The first tip is that install Windows Sharepoint Services with the login you used on the Windows 2003; choosing Basic mode; that also installs “Windows Internal Database” which is a variant of SQL Server 2005 Express Edition but without any limits of SQLEE. By doing this; not only that all the things gets configured; but also your login will automatically become Sharepoint Administrator and Site Collection Owner of the site it creates. And when you will install VseWss; you will be able to use it without any issues; otherwise setting up deployment with VseWss is bit tricky! Also dont forget to give correct url in the project’ debug setting; VseWss uses it to discover the Sharepoint site!

Sharepoint/VseWss combination gets broken often in early days; and uninstalling these both and reinstalling is the most easiest way to get back to the working state; and for this you might need to uninstall the Windows Internal Database as well; on 32bit OS the command is given below; after the command dont forget to delete the %windir%\sysmsi\ssee folder so that the Config/Content and Search databases gets deleted and on reinstalation you dont get any dormant thing back!

msiexec /x {CEB5780F-1A70-44A9-850F-DE6C4F6AA8FB} callerid=ocsetup.exe

Accessing Windows Internal Database instance using SQL Management Studio is also bit tricky; specify the following as database server with Windows Authentication and you will get connected!

\\.\pipe\mssql$microsoft##ssee\sql\query

Next for debugging you need to specify the following setting in your sharepoint site’ web.config

<compilation batch="false" debug="true">

You also need to consider that last Released version of Sharepoint Services; is pre .NET 3/3.5; so before using any Ajax / Ajax Toolkit or Silverlight 2’ Server Control; you need to first setup the sharepoint web site and the most easiest way is that you open the site folder using Visual Studio’ Add Existing Web Site…Visual Studio 2008 prompts to convert it!

Sharepoint works seamless if you deploy the things into Global Assembly Cache (GAC); simply drag/drop the assembly into %windir%\Assembly; so if you are using Silverlight 2’ Server Control; deploy that assembly into GAC and register it as SafeControl into sharepoint site’ web.config. If you have some other version of assembly; discover its version and public key token by opening %windir%\Assembly and right click > Properties of the assembly.

<SafeControl Assembly="System.Web.Silverlight, Version=2.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI.SilverlightControls" TypeName="*" Safe="True" AllowRemoteDesigner="True" />

WSP Window is Visual Studio Addin that comes with VseWss and through this; you can view WSP content; the output of the VseWss project is basically a WSP and behind the scene PKG folder gets created having feature XML files. If you are using Source Control; dont forget to add this folder into source control. If you are using Team Foundation Server; simplest way is to include PKG folder into the project. Dont forget to enable View All Files and adding any new folder that gets created whenever you add some new sharepoint feature into your VseWss project.

I will strongly recommend to watch BB13 video (Creating SharePoint Applications with Visual Studio 2008) from PDC 2008; and you will realize where/how VseWss can help you. Channel 9 also has few more screencasts on VseWss which are worth seeing.

From these videos you will learn how you can deploy custom resources (images, HTML files and even ASPX files) into /_layout/; I will suggest to add “12” folder as Toolbar into your Taskbar for easier access to 12 Folder Hive! If you are planning to deploy ASPX files; you can add the ASPX file by adding HTML Page into the VseWss project and renaming it to ASPX. Second, as said earlier; Sharepoint works seamless if you deploy the things into GAC; so when creating the VseWss project; choose Full Trust (Deploy to GAC) option and thirdly  in the ASPX file you might need to give few more details about your assembly; else you will experience Assembly Not Found errors! You can discover the public key token of your assembly the same way like I said about System.Web.Silverlight above!

<%@ Page Language="C#" AutoEventWireup="true" Inherits="MySharepointArtifacts.MyPage, MySharepointArtifacts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=81c24f946f8d399f" %>

ASP.NET MVC 2

Visual Studio 2010 Beta 2 is recently made generally available to try and it has ASP.NET MVC2 Preview 2 out of box. In ASP.NET MVC2; there is a breaking change from ASP.NET MVC 1. The ASP.NET MVC’ built in JSON support will only serve for POST request and discards GET requests due to JSON Vulnerability. Michael Campbell has written a detailed article on DevProConnections. The article and the links it has; are must read for AJAX developers using JSON.

You don't need Visual Studio 2010 Beta 2 to try ASP.NET MVC2; ASP.NET MVC2 is side by side release and you can use both ASP.NET MVC1 and ASP.NET MVC2 with Visual Studio 2008.

Posted by khurram | 1 Comments
Filed under:

.NET 4: Parallel Programming – Cancelling/Exception Handling with Task Parallel Library

There are lot of goodies in .NET 4 for Parallel Programming. There is even a separate dedicated section on it. The following picture from that section explains the four categories of improvement in Framework just for this.

I mentioned earlier that previously I used Abortable Threadpool to implement cancelling work under specific condition. With ThreadPool we never had an easy way to queue the batch of work, know when that batch is completed and do exception handling properly. Things have significantly improved with Task Parallel Library; which is integrated with ThreadPool and resolves all the issues I mentioned plus lot more. Here is small app that does cancelling the tasks after certain time out and investigates the exception if any thrown by the task!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace TplConsoleApplication
{
    class Program
    {
        static Random random = new Random();
        static void LongWork(int deviceIdentifier, CancellationToken ct)
        {
            Thread.Sleep(2000);
            int r = random.Next(5);
            //Simulating that certain device fails
            if (r > 3)
                throw new ApplicationException(string.Format("{0} failed (by random)", deviceIdentifier));
            Thread.Sleep(r * 2000);
        }
 
        static void Main(string[] args)
        {
            var tokenSource = new CancellationTokenSource();
            var token = tokenSource.Token;
 
            List<Task> listOfTasks = new List<Task>();
 
            for (int i = 0; i < 10; i++)
            {
                int j = i;  //The anonymous delegate will use the latest value by design
                            //If we use the for variable value it will always be the last one
                listOfTasks.Add(Task.Factory.StartNew(() => LongWork(j, token), token));
            }
 
            Task[] tasks = listOfTasks.ToArray();
 
            int seconds = 3;
            Thread.Sleep(1000);                     //Give the tasks a second to start
            Console.WriteLine("Waiting {0}secs", seconds);
            Thread.Sleep(seconds * 1000);           //We have 10secs to do all the tasks
            tokenSource.Cancel();                   //After that we need to abort uncompleted tasks
                                                    //If we want we can return/exit here; the cancelled tasks will
                                                    //  be taken care
 
            #region The region is optional; in case we want to know what happened
 
            try
            {
                Task.WaitAll(tasks);
            }
            catch (AggregateException e)
            {
                foreach (var v in e.InnerExceptions)
                {
                    if (!(v is TaskCanceledException))
                        Console.WriteLine(v.Message);
                }
            }
 
            for (int i = 0; i < tasks.Length; i++)
                Console.WriteLine("task[{0}] status is now {1}, IsCancelled={2}", i, tasksIdea.Status, tasksIdea.IsCanceled);
 
            #endregion
 
            Console.ReadLine();
        }
    }
}
Posted by khurram | 0 Comments
Filed under:
More Posts Next page »