Sunday, 17 March 2013

Error occurred in deployment step 'Retract Solution': Cannot start service SPUserCodeV4 on computer

Error occurred in deployment step 'Retract Solution': Cannot start service SPUserCodeV4 on computer

Title: SharePoint 2010 Error occurred in deployment step 'Retract Solution': Cannot start service SPUserCodeV4 on computer

Details: Building Sandboxed Solutions on SharePoint 2010 using Visual Studio 2010 Beta and encountered the error? Then make sure that the service Microsoft SharePoint Foundation User Code Service ( CA > System Settings > Services on Server ) is Started.

Thursday, 14 March 2013

Creating Full Text Index in SQL Server


Introduction

In this article we will see how to create a full text search index for SQL Server database for effective search. In so many cases we need to provide the search facility in our application. To provide searching facility within our local database we can use the greater feature provided by Microsoft SQL Server i.e. full text index.

Background

When we want to use the full text index service we need to start the service first else it will raise the errors. So let's start with how to start the service and use the Full text index step by step.

Step 1

Open SQL Server and create a new database with the following table for eg. Tbl_Search but keep in mind that the full text index only works on primary key or unique key containing tables.

Create Table Tbl_Search
(
Id Int Primary Key Identity(1,1),
Title Varchar(500),
[Desc]Varchar(max)
)

Insert some rows in the created table.

Step 2

Now we will create full text index on our database and table for providing search in table. So create the Full Text Catalog on our database by using following query.

CREATE FULLTEXT CATALOG FTSearch

In the query above we have created FullText Catalog with the name FTSearch.

Step 3

Now we will create full text index on our table Tbl_Search but for that we require the unique key id or primary key id so find the id of unique or primary key by using following command.

SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS

This command will display the all constraint names on tables present in our database from the output. Copy the Tbl_Search constraint name for creating a full text index on TblSearch.

CREATE FULLTEXT INDEX ON Tbl_Search


(Title, [Desc] LANGUAGE 1033)
KEY INDEX PK__Tbl_Sear__3214EC0700551192
ON FTSearch

In the above statement you can see we are creating a FullText Index on table name with a parameter; this parameter is nothing but the column name of the table on which we want to create the full text index and language 1033 denotes the language English.

Step 4

Now it's time to search the records in a specified indexed table. For that we can write the queries like below.

Select * from Tbl_Search Where Contains(Title,'Asp.Net')
Select * from Tbl_Search Where Freetext([Desc],'Asp.Net')

In the preceding queries you can see we have given a where clause with column name which is the column we want to search and what we want to search. The preceding queries retrive the rows of a table which contain ASP.Net in title column and the second query will retrieve the rows of ASP.Net in the desc column.

In some cases your queries gives an error like fdhost cannot be started. That means your FullTextIndex Service is not started; for that you have to first start the Demon Launcher for FullTextIndex service.

Step 5

For starting FullTextIndex service go to SQL Server Tool->SQL Server Configuration Manage->Service->FullTextSearch Demon Launcher if it is stopped then start this service for performing search operation with a contains and FreeText clause and restart the SQL Server instance.

Conclusion

In this way we can use the FullTextIndex on our database.







Note:


EXEC sp_fulltext_database 'enable'
EXEC sp_fulltext_database 'disable' 






 

Friday, 28 December 2012



Gridview Rows and Columns Value Calculation using Javascript

ex. Just i tried with Invoice application Demo.


   <script type="text/javascript">
      function multiplication(obj)
      {    
          
          var cell = obj.parentNode;               
          var per=obj.value*(0.1236);
          if(obj.value!="")
          {
            cell.parentNode.cells[cell.cellIndex + 1].getElementsByTagName("input")[0].value = per;
            //alert(obj.value*(0.1236));
            cell.parentNode.cells[cell.cellIndex + 2].getElementsByTagName("input")[0].value=parseFloat(obj.value)+parseFloat(per);
                 
       }  
        var gv = document.getElementById('<%=GridView1.ClientID %>');
            var Amount = 0;
            var tax=0;
            var total=0;
            for (var i = 1; i < gv.rows.length - 1; i++){
                if (gv.rows[i].cells[1].childNodes[1].value != '') 
                {
                    Amount = parseFloat(Amount) + parseFloat(gv.rows[i].cells[1].childNodes[1].value);     //getting textbox value
                   
                      tax=parseFloat(tax)+parseFloat(gv.rows[i].cells[2].childNodes[1].value);
                    
                    total=parseFloat(total)+parseFloat(gv.rows[i].cells[3].childNodes[1].value);
                }
             
            }
            document.getElementById('<%=Label1.ClientID %>').textContent = Amount.toFixed(2);
           
              document.getElementById('<%=Label2.ClientID %>').textContent = tax.toFixed(2);
          
            
             document.getElementById('<%=Label3.ClientID %>').textContent = total.toFixed(2);
               
       }
      function Calculatesum()
      {
        var gv = document.getElementById('<%=GridView1.ClientID %>');
            var Amount = 0;
            var tax=0;
            var total=0;
            for (var i = 1; i < gv.rows.length - 1; i++){
                if (gv.rows[i].cells[1].childNodes[1].value != '') 
                {
                    Amount = parseFloat(Amount) + parseFloat(gv.rows[i].cells[1].childNodes[1].value);     //getting textbox value
                   
                      tax=parseFloat(tax)+parseFloat(gv.rows[i].cells[2].childNodes[1].value);
                    
                    total=parseFloat(total)+parseFloat(gv.rows[i].cells[3].childNodes[1].value);
                }
             
            }
            document.getElementById('<%=Label1.ClientID %>').textContent = Amount.toFixed(2);
           
              document.getElementById('<%=Label2.ClientID %>').textContent = tax.toFixed(2);
          
            
             document.getElementById('<%=Label3.ClientID %>').textContent = total.toFixed(2);
           
      }

    </script>


===================================================================>


       <asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
        <Columns>
          <asp:TemplateField HeaderText="Product Name">
         <ItemTemplate>
             <asp:Label ID="Label4" runat="server" Text='<%#Eval("productname") %>'></asp:Label>
         </ItemTemplate>
        </asp:TemplateField>    
       
        <asp:TemplateField HeaderText="Amount">
         <ItemTemplate>
             <asp:TextBox ID="TextBox1" onblur="multiplication(this);return false" runat="server"></asp:TextBox>
         </ItemTemplate>
        </asp:TemplateField>      
         <asp:TemplateField HeaderText="Tax">
         <ItemTemplate>
             <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
         </ItemTemplate>
        </asp:TemplateField>      
         <asp:TemplateField HeaderText="Total">
         <ItemTemplate>
             <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
         </ItemTemplate>
        </asp:TemplateField>
        </Columns>
        </asp:GridView>

Thursday, 27 December 2012


Configuring ASP.NET 2.0 Application Services to use SQL Server 2000 or SQL Server 2005

One question I’ve seen asked a few times by people over the last few weeks is “how do I setup the new ASP.NET Membership, Role Management, and Personalization services to use a regular SQL Server instead of SQL Express?” This blog entry walks you though a few simple steps on how to-do this.

Quick Review: What are the new ASP.NET 2.0 Application Services?

ASP.NET 2.0 includes a number of built-in “building block” application services.  We call them “building blocks” because they are useful core frameworks for enabling super-common scenarios with web applications today – and as a result can provide significant productivity wins and time-savings for developers.

They include: a membership API for managing usernames/passwords and secure credential management, a roles API that supports mapping users into logical groups, a profileAPI for storing arbitrary properties about both authenticated and anonymous users visiting a web site (for example: their zipcode, gender, theme preference, etc), a personalizationAPI for storing control customization preferences (this is most often used with the WebPart features in ASP.NET 2.0), a health monitoring API that can track and collect information about the running state and any errors that occur within a web application, and a site navigation API for defining hierarchy within an application and constructing navigation UI (menus, treeviews, bread-crumbs) that can be context specific based on where the current incoming user is in the site.

The ASP.NET Application Service APIs are designed to be pluggable and implementation agnostic, which means that the APIs do not hardcode the details of where data is stored with them.  Instead, the APIs call into “providers”, which are classes that implement a specific “provider contract” – which is defined as an abstract class with a defined set of methods/properties that the API expects to be implemented.

ASP.NET 2.0 ships with a number of built-in providers including: a SQL Express provider for going against local SQL Express Databases, SQL 2000/2005 providers that work against full-blown SQL Servers, an Active Directory Provider that can go against AD or ADAM implementations, and in the case of site navigation an XML provider that can bind against XML files on the file-system.

The beauty of the model is that if you don’t like the existing providers that ship in the box, or want to integrate these APIs against existing data-stores you are already using, then you can just implement a provider and plug it in.  For example: you might already have an existing database storing usernames/passwords, or an existing LDAP system you need to integrate with.  Just implement the MembershipProvider contract as a class and register it in your application’s web.config file (details below), and all calls to the Membership API in ASP.NET will delegate to your code.

Default SQL Express Providers

Out of the box, most of the ASP.NET 2.0 application services are configured to use the built-in SQL Express provider.  This provider will automatically create and provision a new database for you the first time you use one of these application services, and provides a pretty easy way to get started without a lot of setup hassles (just have SQL Express on the box and you are good to go).  Note that SQL Express databases can also be upgraded to run in the context of full-blown SQL Server instances – so apps built using SQL Express for development can easily be upgraded into a high-volume, clustered, fail-over secure 8P SQL box when your app becomes wildly successful.

How do I change the providers to use SQL Server Instead of SQL Express?

If you want to use a full-blown SQL Server 2000 or SQL Server 2005 database instance instead of SQL Express, you can follow the below steps:

Step 1: Create or obtain a blank SQL database instance

In this step you’ll want to create or obtain a connection string to a standard SQL database instance that is empty.

Step 2: Provision your SQL database with the ASP.NET schemas

Open a command-line window on your system and run the aspnet_regsql.exe utility that is installed with ASP.NET 2.0 in under your C:\WINDOWS\Microsoft.NET\Framework\v2.0.xyz directory. 

Note that this utility can be run in either a GUI based mode or with command-line switches (just add a -? flag to see all switch options).

Using this wizard you can walkthrough creating the schema, tables and sprocs for the built-in SQL providers that come with ASP.NET 2.0.  The below screens show the step-by-step walkthrough of this:











Once you have finished walking through the wizard, all the database schema + sprocs to support the application services will have been installed and configured (note: if your DBA wants to see exactly what is going on behind the covers, we also ship the raw .sql files underneath the above framework directory, and your DBA can walkthrough them and/or run them manually to install the DB).

Step 3: Point your web.config file at the new SQL Database

ASP.NET 2.0 now supports a new section in your web.config file called “<connectionStrings>” which (not too surprisingly) are used to store connection strings.  One nice thing from an administration perspective is that the new ASP.NET Admin MMC Snap-in now provides a GUI based way to configure and manage these:



ASP.NET 2.0 also now supports encrypting any section stored in web.config files -- so you can also now securely store private data like connectionstrings without having to write any encryption code of your own. 

ASP.NET 2.0 ships with a built-in connection string called “LocalSqlServer” which by default is configured to use a SQL Express database, and which by default the Membership, Roles, Personalization, Profile and Health Monitoring services are configured to use.

The easiest way to have your application automatically take advantage of your newly created SQL database is to just replace the connectionstring value of this “LocalSqlServer” setting in your app’s local web.config.

For example, if I created my database on the local machine in an “appservicesdb” database instance and was connecting using Windows Integrated security, I would change my local web.config file to specify this:

<configuration>

    <connectionStrings>
        <remove name=”LocalSqlServer”/>
        <add name="LocalSqlServer" connectionString="Data Source=localhost;Initial Catalog=appservicesdb;Integrated Security=True" providerName="System.Data.SqlClient"/>
    </connectionStrings>

</configuration>

Hit save, and all of the built-in application services are now using your newly created and defined SQL Server database.

Note: The one downside with the above approach is that I’m re-using the “LocalSqlServer” connection string name – which will feel weird if/when I deploy my database on another machine.  If I wanted to name it with my own connection string name, I could do this simply by adding a completely new connection-string, and then pointing the existing providers to use the new connection-string name in place of the default LocalSqlServer one. 

Hope this helps,

Thursday, 20 December 2012


Tip - Missing Add Service Reference in Visual Studio 2008(and above)??


If we choose any Framework earlier than .NET Framework 3.0 while creating project or migrate an existing project from older version of Visual Studio, we might not find Add Service Reference in the context menu when you right click on the project. Here is a way to update to the framework version of the project and get Add Service Reference option in the context menu (Project should be saved before doing this) ,

Right click on the project and navigate to the following path,

Compile->AdvancedCompileOptions(button)->TargetFramework(dropdown)

Change the Framework version to .NET Framework 3.0 (or above)

Now we should be able to see Add Service Reference option!!!!!!


(or)

Project-->RightClick--> select Property Page--> Select Built tab -->
TargetFramework(dropdown)

Change the Framework version to .NET Framework 3.0 (or above)





How to add web reference in VS 2008 Project


There are numerous changes between VS 2005 and VS 2008.  One of the changes has to deal with the way you add a web reference in a project.  Here are the steps to add a web reference to a windows application in  VS 2008.  First step is to right click the project and select Add Service Reference.


The second step is to select the Advanced button at the bottom of the form:

 The third step is to click the Add Web Reference button to open the web reference dialog:

You are now able to add your web reference as before:


 Not as convenient as right clicking the project and adding the web reference but just need to drill down a little further.

Upload a file using ASP.Net file upload control and WCF


I came across a question last week on how we can upload a file using a WCF service, So thought of solving through an example.

Introduction

I came across a question last week on how we can upload a file on to third party server using a WCF service, So thought of solving that through an example. 

So In this example we will upload a pdf file using ASP.Net upload control and passing the details to the WCF and saving the file in the server.

Objective

So as discussed our objective is to upload a pdf file from a web application to a third party server using a WCF service.


Using the code

So lets start building our sample step wise.

Step 1: First of all we will build the web application that a user will use to upload a file using the asp.net upload control. So lets code our aspx page as shown below.



Step 2: Now on the code behind file we will write the code to upload the details on btnUpload_click, where we will first validate to restrict the file type to be pdf and size to a max of 40 MB.


So here we have made sure to validate the posted file size not to exceed 40 MB and and type to be pdf file.

Step 3: We can also do a validation using the custom validation control too as below



Step 4: So on button click we have called a method called upload which will help us call our wcf service and send the details to save it on the third party server.

protected bool Upload(HttpPostedFile file, long actualFileSize)
        {
            int filePosition = 0;
            int filePart = 16 * 1024; //Each hit 16 kb file to avoid any serialization issue when transfering  data across WCF

            //Create buffer size to send to service based on filepart size
            byte[] bufferData = new byte[filePart];

            //Set the posted file data to file stream.
            Stream fileStream = file.InputStream;

            //Create the service client
            FUWcfService.FileUploadServiceClient serviceClient = new FUWcfService.FileUploadServiceClient();

            try
            {
                long actualFileSizeToUpload = actualFileSize;
                //Start reading the file from the specified position.
                fileStream.Position = filePosition;
                int fileBytesRead = 0;

                //Upload file data in parts until filePosition reaches the actual file end or size.
                while (filePosition != actualFileSizeToUpload)
                {
                    // read the next file part i.e. another 100 kb of data 
                    fileBytesRead = fileStream.Read(bufferData, 0, filePart);
                    if (fileBytesRead != bufferData.Length)
                    {
                        filePart = fileBytesRead;
                        byte[] bufferedDataToWrite = new byte[fileBytesRead];
                        //Copy the buffered data into bufferedDataToWrite
                        Array.Copy(bufferData, bufferedDataToWrite, fileBytesRead);
                        bufferData = bufferedDataToWrite;
                    }

                    //Populate the data contract to send it to the service method
                    bool fileDataWritten = serviceClient.UploadFileData(
                        new FUWcfService.FileData { FileName = file.FileName, BufferData = bufferData, FilePosition = filePosition });
                    if (!fileDataWritten)
                    {
                        break;
                    }

                    //Update the filePosition position to continue reading data from that position back to server
                    filePosition += fileBytesRead;
                }
            }
            catch (FaultException fex)
            {
                //Log data to database or file system here
                return false;
            }
            finally
            {
                //Close the fileStream once all done.
                fileStream.Close();
            }
            return true;
        }

Step 5: Next configure the web.config file to set the httpRuntime tag to set the maxRequestLength otherwise we will not be able to upload a big file like 40 MB file.

Also the WCF service details that we are going to create next.


Step 6: Now lets start creating the WCF service too from our side. First lets have the data contract and the interface.


Here we have created an interface IFileUploadService and the data contracts.

Step 7: Now the implementation part of the interface


Step 8: Finally lets configure the service 


Step 9: So Now its time to test our sample. Run the sample and the service.

So we have selected a pdf file and on clicking the upload button the file gets uploaded and the data is sent to the server through the WCF service part by part [16kb with each hit] and is saved in the server.


And finally displays the success message with the size of the file that got uploaded.

Hope you all will like it. And this would help all.


Conclusion

So we saw how easily we can upload a file across a wcf service. Let me know if you need any other details on this regard.