Jul 20, 2012

Issues with writing to the event log from an ASP.net application

During a recent project I faced with a problem :

I had a form whose content needed to be saved to an Oracle DB.
I also had a fall back code which in case of the failure of the former would write the same data to a SQL server DB as a temporary repository of the form data.

For some reasons my code to write to a Oracle DB were not going through and neither was my code to write to a SQL server temporary table.
Automatically I was checking the Event Log and tried to figure out what was wrong.
I had elaborate Event Logging code all over the project to help me understand what is going on under the hood, which will help me debug. But alas, there was no new log created for the web app at all!!!
There were no relevant entries in the Application Log as well.

I tried concentrating on the fix to the original problem, and tried many random SQL Server  and Oracle fixes but I was unable to reach a solution. This went on throughout the day..
After a lot of misses I finally decided to fix the Event Log issue first… (And how prophetic was it!!!)
So I was already aware of the cause, ASP.Net runs on a lower privilege, which prevents it to write to the logs.. I had faced it earlier in a SharePoint project and had added a code to raise the privilege of the particular method which writes to the log.. Should I apply that again? I thought of digging  deeper… After a lot of scouring through the net in MSDN, StackOverflow and multiple other blogs.. I found out that everybody was suggesting a different approach.. Then I came across a MSDN kb article which gave 2 possible fixes, Firstly, to apply some registry hacks which I am sure most IT admins would not allow me to do on a prod server.. and Secondly to add the Event Logs and Event Source Names manually.. There was a third way too, that to raise the privilege of the ASP.net account to a higher one.. or to use a admin account  as the App pool account.. But then  the reason ASP.net was designed to run on a lower privilege was for some reasons.. right? Namely from stopping access to directories outside the current one or to access other resources etc.. That would be defeated.

I liked the second approach and developed a small tool to create the Event Logs and Event Source Names from a Config file.. And lo the event logging was working for my website… So what was happening? It appears that writing a new event is a common activity which a less privileged thread can perform, but Creating Event Logs and Event Source Names is considered to be Admin tasks, which the ASP.net account is not capable of doing.

So after the Event logging issue was sorted out I now concentrated solving the original problem.. The logs clearly showed that the Oracle connection could not be opened due to some tnsnames.ora issue, and the fall back insertion was failing because the SP name which was hardcoded in the app had an extra “_” (underscore) character..
Moral of the story: Event Logging should be set up as early as possible.

Jul 17, 2012

TFS VS 2010 deployment issue: some files were just not getting deployed..

When the daily build ran today morning and after the deployment was successfully completed, I tried testing some code that I had checked in. I got a file not found error for one of the cshtml file that wwas recently added.

We use a Web Deployment Project, so after the daily build the web content gets pushed into the Web server.. Use (Team Build + Web deployment + Web deploy + VS 2010 framework for this.. I used Vishal Joshi’s steps to set it up.. http://vishaljoshi.blogspot.sg/2010/11/team-build-web-deployment-web-deploy-vs.html)

Meanwhile, coming back to the problem, I checked everything.. found that it was present in the TFS, local folder, created another mapped folder and executed “Get Latest version” Command, and found that it was part of the list of files. All other files were getting properly deployed. The problem was with one cshtml file and couple of scripts. All of which were recently introduced.

Then why wasn’t it getting pushed??? After a lot of brain racking and investigation I found the solution:

For some reason the Build Action property of these files were getting set as “None”. After I changed them back to “Content”, they started flowing smoothly into the web server after the build.

How to change?

In Visual Studio, right-click on the file and go to Properties.

Under the file's properties, make sure that Build Action is set to Content. Otherwise it won't be published via web deploy.

image001

Jul 3, 2012

My tryst with the SQL Server 2008 R2 Full Text Search

In a recent project which had a requirement of a search, I had proposed Full Text Search. Even though I had a brief knowledge of how it works through a online tutorial when I was at MS, I never had dirtied my hands in that technology. So here’s how I went about it.
1. Install the Full text Capability.
  • - The Standard installation will not have this feature and you will have to install it over it.  Funnily, it will still show the Full text nodes in the Object explorer, giving a false sense of assurance that you have it installed already. It may even let you create a “Full Text Catalog”.
    • To make sure if you have it installed, run the following query on a new Query Window:
      SELECT FullTextServiceProperty('IsFullTextInstalled')
       
       
  • The URL to the MSDN page for the detailed capability of Full-TextSearch http://msdn.microsoft.com/en-us/library/ms142571.aspx#like
INSTALLATION:
CONFIGURATION:
  • There are two ways of working with Full text search:
    • Search on indexed Columns. Data types supported:
      • char
      • nchar
      • varchar
      • nvarchar
      • text
      • ntext
    • Search based on indexed documents. Extensions Supported:
      • The search uses a concept called iFilter to parse and index the text of the documents.
        By default all MS text type extensions are automatically supported like,
      • .doc
      • .txt
      • docx
      • extensions like pdf etc can be supported after installing the appropriate filters.
Configuring Full text for Database columns:  (excerpted from Pinal Dave’s blog)
Full Text Index helps to perform complex queries against character data. These queries can include word or phrase searching. We can create a full-text index on a table or indexed view in a database. Only one full-text index is allowed per table or indexed view. The index can contain up to 1024 columns. Software developer Monica who helped with screenshots also informed that this feature works with RTM (Ready to Manufacture) version of SQL Server 2008 and does not work on CTP (Community Technology Preview) versions.
    To create an Index, follow the steps:
    1. Create a Full-Text Catalog
    2. Create a Full-Text Index
    3. Populate the Index
    1) Create a Full-Text Catalog



    Full – Text can also be created while creating a Full-Text Index in its Wizard.
    2) Create a Full-Text Index









    3) Populate the Index


    FYI, All the above mentioned steps can also be performed using scripts instead of the wizards.
  • Querying the Full text indexed columns:
  • As the Index Is created and populated, you can write the query and use in searching records on that table which provides better performance.
    For Example,
    We will find the Employee Records who has “Marking “in their Job Title.
    FREETEXT( ) Is predicate used to search columns containing character-based data types. It will not match the exact word, but the meaning of the words in the search condition. When FREETEXT is used, the full-text query engine internally performs the following actions on the freetext_string, assigns each term a weight, and then finds the matches.
    • Separates the string into individual words based on word boundaries (word-breaking).
    • Generates inflectional forms of the words (stemming).
    • Identifies a list of expansions or replacements for the terms based on matches in the thesaurus.
    CONTAINS( ) is similar to the Freetext but with the difference that it takes one keyword to match with the records, and if we want to combine other words as well in the search then we need to provide the “and” or “or” in search else it will throw an error.
    USE AdventureWorks2008GO
    SELECT BusinessEntityID, JobTitle
    FROM HumanResources.Employee
    WHERE FREETEXT(*, 'Marketing Assistant');

    SELECT BusinessEntityID,JobTitle
    FROM HumanResources.Employee
    WHERE CONTAINS(JobTitle, 'Marketing OR Assistant');

    SELECT BusinessEntityID,JobTitle
    FROM HumanResources.Employee
    WHERE CONTAINS(JobTitle, 'Marketing AND Assistant');
    GO


    Besides the CONTAINS and FREETEXT Keywords, there are 2 more keywords which are available. They are CONTAINSTABLE and FREETEXTTABLE.
    The major difference  between these 2 and the previous 2 are that these 2 would dump the content of the search into a table, which can be queried further.
    This is mostly used to sort the fetched results by Ranking. The rank is based on a Relevancy factor associated with each row. SQL Server Free text engine decides on the relevance of the results fetched based on its internal algorithm.
    Definitions:
    CONTAINSTABLE
    http://msdn.microsoft.com/en-us/library/ms189760(v=SQL.90).aspx Returns a table of zero, one, or more rows for those columns containing character-based data types for precise or fuzzy (less precise) matches to single words and phrases, the proximity of words within a certain distance of one another, or weighted matches. CONTAINSTABLE can be referenced in the FROM clause of a SELECT statement as if it were a regular table name.
    Queries using CONTAINSTABLE specify contains-type full-text queries that return a relevance ranking value (RANK) and full-text key (KEY) for each row. The CONTAINSTABLE function uses the same search conditions as the CONTAINS predicate.
    FREETEXTTABLE
    http://msdn.microsoft.com/en-us/library/ms177652(v=SQL.90).aspxReturns a table of zero, one, or more rows for those columns containing character-based data types for values that match the meaning, but not the exact wording, of the text in the specified freetext_string. FREETEXTTABLE can be referenced in the FROM clause of a SELECT statement like a regular table name.
    Queries using FREETEXTTABLE specify freetext-type full-text queries that return a relevance ranking value (RANK) and full-text key (KEY) for each row.
     
    eg.,
    CONTAINSTABLE:
    SELECT FT_TBL.Description, FT_TBL.CategoryName, KEY_TBL.RANK
    FROM Categories AS FT_TBL
    INNER JOIN
    CONTAINSTABLE (Categories, Description, '("sweet and savory" NEAR sauces)
    OR
    ("sweet and savory" NEAR candies)' )
    AS
    KEY_TBL ON FT_TBL.CategoryID = KEY_TBL.[KEY]
    ORDER BY KEY_TBL.RANK DESC

    FREETEXTTABLE:
    SELECT KEY_TBL.RANK, FT_TBL.Description
    FROM Production.ProductDescription AS FT_TBL
    INNER JOIN
    FREETEXTTABLE(Production.ProductDescription, Description, 'perfect all-around bike')
    AS
    KEY_TBL ON FT_TBL.ProductDescriptionID = KEY_TBL.[KEY]
    ORDER BY KEY_TBL.RANK DESC

  • Other important keywords are
    • Near, which does a proximity based search, for the mentioned set of words.
    • FORMSOF : you can choose to have your CONTAINS search expanded to capture different generations of a word by using the FORMSOF term. This term accepts two arguments – INFLECTIONAL or THESAURUS. The INFLECTIONAL argument will expand the search phrase to search on all conjugations and declensions or each word in the search phrase, and the THESAURUS argument will enable a thesaurus expansion on the search phrase.
      • e.g., Select * from TableName where CONTAINS(*,'FORMSOF(INFLECTIONAL,run)')
    • Thesaurus :
      • While querying a Full text indexed column we may also choose to return back synonyms of the searched term by fetching from the thesaurus!
        • FREETEXT and FREETEXTTABLE queries use the thesaurus by default. CONTAINS and CONTAINSTABLE support an optional THESAURUS argument.
        • e.g., Select * from TableName where CONTAINS(*,'FORMSOF(THESAURUS,run)')

    • Types of Search possible through FTS:
    • Improved querying tools
      • Keywords. Document creators (or trained indexers) are asked to supply a list of words that describe the subject of the text, including synonyms of words that describe this subject. Keywords improve recall, particularly if the keyword list includes a search word that is not in the document text.
      • Field-restricted search. Some search engines enable users to limit free text searches to a particular field within a stored data record, such as "Title" or "Author."
      • Boolean queries. Searches that use Boolean operators (for example, "encyclopedia" AND "online" NOT "Encarta") can dramatically increase the precision of a free text search. The AND operator says, in effect, "Do not retrieve any document unless it contains both of these terms." The NOT operator says, in effect, "Do not retrieve any document that contains this word." If the retrieval list retrieves too few documents, the OR operator can be used to increase recall; consider, for example, "encyclopedia" AND "online" OR "Internet" NOT "Encarta". This search will retrieve documents about online encyclopedias that use the term "Internet" instead of "online." This increase in precision is very commonly counter-productive since it usually comes with a dramatic loss of recall.[5]
      • Phrase search. A phrase search matches only those documents that contain a specified phrase, such as "Wikipedia, the free encyclopedia."
      • Concept search. A search that is based on multi-word concepts, for example Compound term processing. This type of search is becoming popular in many e-Discovery solutions.
      • Concordance search. A concordance search produces an alphabetical list of all principal words that occur in a text with their immediate context.
      • Proximity search. A phrase search matches only those documents that contain two or more words that are separated by a specified number of words; a search for "Wikipedia" WITHIN2 "free" would retrieve only those documents in which the words "Wikipedia" and "free" occur within two words of each other.
      • Regular expression. A regular expression employs a complex but powerful querying syntax that can be used to specify retrieval conditions with precision.
      • Fuzzy search will search for document that match the given terms and some variation around them (using for instance edit distance to threshold the multiple variation)
      • Wildcard search. A search that substitutes one or more characters in a search query for a wildcard character such as an asterisk. For example using the asterisk in a search query "s*n" will find "sin", "son", "sun", etc. in a text.

    • The concept of Stopwords/ noisewords:
      • words (SQL Server 2005 calls them noise words, 2008 stopwords). SQL Server has a list of around 150 common words, which are ignored by the Full Text Search engine. e.g. about, after, all, also, an, and, another etc. You can view the English stopwords in SQL Server 2008 like so:
        select * from sys.fulltext_system_stopwords where language_id = 1033
        In my table there is a Question titled “What are building consents?”. If we search for “what are building consents” like so:
        SELECT [Key], [Rank], 1
        FROM CONTAINSTABLE(dbo.Question, QuestionText, '"what*" AND "are*" AND "building*" AND "consents*"', 100)

        because “are” is a stopword (and so is “what”) we won’t get any results!
        There is a workaround – to wipe the list of stop words! The problem with doing this is that the list of stop words is setup server-wide on the SQL Server itself.



    •  Why Full text Search? : Difference between a regular LIKE search and FULL-TEXT search:
      Compiled from other posts and MSDN -
      •  In general, there is a tradeoff between "precision" and and "recall". High precision means that fewer irrelevant results are presented (no false positives), while high recall means that fewer relevant results are missing (no false negatives). Using the LIKE operator gives you 100% precision with no concessions for recall. A full text search facility gives you a lot of flexibility to tune down the precision for better recall.



        Most full text search implementations use an "inverted index". This is an index where the keys are individual terms, and the associated values are sets of records that contain the term. Full text search is optimized to compute the intersection, union, etc. of these record sets, and usually provides a ranking algorithm to quantify how strongly a given record matches search keywords.



        The SQL LIKE operator can be extremely inefficient. If you apply it to an un-indexed column, a full scan will be used to find matches (just like any query on an un-indexed field). If the column is indexed, matching can be performed against index keys, but with far less efficiency than most index lookups. In the worst case, the LIKE pattern will have leading wildcards that require every index key to be examined. In contrast, many information retrieval systems can enable support for leading wildcards by pre-compiling suffix trees in selected fields.



        Other features typical of full-text search are



        •lexical analysis or tokenization—breaking a block of unstructured text into individual words, phrases, and special tokens

        •morphological analysis, or stemming—collapsing variations of a given word into one index term; for example, treating "mice" and "mouse", or "electrification" and "electric" as the same word

        •ranking—measuring the similarity of a matching record to the query string

        -----------------------------------------------------------------------------------
        FTS involves indexing the individual words within a text field in order to make searching through many records quick. Using LIKE still requires you to do a string search (linear or the like) within the field.


        -------------------------------------------------------------------------------------
        Full Text Searching (using the CONTAINS) will be faster/more efficient than using LIKE with wildcarding. Full Text Searching (FTS) includes the ability to define Full Text Indexes, which FTS can use. Dunno why you wouldn't define a FTS index if you intended to use the functionality...




        LIKE with wildcarding on the left side (IE: LIKE '%Search') can not use an index (assuming one exists for the column), guaranteeing a table scan. I haven't tested & compared, but regex has the same pitfall. To clarify, LIKE

        -------------------------------------------------------------------------------------
        FTS is more efficient, powerful (especially for Word Breakers and stemming functionalities) ... but check your requirements because sometimes DBs don't support all languages for example MSSQL doesn't support Greek (check on this page http://msdn.microsoft.com/en-us/library/ms176076(v=sql.110).aspx )





    Continued in Part 2: File based Full text Search

    Jun 28, 2012

    Odd Outlook Error

    In a recent Pet Project , I was working on an application which used the MS Office libraries, specifically the Outlook ones.

    At almost the very start of the code I was trying to run the following  :

           Microsoft.Office.Interop.Outlook.Application app = null;
         app = new Microsoft.Office.Interop.Outlook.Application();

    During runtime, the application was always throwing an exception while executing the 2nd line.

    Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80080005.

    After trying many options to correct it, I stumbled upon a document which dealt with some similar issues. I tried them and Lo, it worked..

    Apparently these errors were triggered because I was running Outlook and the application on different user permission levels (one of them as administrator and the other one as regular user). I changed both to Administrator (since my VS.Net link is modified to open always in admin mode) and it all started working smoothly. Serendipity!!

    N.B.: These errors only appear if I already have an Outlook 2010 instance started. If Outlook is not started, the application can run smoothly (it can start an Outlook instance by itself).

    Jun 20, 2012

    How to work with Pre-processor directives for conditional execution

    Recently, we had to use a lot of conditional execution of our codes.
    The situation was such:
    1. In a ASP.Net MVC 3 Unit test project we had to read some variables from the static application bag.

    2. Even though we cud inject into and read from the Session Bag, we couldn’t find a easy way for the Application.

    3. Using a Mock framework would have been the right solution, but we didn’t have the time to introduce a mocking framework into the solution.

    4. From our experience of using the Pre-processor directive, “# if DEBUG” earlier, we thought of  depending on the other BUILD CONFIGURATIONS for the same effect. Such that when we run the UNIT TESTS, with a TEST Config, it should return back a fixed value instead of trying to read from the Application Bag.

    5. It wasn’t easy, not much help online either, most advocated using the #define statement at the beginning of the class, which was impractical, since it would require recompile to shift between the different configurations.

     

    Without further ado, lets step through the steps which we took to achieve this.

    0. Create a Test Solution.

      • Add 2 Projects. A Windows Project and a class library.
      • The Windows App Project contains a form, with a Button and a text box.
      • The Class Library, mimics a Utility project which will lookup from Application or other Cache values and will be called from all other layers.
      • Name the Class Library Project, as Common. Add a class Factory, which has a static property, MyProperty, which returns an int. 
        • image
      • On the Button Click event of the Form call the Factory.MyProperty. Display the value in the Text box
        • image

    1. Create a new Build Configuration Item for the Unit Tests.

      • Click on the Configuration Manager, from the Menu
        • image
      • From the “Active Solution Configurations” combo, Select New…
        • image 
      • Add a new Config, lets say UNITTEST, From the “Copy Settings From” combo, select appropriate config, lets select Debug
        • image
      • For Both the Projects set the Build Configuration as “UNITTEST”
        • image
      • Open the Property Page for the “Common” Project and click on the “Build” Tab
      • From the “Configurations” combo, select,  “UNITTEST”
      • In the “Conditional Compilation symbols” textbox, enter “UNITTEST”
        • image
      • Now add the conditional statement targeting the Build Configurations into the Factory Class
        • image
      • We are done. Now the breakpoint will enter the # if UNITTEST section, when when the app is run with “UNITTEST” Build Configuration. Costly exercise of writing Mocking framework averted!
      • ***Remember, the daily build must not use this configuration, while pushing the binaries to the test environments!

     

     

         

         

    Apr 3, 2012

    Configure Full Text Search in Sql Server 2008 R2/ Express

    SQL SERVER - 2008 - Creating Full Text Catalog and Full Text Search

    (Source:http://www.codeproject.com/Articles/29237/SQL-SERVER-2008-Creating-Full-Text-Catalog-and-Ful)

    Full Text Index helps to perform complex queries against character data. These queries can include word or phrase searching. We can create a full-text index on a table or indexed view in a database. Only one full-text index is allowed per table or indexed view. The index can contain up to 1024 columns. Software developer Monica who helped with screenshots also informed that this feature works with RTM (Ready to Manufacture) version of SQL Server 2008 and does not work on CTP (Community Technology Preview) versions.

    To create an Index, follow the steps:

    1. Create a Full-Text Catalog
    2. Create a Full-Text Index
    3. Populate the Index

    1) Create a Full-Text Catalog


    < !--[if gte vml 1]> <![endif]-->

    Full – Text can also be created while creating a Full-Text Index in its Wizard.

    2) Create a Full-Text Index

    <!--[if gte vml 1]> <![endif]-->

    3) Populate the Index

    As the Index Is created and populated, you can write the query and use in searching records on that table which provides better performance.

    For Example,

    We will find the Employee Records who has “Marking “in their Job Title.

    FREETEXT( ) Is predicate used to search columns containing character-based data types. It will not match the exact word, but the meaning of the words in the search condition. When FREETEXT is used, the full-text query engine internally performs the following actions on the freetext_string, assigns each term a weight, and then finds the matches.

    • Separates the string into individual words based on word boundaries (word-breaking).
    • Generates inflectional forms of the words (stemming).
    • Identifies a list of expansions or replacements for the terms based on matches in the thesaurus.

    CONTAINS( ) is similar to the Freetext but with the difference that it takes one keyword to match with the records, and if we want to combine other words as well in the search then we need to provide the “and” or “or” in search else it will throw an error.

    USE AdventureWorks2008
    GO

    SELECT BusinessEntityID, JobTitle
    FROM HumanResources.Employee
    WHERE FREETEXT(*, 'Marketing Assistant');

    SELECT BusinessEntityID,JobTitle
    FROM HumanResources.Employee
    WHERE CONTAINS(JobTitle, 'Marketing OR Assistant');

    SELECT BusinessEntityID,JobTitle
    FROM HumanResources.Employee
    WHERE CONTAINS(JobTitle, 'Marketing AND Assistant');
    GO

    Conclusion

    Full text indexing is a great feature that solves a database problem, the searching of textual data columns for specific words and phrases in SQL Server databases. Full Text Index can be used to search words, phrases and multiple forms of word or phrase using FREETEXT() and CANTAINS() with “and” or “or” operators.

    Mar 24, 2012

    How to debug the ASP.Net MVC framework

    http://weblogs.asp.net/gunnarpeipman/archive/2010/07/04/stepping-into-asp-net-mvc-source-code-with-visual-studio-debugger.aspx

    Using Visual Studio symbols and source files makes debugging much easier. I am specially happy about ASP.NET MVC 2 source files because I develop on ASP.NET MVC 2 almost every day. You may also find other useful symbols and source files. In this posting I will show you how to get ASP.NET MVC source to your computer and how to use it.

    1. Debug options

    Open options dialog and make sure you have check boxes set as on following image in red boxes.

    debugoptions

    2. Download symbols and source

    Now we have to allow downloading symbol files. By default the location of symbols is somewhere under application user data folder. I prefer some location on some drive root usually.

    debugsymbols

    NB! I chose “All modules, unless excluded” to get everything from symbol server. If you need only MVC symbols then choose “Only specified modules” and add System.Web.MVC there (you can also add other modules you need).

    After clicking OK you see window like on following image. Make a cup of coffee and wait until symbols are downloaded. It takes a while.

    downloadingpublicsymbols

    3. Debugging

    Open your ASP.NET MVC application, put breakpoint somewhere in code and run it. Wait until code execution hits the breakpoint.

    aspnetmvcbreakpoint

    When breakpoint is hit click Step-in and Step-over icons to go to some line where some method of ASP.NET MVC is called. On this method click Step-in.

    4. Source code download

    If ASP.NET MVC source is not there yet then you can see EULA windows like on the following image.

    aspnetmvcsourceeula

    If you don’t plan to do anything illegal then click Accept button. You may get some warnings about file downloads and UTF-8 encoding. Say Yes and when ASP.NET MVC source is downloaded you can see something like on the following image.

    aspnetmvccontrollersource

    Well, we are in View() method of controller class. Not bad at all! :)

    More symbols

    You can find more symbols and source files from Microsoft Reference Source Code Center. For .NET Framework you can find only symbols right now. Hopefully source is also coming soon.

    Mar 4, 2012

    Installing SQL Server Management Studio for Sql Server 2008 R2 Express

    Step by Step Solution for Installing SSME
    ----------------------------------------------------------
    0. If you are using Server 2008, Install Windows PowerShell using these instructions: http://www.tech-recipes.com/rx/2521/windows_server_2008_install_windows_powershell/. Otherwise download and install it from here: http://technet.microsoft.com/en-ca/scriptcenter/dd772288.aspx



    1. Download and run the SSME installer from http://www.microsoft.com/downloads/details.aspx?familyid=08e52ac2-1d62-45f6-9a4a-4b76a8564a2b&displaylang=en


    2. Click Installation on the left side of the the wizard.


    3. Select "New SQL Server stand-alone installation or add features to an existing installation". Click OK.


    4. On the Setup Support Files page, select Install.


    5. On the Setup Support Rules page, click Next (the Windows Firewall warning is ok).


    6. On the Installation Type page of the wizard, select "Perform a new installation of SQL Server 2008", then click Next. (I realize that this is counter-intuitive, but if you select "Add features to an existing instance of SQL Server 2008", you will be met with a greyed out pre-selected option to install the SQL Client Connectivity SDK, and you will not even see an option to install "Management Tools - Basic".) You will see that SQLEXPRESS is recognized as an installed instance.


    7. The Product Key screen is all greyed out with the "Specify a free edition" selected. Click Next.


    8. Agree to the License Terms as usual. Click Next.


    9. On the Feature Selection page, you will FINALLY have a blank checkbox next to "Management Tools - Basic". Put a check in that box. SQL Client Connectivity SDK is selected and greyed out by default; so is the install location. Click Next.


    10. Click Next on the Disk Space Requirements screen.


    11. Check both boxes to send error info to Microsoft if you wish. I usually do so that they can make the product better. :-) Click Next.


    12. Click Next on Installation Rules page if your system passed.


    13. Click Install on the Ready to Install page.


    14. Hopefully you will see a "Management Tools - Basic Success" message on the Installation Progress page of the wizard. Click Next.


    15. You should see a "Your SQL Server 2008 installation completed successfully" message on the Complete page. Click Close.





    Sep 13, 2010

    WCF Client side Aync Calls: Using BeginXXX EndXXX calls and use the ManualResetEvent for thread marshalling

    Sample code:
    1. Generate the Proxy with the /async switch
    e.g.: svcutil.exe /serializer:DataContractSerializer /async /out:ServiceProxy.cs, "https://www.abcd.com/ServiceHost/UserManagement.svc"

    2. Instantiate the proxy client:
    e.g.:
    UserManagementClient userClient = null;
    endPtKey = "UserManagement_WindowsEndpoint";
    userClient = new PartnerContactManagementClient(endPtKey);
    User[] users = null;

    3. Declare and Instantiate the manualresetEvents
    e.g.:
    ManualResetEvent[] handles = new ManualResetEvent[2];
    handles[0] = new ManualResetEvent(false);
    handles[1] = new ManualResetEvent(false);

    4. Use the BeginXXX / EndXXX way of invoking aync calls:
    (The following example is made using anonymous methods, so that we can use the local variables.)
    e.g.:
    AsyncCallback contactAsyncCallback = delegate(IAsyncResult userResult)
    {
    try
    {
    users = userClient.EndLookupUser userResult);
    }
    catch (Exception ex)
    {
    exceptions.Add(ex);
    }
    finally
    {
    ////Set the waithandle signal to true
    handles[0].Set();
    }
    };

    ////The Begin Invoke Call
    int userId = "12345";
    contactClient.BeginLookupUser(userId, contactAsyncCallback, null);


    5. Make the second such Async call:
    e.g.:
    UserRoles[] userRoles = null;

    AsyncCallback roleAsyncCallback = delegate(IAsyncResult roleResult)
    {
    try
    {
    userRoles = userClient.EndLookupUserRoles(roleResult);
    }
    catch (Exception ex)
    {
    exceptions.Add(ex);
    }
    finally
    {
    ////Set the waithandle signal to true
    handles[1].Set();
    }
    };

    userClient.BeginLookupUserRole(userid, accountAsyncCallback, null);

    6. Wait for the Calls to return:
    e.g.:
    WaitHandle.WaitAll(handles);
    ////At this point both the reset event would join back
    ////Close both the handles manually
    handles[0].Close();
    handles[1].Close();
    ////Write the follow up code

    Sep 3, 2010

    Patterns and Practices: Microsoft Application Blocks

    List of all the Microsoft Application Blocks:

    1. Data Access Application Block v 2.0:
    http://www.microsoft.com/downloads/details.aspx?FamilyId=F63D1F0A-9877-4A7B-88EC-0426B48DF275&displaylang=en

    The Data Access Application Block encapsulates performance and resource management best practices and can easily be used as a building block in your own .NET application. If you use it, you will reduce the amount of custom code you need to create, test and maintain.
    ==========================================================


    2. Exception Management Application Block:
    http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=8CA8EB6E-6F4A-43DF-ADEB-8F22CA173E02

    The Exception Management Application Block provides a simple yet extensible framework for handling exceptions. With a single line of application code you can easily log exception information to the Event Log or extend it by creating your own components that log exception details to other data sources or notify operators, without affecting your application code. The Exception Management Application Block can easily be used as a building block in your own .NET application.
    =======================================================


    3. Authorization and Profile Application Block :
    http://www.microsoft.com/downloads/details.aspx?familyid=ba983ad5-e74f-4be9-b146-9d2d2c6f8e81&displaylang=en

    The Authorization and Profile Application Block provides you with an infrastructure for role-based authorization and access to profile information.
    ===================================================


    4. Aggregation Application Block:
    http://microsoft.com/downloads/details.aspx?FamilyId=9058F345-E5FE-42FC-B40B-14EBDD182F48&displaylang=en

    The Aggregation Application Block is a .NET Framework extension that allows you to easily manage and coalesce information from various service providers and other systems and present that information to users.
    ======================================================


    5. Asyncronous invocation application block:
    http://msdn.microsoft.com/library/en-us/dnpag/html/PAIBlock.asp?frame=true
    ======================================================

    6. Configuration Management Application Block :
    http://www.microsoft.com/downloads/details.aspx?familyid=85cb1c53-8ca7-4a92-85e3-e4795bd27feb

    The Configuration Management Application Block is an easy to use mechanism through which you can read and write application configuration data.
    ======================================================

    7. Updater Application Block:
    http://www.microsoft.com/downloads/details.aspx?familyid=c6c17f3a-d957-4b17-9b97-296fb4927c30

    In medium to large organizations, it is common to want to keep all instances of a desktop application up to date with the latest version of executables, libraries, and other files. The Updater Application Block provides an extensible framework that companies can use to create updateable applications
    ======================================================

    8. User Interface Processes Application Block v 2.0:
    http://www.microsoft.com/downloads/details.aspx?FamilyId=98C6CC9D-88E1-4490-8BD6-78092A0F084E&displaylang=en

    The User Interface Process Application Block provides a simple yet extensible framework for developing user interface processes. It is designed to abstract the control flow and state management out of the user interface layer into a user interface process layer.
    =====================================================


    9. Web Services Facade for legacy applications:
    http://msdn.microsoft.com/library/en-us/dnpag/html/WSFacadeLegacyApp.asp?frame=true
    =====================================================


    10. Caching Application Block:
    http://microsoft.com/downloads/details.aspx?FamilyId=B55164C9-94C8-4077-AA29-AFE4074746DE&displaylang=en

    The Caching Application Block has been designed to encapsulate Microsoft's recommended best practices for caching in .NET applications
    =====================================================


    11. Smart Client Offline Application Block:
    http://www.microsoft.com/downloads/details.aspx?FamilyId=BD864EB5-56B3-43A5-A964-6F23566DF0AB&displaylang=en

    The Offline Application Block, is intended to serve as an architectural model for developers who want to add offline capabilities to their smart client applications.
    =====================================================


    12. Logging Application Block:
    http://www.microsoft.com/downloads/details.aspx?FamilyId=24F61845-E56C-42D6-BBD5-29F0D5CD7F65&displaylang=en

    This block is a reusable code component that uses the Microsoft Enterprise Instrumentation Framework (EIF) and the Microsoft .NET Framework to help you design instrumented applications.
    =======================================================


    13. Persistent Asynchronous Invocation Application Block :
    http://microsoft.com/downloads/details.aspx?FamilyId=794EC811-B5EA-46AE-BAA4-69A3DEADD38E&displaylang=en

    The Microsoft Asynchronous Invocation Application Block manages asynchronous communication between a Web client and one or more foreign service providers (FSP).
    ===========================================================

    Other important links:
    1. Microsoft Patterns and Practices Application Blocks and Enterprise Library, in ASP.Net Forums :
    http://forums.asp.net/122.aspx

    2. An Introduction and Overview of the Microsoft Application Blocks, in 4GuysFromRolla.com :
    http://www.4guysfromrolla.com/articles/062503-1.aspx

    3. Patterns and Practices in Msdn :
    http://www.4guysfromrolla.com/articles/062503-1.aspx

    4. Microsoft Enterprise Library 5.0 – April 2010 in Msdn:
    http://msdn.microsoft.com/en-us/library/ff632023.aspx

    5. Microsoft Enterprise Library 5.0 – April 2010 in Codeplex:
    http://entlib.codeplex.com/
    http://entlib.codeplex.com/wikipage?title=EntLib5%20Beta1

    Aug 6, 2010

    Configuring Your ASP.NET 2.0 Site

    1. For configuration of Asp.net applications and Web sites and for Role Management: (Use the default WSAT tool)
    http://www.developer.com/net/asp/article.php/3569166/Configuring-Your-ASPNET-20-Site.htm

    2. For configuring the Asp.Net MVC Applicationsand for Role Management: (Use the MVC WSAT tool)
    http://wsat.codeplex.com/

    3. For Configuring WCF Roles:
    http://weblogs.asp.net/spano/archive/2007/03/12/how-to-implement-a-wcf-authorization-manager-using-azman.aspx

    Problem: Intellisense missing in Visual Studio


    1. Open Tool>Options

    2. Goto Text Editor>All Languages

    3. In the Right Hand pane Check the "Auto List members"

    4. Uncheck "Hide advanced members"

    5. Check the "Parameter Information"

    6. Click "OK"


    You're done

    Setup Web Admin Tool for Production Servers

    I have been able installed WebAdminTool for Production Servers using the following steps:

    Create a virtual directory ASP.NETWebAdminFiles in IIS that point to C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ASP.NETWebAdminFiles

    Open properties windows of the new virtual directory, make sure that it is configured to run with ASP.NET 2.0, and in Security tab, uncheck Anonymous Access, check Integrated Windows Authentication.

    After that, you will be able to connect to WebAdminTools using the following syntax
    http://localhost/ASP.NETWebAdminFiles/default.aspx?applicationPhysicalPath=XXX&applicationUrl=/YYY
    in my case, it is:
    http://localhost/ASP.NETWebAdminFiles/default.aspx?applicationPhysicalPath=D:\Tasks\Libranyon\Photonyon\&applicationUrl=/Photonyon

    Although I don't recommend to do it, if you want to access WebAdminTool from other computer, open WebAdminPage.cs from (C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ASP.NETWebAdminFiles\App_Code) and comment the following code block
    if (!application.Context.Request.IsLocal) {
    SecurityException securityException = new SecurityException((string)HttpContext.GetGlobalResourceObject("GlobalResources", "WebAdmin_ConfigurationIsLocalOnly"));
    WebAdminPage.SetCurrentException(application.Context, securityException);
    application.Server.Transfer("~/error.aspx");
    }
    WebAdminTool still be protected by Intergrated Windows Authentication, so you still some have some defense here.

    Jun 12, 2009

    How to run a C# application as an administrator

    To have your C# (or any .NET program) run as Administrator in Windows, you'll have to create a manifest for it.
    Step 1:
    Add a manifest file to your app.
    Solution Explorer>Rightclick>Add>"New Item">"Application Manifest File"




    Step2 : Manipulate the default manifest file as follows

    Just change the highlighted attribute from a"asInvoked" to "requireAdministrator"



    Step 3: Make your app to use the manifest
    [If Not using Visual Studio]
    1. Rename it to (YourEXEName).manifest. The .NET Framework when executing the file will see the Manifest and handle its contents.
    2.Embed the .manifest file into you EXE. This can be done by executing the following command line:
    1.mt -manifest YourProgram.exe.manifest -outputresource:YourProgram.exe
    2.If your assembly is strong named, you will be unable to embed the manifest into it as it would invalidate the strong naming.
    [If using Visual Studio]
    1. Dont have to do anything more...
    2. Just remember to run the Visual Studio as an Administrator, for future debugging.

    Jun 11, 2009

    BackgroundWorker Class and usage examples

    BackgroundWorker Class:
    Brief Defn: Executes an operation on a separate thread(MSDN).
    Detailed Defn: The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.

    To execute a time-consuming operation in the background, create a BackgroundWorker and listen for events that report the progress of your operation and signal when your operation is finished. You can create the BackgroundWorker programmatically or you can drag it onto your form from the Components tab of the Toolbox. If you create the BackgroundWorker in the Windows Forms Designer, it will appear in the Component Tray, and its properties will be displayed in the Properties window.

    To set up for a background operation, add an event handler for the DoWork event. Call your time-consuming operation in this event handler. To start the operation, call RunWorkerAsync. To receive notifications of progress updates, handle the ProgressChanged event. To receive a notification when the operation is completed, handle the RunWorkerCompleted event.

    Note:
    You must be careful not to manipulate any user-interface objects in your DoWork event handler. Instead, communicate to the user interface through the ProgressChanged and RunWorkerCompleted events.

    BackgroundWorker events are not marshaled across AppDomain boundaries. Do not use a BackgroundWorker component to perform multithreaded operations in more than one AppDomain .

    If your background operation requires a parameter, call RunWorkerAsync with your parameter. Inside the DoWork event handler, you can extract the parameter from the DoWorkEventArgs..::.Argument property.
    ---------------------------------------------------
    Usage:

    This class can be added both by code and also by using the toolbox
    Usage 1: Simple invocation
    ////Declaration and Instantiation
    BackgroundWorker Worker = new BackgroundWorker();

    ////Add the event handlers in the Constructor
    public Form2()
    {
    InitializeComponent();
    Worker.DoWork += new DoWorkEventHandler(Worker_DoWork);
    Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Worker_RunWorkerCompleted);
    }

    /////The Do work method is performed in a Async/multithreaded way when the
    ////RunWorkerAsync method of the background worker is invoked.
    ////N.B.: No UI Control manipulation is permitted.
    void Worker_DoWork(object sender, DoWorkEventArgs e)
    {
    // Do not access the form's BackgroundWorker reference directly.
    // Instead, use the reference provided by the sender parameter.
    BackgroundWorker bw = sender as BackgroundWorker;

    // Extract the argument.
    int arg = (int)e.Argument;

    // Start the time-consuming operation.
    e.Result = TimeConsumingOperation(bw, arg);

    // If the operation was canceled by the user,
    // set the DoWorkEventArgs.Cancel property to true.
    if (bw.CancellationPending)
    {
    e.Cancel = true;
    }
    }

    ////This is the method which is automatically called when the async thread has completed its work.
    private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
    if (e.Cancelled)
    {
    // The user canceled the operation.
    MessageBox.Show("Operation was canceled");
    }
    else if (e.Error != null)
    {
    // There was an error during the operation.
    string msg = String.Format("An error occurred: {0}", e.Error.Message);
    MessageBox.Show(msg);
    }
    else
    {
    // The operation completed normally.
    string msg = String.Format("Result = {0}", e.Result);
    MessageBox.Show(msg);
    }
    }

    =============================================================
    Usage 2: Implementing BackgroundWorker with Progress Bar
    http://msdn.microsoft.com/en-us/library/waw3xexc.aspx


    Jun 5, 2009

    Consuming and Publishing RSS feeds

    1. http://www.code101.com/Code101/DisplayArticle.aspx?cid=48
    2. http://www.dotnetcurry.com/ShowArticle.aspx?ID=137&AspxAutoDetectCookieSupport=1
    3. http://www.c-sharpcorner.com/UploadFile/pwright/RssFeedProject12062005000807AM/RssFeedProject.aspx
    4. http://aspalliance.com/919_Awesome_ASPNET_20_RSS_ToolKit_Released.1 -- (Detailed Tutorial)
    5. http://blogs.msdn.com/dmitryr/archive/2006/02/21/536552.aspx

    WCF certificate authentication with IIS7

    1. http://romualdas.spaces.live.com/blog/cns!DCDC5E439E70339D!1006.entry
    2. http://social.technet.microsoft.com/Forums/en-US/winserversecurity/thread/3bfd8974-ac8a-4c53-ade8-e8b71713f92a
    3. http://forums.iis.net/
    4. http://notgartner.wordpress.com/2007/09/06/using-certificate-based-authentication-and-protection-with-windows-communication-foundation-wcf/