Wednesday, January 28, 2015

MVC4-Razor: Hide/Show menu item based upon logged in user

Following is the code to check cookie value in MVC and use to manage menu(or any other item) item in CsHTML

@if(Functions.ReadCookie("CookieName")=="1") {
@Html.ActionLink("Admin Users", "Index", "Admin", null, new { @class = Model == "Admin" ? "active" : "" })
}

Microsoft Visual Studio is busy waiting for an internal operation to complete

Hi,

With higher versions of Microsoft Visual Studio, this error is much familiar than ever. There could be many reasons behind this. Few common fixes are below:


  1. Remove website cache from following location:
    1. C:\Users\user_name\AppData\Local\Microsoft\WebsiteCache
  2. Restart IIS:
    1. Start -> RUN -> iisreset 
  3. Go to Tools -> Options and browse all the options and disable all unnecessary options.
  4. Clear cache.
  5. Remove temp files.
  6. Ensure there is enough space in C (System) drive.
However I will include one more scenario here. In a special case, I was facing this issue with one of my solutions only(not with all .net solutions). And after so much Google, when I find nothing about it, I opened Task Manager and started digging further. After killing my Devenv.exe more than 10 times, I decided to debug all my projects individually. And I opened BigSolution.sln file in notepad and started removing projects one by one(following kind of lines):

Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProjectX", "ProjectX\ProjectX.csproj", "{4C3D1267-EAF4-46E9-92E2-49469713509B}"
EndProject

And then I realized that the issue was with one of my recently added project and I removed that project and this fixed my issue.

Thanks.

Monday, January 19, 2015

XMLHttpRequest cannot load no 'access-control-allow-origin' header is present on the requested resource. Origin is therefore not allowed access

This error comes when a web service is request by browser (using jQuery or JavaScript). Put following httpProtocol node in system.webServer in Web.config file to resolve this issue:

  <system.webServer>
      .
      .
      .
      .
      <httpProtocol>
            <customHeaders>
                  <add name="Access-Control-Allow-Origin" value="*"/>
                  <add name="Access-Control-Allow-Headers" value="Content-Type"/>
                  <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
            </customHeaders>
      </httpProtocol>

  </system.webServer>

Tuesday, January 13, 2015

The virtual path maps to another application, which is not allowed

This problem comes when you copy a complete asp.net website to new folder/location/computer. And "Virtual Path" (same path which you see in browser address bar alongwith localhost and port number) in property is set to the folder name where complete site was originally placed. This can be resolved by removing folder name from virtual path.
Go to website in solution explorer.

Click F4, website properties will open.

Remove folder name from virtual path.


Tuesday, January 6, 2015

Load user control dynamically from code behind in asp.net


Load control from code behind in asp.net:

    UserControl uc = (UserControl)LoadControl("~/UserControl/ContactUs.ascx");
    plcContactUs.Controls.Add(uc);
plcContactUs could be a panel or place holder

Save complete table to database MS Sql + C#

First of all we need to create a user defined data type in SQL:

CREATE TYPE [dbo].[CustomUserType] AS TABLE(
      [Name] [varchar](250) NULL,
      [Age] [varchar](250) NULL,
      [Email] [varchar](250) NULL,
      [Department] [nvarchar](200) NULL
)
GO


Now create a procedure in SQL to consume variable of above defined data table:

CREATE PROC [dbo].[SaveCustomUserInfo]     
(     
 @UserTable [dbo].CustomUserType READONLY
)     
AS       
BEGIN     
      DECLARE @ErrCode INT     
       
      BEGIN TRAN     
      INSERT INTO UserMaster([Name],[Age],[Email], [Department])
            SELECT [Name],[Age],[Email], [Department] FROM @UserTable  

      SELECT @ErrCode = @@ERROR     
      IF (@ErrCode <> 0) GOTO PROBLEM     
            COMMIT TRAN     

      PROBLEM:     
      IF (@ErrCode <> 0) BEGIN     
            PRINT 'Unexpected error occurred!'     
            ROLLBACK TRAN     
      END     
      SELECT * FROM UserMaster
END     
Now pass table with pre-defined columns to above create procedure:
        public void SaveCustomUserInfo (DataTable UserTable)
        {
            ds = new DataSet();
            try
            {
                OpenConn();
                strSql = "SaveCustomUserInfo";

                SqlParameter[] parm = new SqlParameter[1];

                parm[0] = new SqlParameter("@UserTable", UserTable);

                ds = SqlHelper.ExecuteDataset(con, CommandType.StoredProcedure, strSql, parm);
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
            finally { CloseConn(); }
        }

Use following code to create data table and pass to above mentioned function:
    DataTable dt = new DataTable();
    dt.Columns.Add("Name");
    dt.Columns.Add("Age");
    dt.Columns.Add("Email");
    dt.Columns.Add("Department");
    DataRow dr = dt.NewRow();
    dr["Name"] = "Nitin";
    dr["Age"] = "30";
    dr["Email"] = "nitindhiman@gmail.com";
    dr["Department"] = ".net";
    dt.Rows.Add(dr);
    SaveServiceNowAccountDetail(dt);


Thursday, January 1, 2015

Update SQL Table with joins

Following is the query to update sql table with joins

UPDATE a
SET a.sortorder = b.sort_order
FROM picture AS a
INNER JOIN (select row_number() over (order by id) as sort_order,id,projectid from picture
where projectid = 61
) AS b
       ON a.id = b.id
where a.projectid = 61


select * from picture order by id desc


SQL REPLACE() : Argument data type ntext is invalid for argument 1 of replace function.

SQL Server Replace function does not work with text and ntext data types.
Following query contains replace function for ntext type column.

update description_table set description = replace(description,'../G/','http://styletint.in/G/') where description like '%../G/%'

this query is will return following error:

Argument data type ntext is invalid for argument 1 of replace function.

To resolve this, we can cast ntext type to nvarchar(max) and then update column with this value: Following query will work without any error:

update description_table set description = replace(CAST(description AS NVARCHAR(MAX)),'../G/','http://styletint.in/G/') where description like '%../G/%'