Wednesday, January 18, 2012

Return multiple object using JSON in Asp.net MVC

Here are we going to discuss what are the differnt ways to send json response to browser.

Note: we are assuming that json2. js file is already added into html page  you can use following url to download json2.js file or you can directly add this link in your page .

http://www.JSON.org/json2.js
<script type="text/javascript" src=http://www.JSON.org/json2.js />

1. It  is straight forward to retrun a single json object using following statement:

public JsonResult getResult()
{
        // Create an object of any kind
        Report objReport= new Report();
  
retun Json( objReport);
}

in html file we can use it like

function callback(response)
{
     var JsonObject= Json.parse(response);
//now we can use JsonObject same Report Object


}


2. It straight forward to retrun a Multiple object using json  byfollowing statement:

public JsonResult getResult()
{
        // Create an object of any kind
        Report actualReport= new Report();
        Report scheduledReport= new Report();
  
retun Json( new { ActualReport=actualReport,ScheduledReport=scheduledReport);
}

in html file we can use it like

function callback(response)
{
     var JsonObject= Json.parse(response);
//now we can use JsonObject same Report Object
 var actualReport= JsonObject.ActualReport;
var scheduledReport= JsonObject.ScheduledReport;

}

3. It straight forward to retrun a Dynamically Added Multiple object using json  by following statement:

a) if we are sending list of object we will be able to access these using Indexes
public JsonResult getResult(int numberOfReports)
{
        // Create an object of any kind
      List<Report> reportList= new List<Report>();

        Report report= null;
        for(int i=0;i<numberOfReports;i++){
                 report= new Report(); 
                // set properties to report Object 
                 reportList.Add(report);
        }
       
  
retun Json( reportList);
}

in html file we can use it like

function callback(response)
{
     var JsonObject= Json.parse(response);
//now we can use JsonObject same Report Object
// use JsonObject like
//alert(JsonObject[0]  );

}

b) if we are sending list of object we will be able to access these using Indexes
public JsonResult getResult(int numberOfReports)
{
        // Create an object of any kind
      Dictionary<string,Report> reportList= new Dictionay<string,Report>();

        Report report= null;
        for(int i=0;i<numberOfReports;i++){
                 if(i%2==0){                
                 report= new Report(); 
                // set properties to report Object 
                 reportList.Add("obj"+i.ToString(),report);
               }
               elseif(i%2!=0)
              {
                        report= new Report(); 
                      // set properties to report Object 
                       reportList.Add("obj"+ i.ToString(),report);
               }
        }
       
  
retun Json( reportList);
}

in html file we can use it like

function callback(response)
{
     var JsonObject= Json.parse(response);
//now we can use JsonObject same Report Object
// use JsonObject like
//alert(JsonObject.obj1  );
//alert(JsonObject.obj2  );
// and so on

}

I hope it will help you how can me send JsonResult back to browser.

Happy Living...
Happy Concepts...
Happy Programming...

Monday, January 16, 2012

Exception from HRESULT: 0x80070057 (E_INVALIDARG))

This is very comman issue while we try to run asp.net application we get following error

Could not load file or assembly 'ProjectName' or one of its dependencies. The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))

So basic reason of this issue is that we havent cleaned the project or temprory files

Do 2 things to remove this issue
1. Clean your project and rebuild the project.
2. After following step 1 if you are still having same issue. check target framework of project and go to following location and delete all files

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files

In My case, project was in .net framework 4.0 so i deleted temporary asp.net files from its child folder. If your project is targeting to some other project delete  Temporary ASP.NET Files from its child folders.

Happy Living...
Happy Concepts...
Happy Programming....

Saturday, December 17, 2011

Speed up query or Stored procedure in sql server 2005 or 2008

Speed up query or Stored procedure in sql server 2005 or 2008

Way to optimize your query or stored procedure:

1. We can use Sql perfomance tuner under Tool's in menu bar. we just need to provide script file or database object like sp to get suggestion from sql server 2005.
Mostly it will ask to add index and statistics into tables.

2. We can also use Estimated Plan to check if our query missing any index or statistics on a table.


Happy Living...
Happy Coding...
Happy Concepts...

    

Wednesday, December 14, 2011

Open Modal Popup in different Browsers



In Windows Internet Explorer supports a direct method to open a modal pop using

window.showModalDialog("popupModel.html") ;

method.

To get more information on window.showModalDialog(xxxxxxxxxxx)  visit:
 http://fromdotnet.blogspot.com/2011/09/call-parent-window-methods-form-dialog.html

We have one advantage with showModalDialog that we can pass arguments to Modal popup.

But other Browser doesnt support it and they have there own way to implement it by passing an additonal property model=yes with Window.Open() method.

window.open('popupModal.html','name',
'height=255,width=250,toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no ,modal=yes');

Example:
function popupModalWin() {
if (window.showModalDialog) {
var
window.showModalDialog("popupModelWindow.htm",,"popupModelWindowName",
"dialogWidth:255px;dialogHeight:250px");
}
else {
window.open(popupModelWindow.htm','popupModelWindowName',
'height=255,width=250,toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no ,modal=yes');
}
}



Happy Living...
Happy Coding...
Happy Concepts....

Thursday, December 8, 2011

"HTTP Error 404 - File or Directory not found" error with windows server 2003 message when you request dynamic content with IIS 5.0 and IIS 6.0

"HTTP Error 404 - File or Directory not found" error message when you request dynamic content with IIS 6.0

Changes required in webExtension for to allow Activeserverpage and other page based on our application for example for asp.net its ActiveServerPage. Just allow to access these pages through server.
And magically its done :).
Use Below link for more information:


By default only static content HTML is enabled in windows server 2003 family when IIS is installed on any version of the its family.

So enable web server extensions.

Happy Living....
Happy Coding.....
Happy Concepts .....

Wednesday, November 30, 2011

Right place to put Response.Redirect

One of my Friend was encountered with this a issue in security auditing where redirect wasn't working as expected.


Actual issue:


He was new with asp.net so instead of using form authentication/authorization he used simple session to maintain logged in user. so on each page he was checking if session contain valid information like user name and role to access internal page. If it doesn't exists the user redirected to log in page.
               For a normal user it was fine it was working as it should but for hacker it contain where while looking pages response into some tool she will be able to see response code 302 change(redirect response code) and body of undisplayed page. Just by changing status code to 302 change to 200 OK she was able to see the page in browser. and by sending it again server it can lead to other exception or other uses are also possible.

page_Load()
{
..........
..........
// some code to check authenticate/authorize user
if (failed)
{
Response.Redirect("Login.aspx?target=http://...../currentpage.aspx",false);
}
else
// continue with page
}

Suggested Solution:


Page_Load is state where our page is already loaded so there isn't any benefit of using false (which indicates not to load page control).


So better place to put validation code is OnInit() method:

OnInit()
{
..........
..........
// some code to check authenticate/authorize user
if (failed)
{
Response.Redirect("Login.aspx?target=http://...../currentpage.aspx",false);
}
else
// continue with page
}

So i suggested him to put it on OnInit and i dont know if its working. I am waiting for his response :).


Happy Living, Happy Coding.


Thanks
Yashpal Sharma


Thursday, November 24, 2011

Split a Value in SqlSever



If we want values in the from of individual text so we can use following way:
1. If we have a text value combination so here is the way to separate these 2 values :


Declare @CompositeValue as Varchar(500)
set @CompositeValue='Text_Value'

Select Substring(@CompositeValue,0,CharIndex('_,@CompositeValue,1')) as Text

Select Substring(@CompositeValue,CharIndex('_,@CompositeValue,1')+1,Len(@CompositeValue)) as Value

2. There is another way to get split-ed value in a form of table :


/****** Object:  UserDefinedFunction [dbo].[Split]    Script Date: 05/10/2012 20:30:30 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[Split]
(
    @String nvarchar(max),
    @Delimiter char(1)
)
returns @Results TABLE (ID int identity, Item nvarchar(4000))
as
   begin
   declare @index int
   declare @slice nvarchar(max)

   select @index = 1
   if @String is null return

   while @index != 0
       begin
        select @index = charindex(@Delimiter,@String)
          if @index !=0
           select @slice = left(@String,@index - 1)
          else
             select @slice = @String

          insert into @Results(Item) values(ltrim(rtrim(@slice)))

          select @String = right(@String,len(@String) - @index)
          if len(@String) = 0 break
       end  
  
    return
end
GO


Happy Living , Happy Coding 
Yashpal Sharma