Wednesday, 4 March 2015

ajax pro is not working with .Net Framework 4.0 and visual studio 2013

If you guys are converting from .net2.0 to 4.0 and visual studio 2013 then you may experience that your ajax pro will not work.

Ajax pro is work with classic managed pipeline mode.

In visual studio 2013 there is a facility to change managed pipeline mode via website Property window.










By default it is integrated for me.

So i change it to Classic and Ajax pro is working.

Thursday, 12 February 2015

Potentially dangerous Request.Form value was detected

Sys.WebForms.PageRequestManagerServerErrorException:An unknown error occurred while processing the request on the server. The status code returned from the server was: 500
Today i was stucked in one issue after converting my website from .net2.0 to 4.0.

In .net2.0 page is working fine with ValidateRequest="false" but after converting to 4.0 it's throwing error

Sys.WebForms.PageRequestManager.prototype._endPostBack  ScriptResource.axd
 Sys.WebForms.PageRequestManagerServerErrorException:An unknown error occurred while processing the request on the server. The status code returned from the server was: 500


I tried different way to solve the issue but no luck.at the end i tried to remove ValidateRequest="false" attribute from page and then i got actual error which is that "Potentially dangerous Request.Form value was detected"

It was because i am storing some xml values in hidden field.but the strange in .net2.0 it was working fine then what is the issue in 4.0.

I think in .net4.0 Microsoft has change  some logic of validating request of web page.

So currently i have 2 solution to solve the issue.

1. Change the code and remove xml things from hidden variable.
2. I can validate page request as per .net framework 2.0

So Solution no 2 is better for me.

I have added following attribute to web.config

<httpRuntime requestValidationMode="2.0"/>

Saturday, 31 August 2013

Download interrupted in IE10


In IE 10 you guys may get error Download interrupted error for some files which is grater then 20mb.

It's error occurred in IE10 only.

So For that you need to change something in your code.

If you use Response.close(); then remove it.

Just wirte something below.

Response.Flush();
Response.End();

For more info visit
http://blogs.msdn.com/b/ieinternals/archive/2012/07/16/content-length-and-transfer-encoding-validation-in-ie10-download-manager-couldnt-be-downloaded-retry-cancel.aspx

Tuesday, 22 January 2013

Set Wallpaper using C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using Microsoft.Win32;  

namespace CustomWallpaper
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private static readonly UInt32 SPI_SETDESKWALLPAPER = 0x14;
        private static readonly UInt32 SPIF_UPDATEINIFILE = 0x01;
        private static readonly UInt32 SPIF_SENDWININICHANGE = 0x02;

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern Int32 SystemParametersInfo(
            UInt32 action, UInt32 uParam, String vParam, UInt32 winIni);

        private void Form1_Load(object sender, EventArgs e)
        {
            string strPath = "D:\\Projects\\Wallpaper\\Wallpaper.jpg";

            
            if (File.Exists(strPath))
            {
                SetWallpaper(strPath);
            }
            else
            {
                 strPath = "D:\\Projects\\Wallpaper\\Wallpaper.jpeg";
                if (File.Exists(strPath))
                { 
                    SetWallpaper(strPath); 
                }
                else
                {
                    strPath = "D:\\Projects\\Wallpaper\\Wallpaper.png";
                    if (File.Exists(strPath))
                    {
                        SetWallpaper(strPath); 
                    }
                    else
                    {
                        MessageBox.Show("Wallpaper.jpg Or Wallpaper.jpeg OR Wallpaper.png is not found on this path D:\\Projects\\Wallpaper\\");
                        this.Close();
                    }
                }
            }
        }

        private void SetWallpaper(string path)
        {
            SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path,SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);

            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);            
            key.SetValue(@"WallpaperStyle", 2.ToString());
            key.SetValue(@"TileWallpaper", 0.ToString());            
            this.Close();
        }
    }
}


Monday, 7 January 2013

Dialog is not a function in asp.net mvc

Guys you may get error when using jquery dialog function in your mvc application.It's because by default visual studio importing script which is old version script and also it's not importing jquery-ui-1.9.2.custom.js.

Dialog is function of ui js.

Here below you can see how js import by default in _layout.cshtml by visual studio. 




you have to change this and cut it and paste to top of the page because if you import jquery ui in top of the page then you may get the error that jquery is undefined. so as we are doing always put it to top of the page like as shown in below image. 



Now you guys have to update the version of js like below.



Now finally you guys have to update all new css version of ui inContent -->themes-->base

 

Wednesday, 2 January 2013

Cascading dropdownlist using Jquery in MVC

Hii guys it's little difficult to do code for cascading dropdwon in asp.net mvc. In asp.net web forms We have a directly event of asp.net control. While in mvc we have html control and there is no event. So What we have to do we have to use Jquery event for this and make ajax call to our server side code and then bind the dropdown. Here below explain how to achieve this. First of all we have to import jquery so we can use jquery functions like we importing namespace in our C# code.

Here below is Jquery functions required to bind the dropdown list. Let me explain how these functions are working.
$('#Country').change this is jquery dropdown change event whatever code you write inside this it will run when country dropdown index is changed. Inside this event i am calling function GetState($(this).val())
In Getstate function i am calling one ajax method and calling action result "GetState" which is my C# code is written in controller named nik.
As you can see in action result i have argument name countryid so i can pass from here like this way data: { 'Countryid': Countryid }
Now with this country id i will return states in json format of the passed coutryid.
I also get city of selected state same way here is change event for state dropdwon $('#State').change


Here below is code you can see is that simple html code. But something strange you can find like VIEWBAG. View bag helps to maintain data when you move from controller to view. So here using view bag i am binding country dropdown. You can see in action result DropDown i am setting value of ViewBag. ViewBag.Country = items;
<%-- Here is dropdowns --%>
@{
    ViewBag.Title = "DropDown";
}

DropDown

Country : @Html.DropDownList("Country", (IEnumerable)ViewBag.Country, htmlAttributes: new { id = "Country"})
State :
City :

Here below you guys can see it is controller code. There are 3 different action result Dropdown,GetState,GetCity.
Let me explain when these all will fired.
1.Dropdwon :- This will fire when my page is load first time or when page is postback again.
2.GetState :- As i explain above it will fired by ajax method which i write in GetState(Countryid) jquery function.
3.GetCity :- Same as "GetState" it will fired by ajax method which i write in GetCity(Stateid) jquery function.
'Here is controller code

namespace MvcApplication1.Controllers
{
    public class NikController : Controller
    {
        public ActionResult DropDown()
        {       
            List items = new List();
                items.Add(new SelectListItem { Text = "---Select Country---", Value = "0", Selected = true });
                items.Add(new SelectListItem { Text = "India", Value = "1",Selected= true  });
                items.Add(new SelectListItem { Text = "USA", Value = "2" });
                items.Add(new SelectListItem { Text = "Russia", Value = "3"});
                items.Add(new SelectListItem { Text = "South Africa", Value = "4" });
                ViewBag.Country = items;            
                return View(); 
        }


        public ActionResult GetState(int Countryid)
        {
            List States = new List();

            if (Countryid==1)
            {
                States.Add(new SelectListItem { Text = "Gujarat", Value = "1", Selected = true });
                States.Add(new SelectListItem { Text = "Maharashtra", Value = "2"});
                States.Add(new SelectListItem { Text = "Rajsthan", Value = "3"});
                States.Add(new SelectListItem { Text = "Punjab", Value = "4"});
                States.Add(new SelectListItem { Text = "MP", Value = "5" });
                States.Add(new SelectListItem { Text = "Keral", Value = "6" });
                States.Add(new SelectListItem { Text = "Karnatak", Value = "7"});
                States.Add(new SelectListItem { Text = "Jammu", Value = "8"});
                States.Add(new SelectListItem { Text = "Assam", Value = "9"});
                States.Add(new SelectListItem { Text = "AP", Value = "10"});
            }                                                                                                    
            else if(Countryid ==2)
            {
                States.Add(new SelectListItem { Text = "Alabama", Value = "11", Selected = true });
                States.Add(new SelectListItem { Text = "Alaska", Value = "12"});
                States.Add(new SelectListItem { Text = "Arizona", Value = "13"});
                States.Add(new SelectListItem { Text = "Arkansas", Value = "14"});
                States.Add(new SelectListItem { Text = "California", Value = "15"});
                States.Add(new SelectListItem { Text = "Colorado", Value = "16"});
                States.Add(new SelectListItem { Text = "Connecticut", Value = "17"});
                States.Add(new SelectListItem { Text = "Delaware", Value = "18"});
                States.Add(new SelectListItem { Text = "Florida", Value = "19" });
                States.Add(new SelectListItem { Text = "Georgia", Value = "20"});
            }

            return Json(States);
        }


        public ActionResult GetCity(int Stateid)
        {
            List City = new List();

            if (Stateid == 1)
            {
       City.Add(new SelectListItem { Text = "Ahmedabad", Value = "1", Selected = true });
                City.Add(new SelectListItem { Text = "Surat", Value = "2" });
                City.Add(new SelectListItem { Text = "Baroda", Value = "3" });
                City.Add(new SelectListItem { Text = "Rajkot", Value = "4" });
                City.Add(new SelectListItem { Text = "Jamnagar", Value = "5" });
                City.Add(new SelectListItem { Text = "Junagadh", Value = "6" });
                City.Add(new SelectListItem { Text = "Jetpur", Value = "7" });
                City.Add(new SelectListItem { Text = "Bharuch", Value = "8" });
                City.Add(new SelectListItem { Text = "Limabi", Value = "9" });
                City.Add(new SelectListItem { Text = "Vapi", Value = "10" });
            }
            return Json(City);
        } 
    }
}
Here it is how it look likes.

Friday, 14 December 2012

Track Alter stored procedure in Sql Server

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE trigger [Tracking_Alter_SP]
on database
for create_procedure, alter_procedure, drop_procedure,
create_table, alter_table, drop_table,
create_function, alter_function, drop_function
as set nocount on

SET ARITHABORT ON

declare @data xml
set @data = EVENTDATA()

insert into changelog(databasename, eventtype,
    objectname, objecttype, sqlcommand, loginname,hostname)
values(
@data.value('(/EVENT_INSTANCE/DatabaseName)[1]', 'varchar(300)'),
@data.value('(/EVENT_INSTANCE/EventType)[1]', 'varchar(60)'),
@data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'varchar(300)'),
@data.value('(/EVENT_INSTANCE/ObjectType)[1]', 'varchar(50)'),
@data.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'varchar(max)'),
@data.value('(/EVENT_INSTANCE/LoginName)[1]', 'varchar(300)'),
HOST_NAME()
)
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


Get Control in Gridview's Row command Event

<%-- Let us consider below is our grid.--%>

 
      
           
              

              
           
      
 

'Here is code behind.
Private Sub gridview_RowCommand(sender As Object, _

e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridview.RowCommand
 
Dim btnActive As Button = DirectCast(e.CommandSource, Button)
Dim index As Integer = DirectCast(btnActive.Parent.Parent, GridViewRow).RowIndex
Dim chkmail As CheckBox = DirectCast(gridview.Rows(index).FindControl("chkmail"), CheckBox) 

'Here i get control like btnactive.parent.parent.It may be different for you.
'It depends how many controls you use in grid view. 

End Sub

Performance of CTE(Common table expression) Vs Hash(#)Tables.


Let say we have one report and in which we want data from around 20 tables.

so i just created some 4 to 5 cte(Common table expression) for every 4 to 5 tables.

and then join cte's and get the data.but when i execute that stored procedure it will take around 10 Minutes.

i am really strange about this.

Now what i do just replace all cte(Common table expression) with Hash(#)table.

and it's executed with only around 15 seconds.

So i suggest when cte 1 or 2 then ok but 4 to 5 then you can use #tables.

This is work for me.Let's you guys try it.if you use cte and it will take too much time to execute.

Friday, 7 December 2012

Bind WebGrid in Asp.net MVC


I just learn how to bind grid in MVC. I hope you guys just know basic about MVC.
First of all You guys just have to install one package.for that got to Tools->Library Package Manager
and run command in output window
Command:- Install-Package RazorGenerator.Templating

1.) Below is controller code.
in above code i just create simple List of my model.you can also get that list from database also.

2.) Below is model code.


in above code simple properties are created.

3.) Below is view code.







Here is your view code. here one thing is that you have to take care is that is first line.i tried with @model MvcApplication1.Models.NiksModel but it means it accept model from controller.but here we are passing list from controller so you just have defined as list of your model.

Reference:
http://www.dotnetcurry.com/ShowArticle.aspx?ID=618


Wednesday, 28 November 2012

View Last Excuted Quries in Sql Server


View Last Excuted Quries in Sql Server
SELECT DEQS.LAST_EXECUTION_TIME AS [TIME]
,SUBSTRING(DEST.TEXT,(DEQS.STATEMENT_START_OFFSET/2)+1
,((CASE DEQS.STATEMENT_END_OFFSET WHEN -1 THEN DATALENGTH(DEST.TEXT)ELSE DEQS.STATEMENT_END_OFFSET
END - DEQS.STATEMENT_START_OFFSET)/2) + 1) AS STATEMENT_TEXT
,DEST.*
FROM SYS.DM_EXEC_QUERY_STATS AS DEQS
CROSS APPLY SYS.DM_EXEC_SQL_TEXT(DEQS.SQL_HANDLE) AS DEST
ORDER BY DEQS.LAST_EXECUTION_TIME DESC

Thursday, 24 May 2012

Comma seperated records in sql without loop or cursor

SELECT STUFF
(
(

SELECT ',' + T1.FULLNAME AS [text()]

FROM DBO.TABLE_1 AS T1

INNER JOIN DBO.TABLE_2 AS T2 ON T1.ID = T2.ID

FOR XML PATH('')
)
,1,1,''
)


DECLARE @COLS NVARCHAR(2000)

SELECT @COLS = COALESCE(@COLS + ',[' + CONVERT(NVARCHAR(100),T1.FULLNAME ) + ']','[' + CONVERT(NVARCHAR(100),T1.FULLNAME) + ']')

FROM DBO.TABLE_1 AS T1

INNER JOIN DBO.TABLE_2 AS T2 ON T1.ID = T2.ID

Friday, 11 November 2011

Insert and update data Using Xml file in Sql Server

'Making Xml 
 Dim sb As New System.Text.StringBuilder
sb.Append("")
For i = 0 To dt.Rows.Count - 1
sb.Append(" sb.Append("PQty=""" & dt.Rows(i).Item("PQty") & """")
sb.Append("PWeight=""" & ClearWhiteSpace(dt.Rows(i).Item("PWeight")) & """")
sb.Append("/>")
Next
sb.Append("
")
-- Making Stored Procedure
CREATE PROCEDURE [dbo].[TestMasterInsert]    
    @MId Int,    
    @GId Int,
    @PId Int,
    @Name varchar(50),
    @Data text,
    @TranType  Char(1)
AS
BEGIN    
    SET NOCOUNT ON;    
    
    Declare @id As Int 
        SET @id = 0
        
        DECLARE @hDoc int exec sp_xml_preparedocument @hDoc OUTPUT, @Data
        
    IF @TranType = 'I'    
        BEGIN        
            Insert Into TestMaster Values (@GId,@PId,@Name)
        
            Select @id = SCOPE_IDENTITY()  
        
            INSERT INTO TestDetail
                SELECT @id,PQty,PWeight
                FROM   OPENXML (@hDoc, '/ROOT/SI',2)          
                WITH (
                       PQty       Decimal(18,3) '@PQty',
                       PWeight    Decimal(18,3) '@PWeight'
                     )   
          
             EXEC sp_xml_removedocument @hDoc
        END
    ELSE IF @TranType = 'U'        
        BEGIN
            
            UPDATE TestDetail     
            SET     
                  TestDetail.PQty = XMLTEST.PQty,    
                  TestDetail.PWeight = XMLTEST.PWeight
            FROM OPENXML(@hDoc, '/ROOT/SI',2)
                        WITH (DId Int '@DId',PQty Decimal(18,3) '@PQty',PWeight Decimal(18,3) '@PWeight') XMLTEST
            WHERE  TestDetail.DId = XMLTEST.DId
            
            EXEC sp_xml_removedocument @hDoc        
        END    
END

Friday, 4 November 2011


Imports System.ServiceProcess
Imports System.IO
Public Class Service1
    Inherits System.ServiceProcess.ServiceBase
    Public Shared DailyTime As String = "DailyTime.txt"
    Public Shared errlogfile As String = "Error.err"


    Protected Overrides Sub OnStart(ByVal args() As String)
        Try


        Catch ex As Exception
            [Error]("OnStart:-" + ex.Message + DateTime.Now.ToString())
        End Try
    End Sub


    Protected Overrides Sub OnStop()
        ' Add code here to perform any tear-down necessary to stop your service.
    End Sub


    Protected Overrides Sub OnSessionChange(ByVal changeDescription As SessionChangeDescription)
        Try


            Select Case changeDescription.Reason
                Case SessionChangeReason.SessionLogon


                    [InsertDailyTime]("Session Logon:-" + DateTime.Now.ToString())


                    Exit Select
                Case SessionChangeReason.SessionLogoff
                    [InsertDailyTime]("Session Logoff:-" + DateTime.Now.ToString())
                    Exit Select
                Case SessionChangeReason.RemoteConnect
                    'Remote Connect 
                    Exit Select
                Case SessionChangeReason.RemoteDisconnect
                    'Remote Disconnect 
                    Exit Select
                Case SessionChangeReason.SessionLock
                    [InsertDailyTime]("Session Lock:-" + DateTime.Now.ToString())
                    Exit Select
                Case SessionChangeReason.SessionUnlock
                    [InsertDailyTime]("Session Unlock:-" + DateTime.Now.ToString())
                    Exit Select
                Case Else
                    Exit Select
            End Select


        Catch ex As Exception
            [Error]("OnSessionChange:-" + ex.Message + DateTime.Now.ToString())
        End Try
    End Sub


    Public Shared Sub [InsertDailyTime](ByVal message As String)
        Dim datewisefile As String = ""
        Dim dt As DateTime = DateTime.Now
        Dim fs As System.IO.FileStream = Nothing
        Dim info As Byte() = Nothing
        Try
            If Not System.IO.Directory.Exists(Path.GetDirectoryName("D:\Projects\TimeManager")) Then
                System.IO.Directory.CreateDirectory(Path.GetDirectoryName("D:\Projects\TimeManager"))
            End If
            'logfile = logfile.Split('.')[0] + System.DateTime.Now.ToString("yyyyMMddHHmm") + '.' + logfile.Split('.')[1]; 
            datewisefile = ((dt.Year & "") + "-" + (If(dt.Month <= 9, "0" & dt.Month & "", dt.Month & "")) & "") + "-" + (If(dt.Day <= 9, "0" & dt.Day & "", dt.Day & ""))
            DailyTime = "\Nik's_" & datewisefile & ".txt"
            fs = System.IO.File.Open(Path.GetDirectoryName("D:\Projects\TimeManager") & "\logs" + DailyTime, System.IO.FileMode.Append)
            info = New System.Text.UTF8Encoding(True).GetBytes((System.DateTime.Now.ToString() & ":") + message & vbLf)
            ' fs.Close(); 
            fs.Write(info, 0, info.Length)
            fs.Flush()
            fs.Close()
            fs = Nothing
            info = Nothing
        Catch ex As Exception
            [Error]("InsertDailyTime:-" + ex.Message + DateTime.Now.ToString())
        Finally
            'GC.SuppressFinalize(Me)
        End Try
    End Sub


    Public Shared Sub [Error](ByVal message As String)
        Dim datewisefile As String = ""
        Dim dt As DateTime = DateTime.Now
        Dim fs As System.IO.FileStream = Nothing
        Dim info As Byte() = Nothing
        Try
            If Not System.IO.Directory.Exists(Path.GetDirectoryName("D:\Projects\TimeManager") & "\logs") Then
                System.IO.Directory.CreateDirectory(Path.GetDirectoryName("D:\Projects\TimeManager") & "\logs")
            End If
            'logfile = logfile.Split('.')[0] + System.DateTime.Now.ToString("yyyyMMddHHmm") + '.' + logfile.Split('.')[1]; 
            datewisefile = ((dt.Year & "") + "-" + (If(dt.Month <= 9, "0" & dt.Month & "", dt.Month & "")) & "") + "-" + (If(dt.Day <= 9, "0" & dt.Day & "", dt.Day & ""))
            errlogfile = "\TimeManager_" & datewisefile & ".Log"
            fs = System.IO.File.Open(Path.GetDirectoryName("D:\Projects\TimeManager") & "\logs" + errlogfile, System.IO.FileMode.Append)
            info = New System.Text.UTF8Encoding(True).GetBytes((System.DateTime.Now.ToString() & ":") + message & vbLf)
            ' fs.Close(); 
            fs.Write(info, 0, info.Length)
            fs.Flush()
            fs.Close()
            fs = Nothing
            info = Nothing
        Catch ex As Exception
            'Write("Error:"+ex.Message); 
        Finally
            'GC.SuppressFinalize(Me)
        End Try
    End Sub


End Class

Thursday, 29 September 2011

Open task manager on remote computer even explorer.exe is not running

sometime happens that when we take remote computer and it gets hangs and we end process the explorer.exe and may be task manager also closed.at that time you can use Ctrl+Alt+End t for opening task manager.

Thursday, 4 August 2011

Never Use Sql Connection's Global Object

Never Use sqlConnection's global object in class.because it's create too much problem.it may crash the system.i really face this Issue.for Complete Issue Please see below link.

      

Friday, 15 July 2011

Split Function in Sql

CREATE FUNCTION DBO.SPLIT
(
    @LIST NVARCHAR(2000),
    @SPLITON NVARCHAR(5)
)  
RETURNS @RTNVALUE TABLE 
(
        
    ID INT IDENTITY(1,1),
    VALUE NVARCHAR(100)
) 
AS  
BEGIN
WHILE (CHARINDEX(@SPLITON,@LIST)>0)
BEGIN 
INSERT INTO @RTNVALUE (VALUE)
SELECT
    VALUE = LTRIM(RTRIM(SUBSTRING(@LIST,1,CHARINDEX(@SPLITON,@LIST)-1))) 
    SET @LIST = SUBSTRING(@LIST,CHARINDEX(@SPLITON,@LIST)+LEN(@SPLITON),LEN(@LIST))
END 
   INSERT INTO @RTNVALUE (VALUE)
    SELECT VALUE = LTRIM(RTRIM(@LIST))

    RETURN
END

Wednesday, 13 July 2011

Pass Eval as Argument Of Javascript Function

<input type="button" id="but1" onclick="myFunction('<%# Eval("id") %>','<%# Eval("name")%>' )" />