Friday 1 November 2013

How to identify when a SQL Server database was restored

To know when a database is restored run the below query in the database.

SELECT [rs].[destination_database_name],
[rs].[restore_date],
[bs].[backup_start_date],
[bs].[backup_finish_date],
[bs].[database_name] as [source_database_name],
[bmf].[physical_device_name] as [backup_file_used_for_restore]
FROM msdb..restorehistory rs
INNER JOIN msdb..backupset bs
ON [rs].[backup_set_id] = [bs].[backup_set_id]
INNER JOIN msdb..backupmediafamily bmf
ON [bs].[media_set_id] = [bmf].[media_set_id]
ORDER BY [rs].[restore_date] DESC

Meanings of the column

destination_database_name  -   The name of the database that has been restored.
restore_date   -    The time at which the restore command was started.
backup_start_date  -  The time at which the backup command was started.
backup_finish_date  -  The time at which the backup command completed.
source_database_name  -  The name of the database after it was restored.
backup_file_used_for_restore  -  The file(s) that the restore used in the RESTORE command.

Wednesday 2 October 2013

Operation is not valid due to the current state of the object.

I am getting the below error while binding a gridview.

Operation is not valid due to the current state of the object.

[InvalidOperationException: Operation is not valid due to the current state of the object.]
   System.Web.HttpValueCollection.ThrowIfMaxHttpCollectionKeysExceeded() +2692482
   System.Web.HttpValueCollection.FillFromEncodedBytes(Byte[] bytes, Encoding encoding) +61
   System.Web.HttpRequest.FillInFormCollection() +148

[HttpException (0x80004005): The URL-encoded form data is not valid.]
   System.Web.HttpRequest.FillInFormCollection() +206
   System.Web.HttpRequest.get_Form() +68
   System.Web.HttpRequest.get_HasForm() +8743911
   System.Web.UI.Page.GetCollectionBasedOnMethod(Boolean dontReturnNull) +97
   System.Web.UI.Page.DeterminePostBackMode() +63
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +133

This error occurs when form fields are very large in numbers.By default, the maximum value of MaxHttpCollection is 1000.

To solve this error, increase MaxHttpCollection value in web.config.Add the following setting in your web.config's <appsettings> block.

<appSettings>
        <add key="aspnet:MaxHttpCollectionKeys" value="3000" />
 </appSettings>

You can change the value accordingly as per your need.

Tuesday 10 September 2013

Fixed Header and Footer using CSS

If you want to create a header and footer part which will be fixed in their place then follow the below steps.

Place the below css in the page.
 <style type="text/css">
        #header
        {
            background: #eee;
            border: 1px solid #666;
            height: 60px;
            left: 0;
            position: fixed;
            width: 100%;
            top: 0;
            text-align: center;
        }
        #content
        {
            margin: 0 auto;
            overflow: auto;
            padding: 80px 0;
            width: 940px;
        }
        #footer
        {
            background: #eee;
            border: 1px solid #666;
            bottom: 0;
            height: 60px;
            left: 0;
            position: fixed;
            width: 100%;
            text-align: center;
        }
    </style>

Place the below content in the page.
<div id="header">
            Header Content
</div>
<div id="content">
           Text part will place here.
</div>
<div id="footer">
            Footer Content
</div>

Run the project by using F5 and see the output.

Wednesday 17 July 2013

Handler "svc-Integrated" has a bad module "ManagedPipelineHandler" in its module list

If you  will get this error while running your wcf application then you didn't install the prerequistes for ASP.NET 4.

To install the prerequistes go to
Start --> All Programs --> Microsoft Visual Studio 2008 --> Visual Studio Tools --> Open Visual Studio Command Prompt.
Run Visual Studio 2008 Command Prompt as “Administrator”.

Type the following:
     aspnet_regiis.exe -i

Run your application.

Saturday 13 July 2013

Windows could not start the SQL Server (MSSQLSERVER) service on Local Computer.Error 1069: The service did not start due to a logon failure.

I was getting the same error since I had changed the password of my computer. I have changed in the services after that it is working fine.

Go to Run-->services.msc--> SQl Server(MSSQLSERVER) . Right click --> Properties -->  Click on "Log on" tab. I have changes the password and retype the current windows password again. It works.

Thursday 27 June 2013

Store Datatable Column Name in an Array Using LINQ

If you want to store datatable column values in an array using LINQ you can achieve this by the following ways.

string[] ColName = dt.Columns.Cast<DataColumn>().
                                   Select(x => x.ColumnName).ToArray();

Wednesday 26 June 2013

Store Datatable Row Values in Jagged Array using LINQ

If you want to store values of a datatable in a jagged array using LINQ you can achieve in the following ways.

string[][] Value = dt.Rows.OfType<DataRow>().
                                Select(r => dt.Columns.OfType<DataColumn>().
                                Select( c => r[c.ColumnName].ToString()).ToArray()).
                           ToArray();

Thursday 6 June 2013

Find System MAC Address using C#

protected void Page_Load(object sender, EventArgs e)
{
    Response.Write(GetMACAddress());
}

public string GetMACAddress()
{
        NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();        
        foreach (NetworkInterface adapter in nics)
        {
             if (sMacAddress == String.Empty)  // only return MAC Address from first card  
             {
                   IPInterfaceProperties properties = adapter.GetIPProperties();
                   return adapter.GetPhysicalAddress().ToString();
              }
        }
        return String.Empty;
}

Saturday 1 June 2013

WCF Service Host cannot find any service metadata. This may cause the client application to run improperly. Please check if metadata is enabled. Do you want to exit?

In my case I got this error because the service name field did not actually match the namespace of the class actually implementing the operation contract in app.config file.

<services>
<service name="WCFHelloWorld.MySyncService" behaviorConfiguration="WCFHelloWorld.Service1Behavior">
.
.
.
</services>

Tuesday 14 May 2013

Security settings for this service require Windows Authentication but it is not enabled for the IIS application that hosts this service

I am getting this error while I am trying to run my WCF service using HTTPS.
Then I have done the following to resolve my issue.

1 - The Contract Operation method has Operation Behaviour "
      [OperationBehavior(Impersonation=ImpersonationOption.Required)]"

2 - Change the following in the web.config file.
      <system.web>
            ....
            <authentication mode="Windows" />
            .....
     </system.web>

3 - You can also verify that Anonymous Authentication is disabled like in the image below in the IIS.
      Open IIS. Select your application from left side. From right side select "Authentication".
     
     In my case "Windows Authentication" is disabled. Click on the status to enabled.

    Run your application.


Saturday 11 May 2013

Execution of user code in the .NET Framework is disabled. Enable "clr enabled" configuration option.


While running a project I got this error:
Execution of user code in the .NET Framework is disabled. Enable "clr enabled" configuration option.
Execution of user code in the .NET Framework inside the database is disabled.
Execute this TSQL:  "sp_configure 'clr enabled',1" and "RECONFIGURE"
So to fix this run this TSQL inside the database.
sp_configure 'clr enabled',1
GO
RECONFIGURE

Tuesday 7 May 2013

The database owner SID recorded in the master database differs from the database owner SID recorded in database 'AdventureWorks2008R2'. You should correct this situation by resetting the owner of database 'AdventureWorks2008R2' using the ALTER AUTHORIZATION statement.

--To get owner SID recorded in the master database for the current database
SELECT owner_sid FROM sys.databases WHERE database_id=DB_ID()

--To get the owner SID recorded for the current database owner
SELECT sid FROM sys.database_principals WHERE name=N'dbo'

They should return you same SID values in the format of a GUID.

Now if the two SID's differ which they did in my case it means that you need to reset the database owner so that both values are the same. To do this you can run another ALTER statement and pass in the owner value you want to use e.g

use AdventureWorks2008R2

ALTER AUTHORIZATION ON Database::AdventureWorks2008R2 TO sa

or

DECLARE @Command VARCHAR(MAX) = 'ALTER AUTHORIZATION ON DATABASE::<<DatabaseName>> TO [<<LoginName>>]'
SELECT @Command = REPLACE(REPLACE(@Command,'<<DatabaseName>>',SD.Name), '<<LoginName>>', SL.Name)
FROM master..sysdatabases SD
JOIN master..syslogins SL ON  SD.SID = SL.SID
WHERE  SD.Name = DB_NAME()

PRINT @Command
EXEC(@Command)

The problem will be fixed.

Thursday 18 April 2013

The type 'System.Data.Objects.ObjectContext' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'


You receive this error because you have not used references in your project to use System.Data.Entity namespaces.

To including the Entity Framework in your application, you must have a reference to the System.Data.Entity namespace so that you have access to the core functionality of the Entity Framework. These classes enable you to query, insert, update, and delete data.

1. In Solution Explorer, right-click References and select Add Reference from the right-click menu.
2. The Reference Manager dialog box is displayed.
3. Select System.Data.Entity from the list in the dialog box and Click OK.

Sunday 14 April 2013

How to make single radio button selection in gridview using javascript

In ASP.Net the GridView control does not support selection of a single RadioButton that works as a group across rows. Here we will see how to select only one RadioButton in a GridView using javascript.

Step - 1  In the design drag ang drop a grid view control from the toolbox.
               Change the gridview according like below.
               <asp:GridView ID="grdDisply" runat="server" AutoGenerateColumns="false">
               <Columns>
                <asp:TemplateField HeaderText="Select">
                    <ItemTemplate>
                        <asp:RadioButton runat="server" ID="rbtnSelect" OnClick="SelectSingleRbtn(this.id)">
                        </asp:RadioButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Dosage" HeaderText="Dosage" />
                <asp:BoundField DataField="Drug" HeaderText="Drug" />
                <asp:BoundField DataField="Patient" HeaderText="Patient" />
                <asp:BoundField DataField="Date" HeaderText="Date" />
             </Columns>
            </asp:GridView>

Step - 2 In the cs to bind the grid view write the below code.
              protected void Page_Load(object sender, EventArgs e)
             {
                     if (!IsPostBack)
                    {
                         Bind();
                    }
             }

             private void Bind()
            {
                 grdDisply.DataSource = GetTable();
                 grdDisply.DataBind();
            }

           static DataTable GetTable()
          {      
                DataTable table = new DataTable();
                table.Columns.Add("Dosage", typeof(int));
                table.Columns.Add("Drug", typeof(string));
                table.Columns.Add("Patient", typeof(string));
                table.Columns.Add("Date", typeof(DateTime));
                table.Rows.Add(10, "A", "Rabi", DateTime.Now);
                table.Rows.Add(20, "B", "Bopara", DateTime.Now);
                table.Rows.Add(30, "C", "Johny", DateTime.Now);
                table.Rows.Add(40, "D", "Marry", DateTime.Now);
                table.Rows.Add(50, "E", "Shetty", DateTime.Now);      
                return table;
          }        

Step - 3  In the head section of the add the below javascript code.
              <script language="javascript" type="text/javascript">
              function SelectSingleRbtn(rdbtnid) {
                  var rdBtn = document.getElementById(rdbtnid);
                  var rdBtnList = document.getElementsByTagName("input");
                  for (i = 0; i < rdBtnList.length; i++) {
                        if (rdBtnList[i].type == "radio" && rdBtnList[i].id != rdBtn.id) {
                            rdBtnList[i].checked = false;
                        }
                 }
            }
           </script>

Step - 4 Then press F5 to build and run your application. 

Saturday 16 March 2013

How To Generate Scripts of all tables with data in sql server 2008


MS SQL Server 2008 has new Generate Scripts option which enables sql programmers to script data in SQL Server database tables. SQL developers can script data from sql tables into a script file, to the clipboard or script data on a new sql query window. Script data can be used to export and/or import table data from one database to another database.

The Script Data option creates INSERT statements foreach row in the table using the column data that the related table record has.

Requirement:
I have a database name as “sanjeet”. In that database some tables are there. My requirement is to generate scripts of all tables,tables data and all stored procedure present in that database.

Solution:
1. Open sql server. Right click on the database name and open the context menu, choose Tasks menu and open submenu. Select Generate Script submenu item from the displayed list.

2.      Click on Next.

3.     If you want to select particular table and stored procedure script then select "Select Specific Database Object" option.Then select your required table and procedure from below. Click on next.

4.     If you want to generate table structure script with data then click on advance option.
      
 5.    Choose "Schema and Object" option.


6.    Output Option screen in the Generate Script Wizard is the screen where a sql administrator or a programmer can make a selection among the existing output options. The script generator can create the desired scripts in the forms of a file, also can split the automatic generated script per object basis, or define the file as a unicode file or in ANSI text. A database developer can also select the file name and the output file folder for the script engine to create and place the script file. Click on Next.

7.     Click on Next.
  
8.      Generate Script Progress screen displays the status of the scripting operation. If an error occurs sql developers and administrators can find the error details on this screen. If everything runs without any error and does not fail, you will see Success status for each scripting action on the progress screen.


9.      Since as the output option for the scripting, the New Query Window is selected, the final script is displayed on the SQL Server Management Studio Query Editor window as shown below.

      
       

Wednesday 27 February 2013

Disable mouse right click using javascript


When we right click on the page and click on the view source option then page html source along with inline css will see. From the source code, they can figure out how you did things and where your graphics are stored, or just plain old copy your content coding. To prevent the user to know the source detail we disable right click on the page.

<script type="text/javascript">
        var message = "Right Click Disabled!";
        function DisableIE() {
            if (event.button == 2) { alert(message); return false; }
        }
        function DisableOther(e) {
            if (document.layers || document.getElementById && !document.all)
            { if (e.which == 2 || e.which == 3) { alert(message); return false; } }
        }
        if (document.layers) { document.captureEvents(Event.MOUSEDOWN); document.onmousedown = DisableOther; }
        else if (document.all && !document.getElementById) { document.onmousedown = DisableIE; }
        document.oncontextmenu = new Function("alert(message);return false")
</script>

Disable F12 key in the browser


When user press F12 key, browsers developer tool bar will open in the below portion of the browser. By
using the developer tool bar user can see the design, javascript code and corresponding css applied to the controls in the page. To prevent the user to do that we will the hide developer tool bar.

You can use the below code to do that. Write the below code in the head section of the page.
<script type="text/javascript">

document.onkeydown = function (event)
{
     event = (event || window.event);
     if (event.keyCode == 123 || event.keyCode == 18)
     {
           alert("This function is disabled here");
           return false;
     }
}
</script>

Monday 25 February 2013

Request format is unrecognized for URL unexpectedly ending in


Add the following to web.config since GET and POST are disabled by default in ASP.NET 2.0 and greater:

<configuration>
    <system.web>
    <webServices>
        <protocols>
            <add name="HttpGet"/>
            <add name="HttpPost"/>
        </protocols>
    </webServices>
    </system.web>
</configuration>

Build the project and run.

Sunday 24 February 2013

Show Logo on Title Bar

1 - Take a small logo image of 16*16 pixel.
2 - Put that image in the image folder of the project.
3 - In the master page write the below line.
      <link type="image/x-icon" rel="Logo" href="Image/sanjeet.ico" />
      Here my icon name is sanjeet.ico.
4 - Press F5 to run your project.

The form cannot be rendered. This may be due to a misconfiguration of the Microsoft SharePoint Server State Service. For more information, contact your server administrator.


You may receive this error when trying to publish a infopath form in SharePoint 2010.

The form cannot be rendered. This may be due to a misconfiguration of the Microsoft SharePoint Server State Service. For more information, contact your server administrator.

Cause :
State service is not enabled on Server.You would need to install the ‘State Service’ via the Configuration wizard in Central Administration or via PowerShell.

Before configure the settings check by using following steps.
1. Go to "Application Management" --> "Manage service applications"
2. Check whether the "State Service" is enabled or not
3. If the service is not started or missed, we should configure/start the state service. OK.

Configure the State Service using the Farm Configuration Wizard
1- Open Central Administration. Click on Configuration Wizards option from left navigation.

2 - Click on the "Launch the Farm Configuration Wizard" option from RHS.

3 -  Click on the "Start the Wizard" button.

4 - On the services configuration page, in the Services section, select the State Service check box (and/or any other services you might be interested) and click Next.

5 - If you set-up a top-level site already click on Skip button if not go ahead and create it now by clicking OK.

6 - On the final page of the Farm Configuration Wizard, review your freshly installed services and click Finish.

Configure the State Service using Windows PowerShell
1 - Open SharePoint 2010 Management Shell.
2 - To create a service application, type the following command:
      $serviceApp = New-SPStateServiceApplication -Name "State Service"
3 - Create a State Service database and associate it with a service application, by typing:
      New-SPStateServiceDatabase -Name "StateServiceDatabase" -ServiceApplication $serviceApp
4 - Create a State Service Application Proxy and associate it with the service application by typing:
      New-SPStateServiceApplicationProxy -Name "State Service" -ServiceApplication $serviceApp -   DefaultProxyGroup

Friday 15 February 2013

List Join in SharePoint 2010 using CAML

1. Create a list Department and enter some values in it.
 
2. Create a list "Employee". Here create a column department and make it as look up column of Department -> Title. Enter some values in it.
 
3. Create a web part using visual studio and deploy.
   a) Drag and drop a grid view from tool box in the designing part.
   b) Write the below code to join the list.

       Code:
       using (SPSite site = new SPSite("http://win-j9h3l62i2n9:1000/"))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists["Employee"];

                        SPQuery query = new SPQuery();
                        query.Query = @"<Query><Where><Eq><FieldRef Name='Gender' /><Value Type='Choice'>Male</Value></Eq></Where></Query>";

                        query.Joins = @"<Join Type='INNER' ListAlias='Department'>
                                            <Eq>
                                               <FieldRef Name='Department' RefType='ID' />
                                               <FieldRef List='Department' Name='ID' />
                                            </Eq>
                                        </Join>";

                        query.ProjectedFields =
                             @"<Field Name='Dep_Code' Type='Lookup' List='Department' ShowField='Title' />
                               <Field Name='Dep_Name' Type='Lookup' List='Department' ShowField='Name' />
                               <Field Name='Dep_Comment' Type='Lookup' List='Department' ShowField='Comment' />";

                        query.ViewFields = @"<FieldRef Name='Gender' />
                                             <FieldRef Name='Dep_Code' />
                                             <FieldRef Name='Dep_Name' />
                                             <FieldRef Name='Dep_Comment' />";

                        query.RowLimit = 100;

                        SPListItemCollection items = list.GetItems(query);

                        DataTable dt = items.GetDataTable();

                        grdShow.DataSource = dt;
                        grdShow.DataBind();
                    }
                }
 
4. Build and deploy.

Monday 4 February 2013

How to Add the Reference of a User Control in the webconfig file in ASPNET

At the time of working, developers register the User Controls to individual asp.net pages where, controls are in use. If the control is in use in most of the pages of the site, the reference can be added at one place only, that is in the web.config.

Code to add in web.config file to register the user control
<configuration>
  <system.web>
    <pages>
      <controls>
        <add tagPrefix="uc1" src="~/usercontrols/Address1.ascx" tagName="Address1"/>
        <add tagPrefix="uc2" src="~/usercontrols/Address2.ascx" tagName="Address2"/>
      </controls>
    </pages>
  </system.web>
</configuration>

Code to use the user control in the page
Open your aspx page and place the below code.

<uc1:Address1 ID="ucAddress1" runat="server"/>
<uc2:Address2 ID="ucAddress2" runat="server"/>

Wednesday 30 January 2013

How to use Iframes in Sharepoint

1 - Add a content editor web part on to the page. To add a content editor web part
     Click on Web part -> Media and Content -> Content Editor -> OK.

2 - Click on Format Text -> HTML -> Edit Source tab in Ribbon.

3 - Add the following in the Source.
     <iframe width="420" height="315" src="http://sanjeetsatapathy.blogspot.com" frameborder="0"  allowfullscreen></iframe>
    Click ok.

4 - Click on Save to save your work. You will get your desired result.


Monday 28 January 2013

Enable Sync to SharePoint Workspace for SharePoint document libraries

We will be see how to enable Sync to SharePoint Workspace button in the ribbon interface for SharePoint document libraries so that the documents can be synced to SharePoint Workspace and the users can work from offline.

To enable Sync : 
1. Go to Shared Documents -> Library Settings -> General Settings -> Advanced Settings.

2. Click Yes in Office Client Availability section -> OK.

3. Sync to SharePoint Workspace option is enabled successfully.

Saturday 26 January 2013

LINQ to SQL Classes

LINQ to SQL classes that are mapped to database tables and views are called entity classes. The entity class maps to a record, whereas the individual properties of an entity class map to the individual columns that make up a record. Create entity classes that are based on database tables or views by dragging tables or views from Server Explorer/Database Explorer onto the Object Relational Designer (O/R Designer).



Demo :

1 - Open Visual Studio 2008 and create a new ASP.NET Web Application.
     File --> New --> Web Site --> Visual C# --> ASP.NET Web Application --> Give name of the  application (for Ex- LinqtoSqlClasses).

2 - Right-click on the "App_Data" folder and select Add --> New Item.

3 - Once the Add New Item windows opens select "LINQ to Sql Classes" and name it "Northwind.dbml" as follows:

4 - Now connect your Database in server explorer and drag and drop the tables to Northwind.dbml file. It will automatically converted into a class. See the image below.

   a) Click on server explorer.


    b) Click on connect to database.


      c) Enter credentials to connect to the database.

                
                     Click on OK button.

        d) Drag your table from server explorer and drop it to the dbml file.



               Press Ctrl+S to save your work.

    5 - Open your default.aspx page. Drag and drop grid view control from tool box menu on to the page.
   
    6 - Write the below code on the page load to fetch data from database.

           protected void Page_Load(object sender, EventArgs e)
          {
               if (!IsPostBack)
              {
                     Bind();
               }
          }

          private void Bind()
         {
               NorthwindDataContext db = new NorthwindDataContext();

               var category = from c in db.Categories
                                      select c;

               grdCategory.DataSource = category;
               grdCategory.DataBind();
         }
            
    7 - Save and run the application. You will get your required output.

          

Tuesday 15 January 2013

The current page has been customized from its template. Revert to template.


If you have customized a SharePoint 2010 aspx page by using SharePoint Designer, you may experience that when opening the modified webpage in your browser, that a yellow bar below the navigation bar will appear. This is not actually a error. This is a warning message.

To resolve this, you can use one of the below steps.

First Way :
Add the Css in the master page.
<style type="text/css">
body #pageStatusBar{height:0px; font-size:0px; padding:0px; border-style:none;}
</style>

2nd Way :
The following style attribute to the first DIV:
<div id="s4-statusbarcontainer" style="display: none">
<div id="pageStatusBar">
</div>
</div>

3rd Way :
Add the below code in the head section.

<head>
<title></title>
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(hideWarning, "SP.js");

function hideWarning() {
    var statusbarContainer = document.getElementById('s4-statusbarcontainer');    
    if (statusbarContainer != null) {  
       var messageSpan = document.getElementById('pageStatusBar');    
       if (messageSpan != null) {
           if (messageSpan.innerHTML.indexOf('The current page has been customized from its template.') == -1)
               statusbarContainer.style.display = 'inline';      
       else
       statusbarContainer.style.display = 'none';
}
    }
}
</script>

</script>
</head>

Wednesday 9 January 2013

The Site URL property of the project does not contain a valid URL

The Site URL property to which this error is referring can be found in the properties tool window when you have the project selected.  If you cannot see the properties tool window then you should be able to make it appear by hitting F4 or selected View > Properties Window from the menu.  From there, you just type the URL into the Site URL property and you should be good to go.

You must specify a value for this required field


If you are using a custom masterpage it is very common to use the visible="false" tag to hide element SharePoint is looking for but you don’t want displayed on your page.  If you did this with the PlaceHolderPageTitleInTitleArea tag at first glance everything works as it should.  However, you will notice that you can no longer save pages through the UI without getting the “You must specify a value for this required field” error.

To resolve this issue. Create a css class and call it.

.hide {
visibility: hidden;
}

Then wrap your PlaceHolderPageTitleInTitleArea in a <asp:Panel> tag that looks like this…

<asp:panel runat="server" cssclass="hide">
  <asp:contentplaceholder id="PlaceHolderPageTitleInTitleArea" runat="server" />
</asp:panel>