Friday, February 25, 2011

Opening a Pdf file in a seperate windows using ASP.NET

How it works:

1. File uploader is used to get the pdf file input.

2. The pdf stream is recieved in the form of bytes using fupload.PostedFile.InputStream.Read and it is stored in the byte variable.

3. The stream variable is stored in the session.

4. The Read Document button opens the pdf file with the help of windows.open.

5. The child pop up usually spits up the session pdf stream with the help of Response.BinaryWrite.

Two files has been used. 
one to upload the pdf file (AcrobatReader.aspx) and the other to show the pdf file(Reader.aspx).

Functionality to received the pdf stream from fileupload control and open a child popup window

  if (fupDocument.HasFile && fupDocument.PostedFile.ContentLength > 0)
  {
      HttpPostedFile myFile = fupDocument.PostedFile;
                   
      Byte[] buffer = new byte[myFile.ContentLength];
      myFile.InputStream.Read(buffer, 0, myFile.ContentLength);
      Session["buffer"] = buffer;

      Response.Write("<SCRIPT language=javascript>var  pdf=window.open('Reader.aspx','pdf','width=600,height=400');pdf.moveTo(0,0);</SCRIPT>");
  }

Functionality to display the pdf stream

    Byte[] buffer = (byte[]) Session["buffer"];
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-length", buffer.Length.ToString());
    Response.BinaryWrite(buffer);

    Session["buffer"] = null;





Tuesday, February 22, 2011

Document Navigation using HTML

You may have visited some sites which contains many links where you can navigate within a page. so how to do it..

You need just two anchor one with href and one with name..

Does that sounds cool

here is the coding


<a href="#bottom"> go to bottom </a>
MOVE TO  BOTTOM
MOVE TO  BOTTOM
MOVE TO  BOTTOM
MOVE TO  BOTTOM
MOVE TO  BOTTOM
MOVE TO  BOTTOM

<a name="bottom">BOTTOM</a>

Monday, February 21, 2011

How to Increase the Session timeout in ASP.NET

By default the session timeout is 20 minutes for IIS and session variables. Inorder to increase the session timeout you need to do the following changes.

 <system.web>
  <sessionState timeout="540"  mode="InProc" />  <!-- In minutes -->
  </system.web>

and in the IIS seetings changes the following
1. Open Internet Services Manager.
2.  From the Web site Properties, click the Home Directory tab, then click the Configuration... button in the Application Settings section.
3.  On the configuration panel, click the App Options tab and set the session timeout there. 

If your using form authentication then you need to do the following settings and by default the form authentication session timeout is 30 minutes.

<system.web>
    <authentication mode="Forms">
          <forms timeout="50000000"/>  <!-- in minutes -->
    </authentication>
</system.web>

Friday, February 18, 2011

Difference between Table Variables and Temporary Tables

There are four types of temporary tables Local Temporary tables, Global Temporary Tables Permanent Tables and Tables variables.

How to declare Temporary Tables


CREATE TABLE #people
(
    id INT,
    name VARCHAR(32)
)


DECLARE @people TABLE
(
    id INT,
    name VARCHAR(32)
)

 Scope

The temporary table is deleted automatically when it is goes out of the scope but you should manually drop it to use it again.

DROP TABLE #people

But in the table variable the table is dropped automatically when it goes out of the scope. 

What are the difference between Temp and Table Variables

1.Table variables result in fewer recompilations of a stored procedure as compared to temporary tables.

2. You cannot use the EXEC statement or the sp_executesql stored procedure to run a dynamic SQL Server query that refers a table variable, if the table variable was created outside the EXEC statement or the sp_executesql stored procedure. Because table variables can be referenced in their local scope only, an EXEC statement and a sp_executesql stored procedure would be outside the scope of the table variable.

FYI: However, you can create the table variable and perform all processing inside the EXEC statement or the sp_executesql stored procedure because then the table variables local scope is in the EXEC statement or the sp_executesql stored procedure.

3. You use table variables whenever possible except when there is a significant volume of data and there is repeated use of the table because table variables doesnot create any indexes.

4. You cannot use a table variable in Select INTO
    SELECT * INTO @table FROM someTable

5. You cannot truncate a table variable. 

6.  You cannot drop a table variable.

7. You cannot generate a table variable's column list dynamically, the below will throw the error
     SELECT * INTO @tableVariable 

 8. Table variables must be referenced by an alias name when it is used in the JOINS.

      SELECT id
    FROM @foo f
    INNER JOIN #foo
    ON f.id = #foo.id

9.  Table variable use fewer resource than a temporary table because of there limited scope. 

10. we cannot change the definition of the table after the table is created. 

11. Microsoft also say transactions involving table variables require less logging. I assume they say this because the transactions are shorter.





Traversing through the list of items in a table without using cursors.

What we do
1.  Retrieve the values from the Requirement Table.
2. Insert into the table variable.
3. Insert into the actual table by doing some processing on each record of table variable.

Structure of Table variable
DECLARE @RequirementIds TABLE
(
    Id INT,
    ReqId INT
)

--Retrieve the list of requirement ids
INSERT INTO @RequirementIds(Id,ReqId)
SELECT Id,CAST(Data AS INT) AS ReqId FROM Requirements

-- Get the total requirement ids
DECLARE @RowCount INT
SET @RowCount = (SELECT COUNT(Id) FROM @RequirementIds)



-- Declare an iterator
DECLARE @I INT
SET @I = 1



-- Loop through the rows of a table Assets
WHILE (@I <= @RowCount)
BEGIN     


        INSERT INTO Assets      
        (
          AssetsId,
          ProjectID,
          ReqID,
          AssetTypeID,       
          Title,
          [Description],
          FileSize,
          URL,
          CanVersion,
          [Version],
          [FileName],
          CreatedBy,
          DateCreated
         )       
        SELECT       
        (Select COALESCE(Max(AssetsId),0) + 1 FROM Assets WHERE ReqID=RI.ReqId AND ProjectID=@ProjectID) AS AssetsId,
        @ProjectID,
        RI.ReqId,
        @AssetTypeID,      
        @Title,
        @Description,
        @FileSize,
        REPLACE(@FURL,'{0}',CAST(RI.ReqId AS VARCHAR(3))) AS URL,
        @CanVersion,
        @Version,
        @FileName,   
        @CreatedBy,   
        @DateCreated
        FROM @RequirementIds RI WHERE Id = @I      
       
        SET @I = @I  + 1
END



Split Function in Sql Server

Input: 
Row Data:  100,200,300,4000
SplitOn : ','

Output as Table
-----------------
Id      Data
-----------
1        100
2        200
3        300
4        4000


ALTER FUNCTION [dbo].[Split]
(
    @RowData nvarchar(2000),
    @SplitOn nvarchar(5)

RETURNS @RtnValue table
(
    Id int identity(1,1),
    Data nvarchar(100)
)
AS 
BEGIN
    Declare @Cnt int
    Set @Cnt = 1


    While (Charindex(@SplitOn,@RowData)>0)
    Begin
        Insert Into @RtnValue (data)
        Select
            Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))


        Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
        Set @Cnt = @Cnt + 1
    End
   
    Insert Into @RtnValue (data)
    Select Data = ltrim(rtrim(@RowData))


    Return
END

Monday, February 14, 2011

IMultipleResults using LINQ

There may be situation where you want to retrieve multiple result from a single stored procedure, this was easy process using previous dataset and SQLConnection and SQLParameters, but in LINQ we need to do some coding to get it worked.
The LINQ only support SingleResult by default so inorder for your LINQ.dbml to support multipleresults you need to do a manual coding to get it done.

Below are the following steps to get it done..

Step 1:  First of all you need to retrieve the singleresultset class template.. Usually when you drag and drop a particular storedprocedure into the dbml file it generates a singleresultset class template in the form of partial class. Make a copy of each partial resultset. The singleresultset class template usually is available in the SluiceDb.designer.cs.

The sample of singleresultset template

public partial class AssetsProject_SelectByAssetSearchResult
    {

        private int? _ID;

        private int? _AssetsID;

        private string _Title;
       
        private string _FileName;

        private string _URL;

        private string _CreatedBy;

        private string _UploadedDate;

        private string _FileSize;

        public AssetsProject_SelectByAssetSearchResult()
        {
        }

        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_ID", DbType = "Int")]
        public int? ID
        {
            get
            {
                return this._ID;
            }
            set
            {
                if ((this._ID != value))
                {
                    this._ID = value;
                }
            }
        }


        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_AssetsID", DbType = "Int")]
        public int? AssetsID
        {
            get
            {
                return this._AssetsID;
            }
            set
            {
                if ((this._AssetsID != value))
                {
                    this._AssetsID = value;
                }
            }
        }

        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_Title", DbType = "NVarChar(4000)")]
        public string Title
        {
            get
            {
                return this._Title;
            }
            set
            {
                if ((this._Title != value))
                {
                    this._Title = value;
                }
            }
        }

        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_FileName", DbType = "NVarChar(350)")]
        public string FileName
        {
            get
            {
                return this._FileName;
            }
            set
            {
                if ((this._FileName != value))
                {
                    this._FileName = value;
                }
            }
        }

        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_URL", DbType = "NVarChar(350)")]
        public string URL
        {
            get
            {
                return this._URL;
            }
            set
            {
                if ((this._URL != value))
                {
                    this._URL = value;
                }
            }
        }

        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_CreatedBy", DbType = "NVarChar(101)")]
        public string CreatedBy
        {
            get
            {
                return this._CreatedBy;
            }
            set
            {
                if ((this._CreatedBy != value))
                {
                    this._CreatedBy = value;
                }
            }
        }

        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_UploadedDate", DbType = "NVarChar(30)")]
        public string UploadedDate
        {
            get
            {
                return this._UploadedDate;
            }
            set
            {
                if ((this._UploadedDate != value))
                {
                    this._UploadedDate = value;
                }
            }
        }

        [global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_FileSize", DbType = "NVarChar(33)")]
        public string FileSize
        {
            get
            {
                return this._FileSize;
            }
            set
            {
                if ((this._FileSize != value))
                {
                    this._FileSize = value;
                }
            }
        }
    }


Step 2: After you are done with creating the partial resulset for each resultset available in the stored procedure of multiple resultset, delete the stored procedure from the dbml which was helpful for creating the resultset class template. Since you are going to create the class template and the way to manipulate it manually you can always delete those copy of the stored procedure which was helpful to create resultset class template  rrom the dbml which otherwise will create a replicated copy which we dont need.


Step 3:  Copy and paste the copy of each singleresultset class template in SluiceDb.cs.


Step 4: Having known the template of each resultset available in the stored procedure you can create your own function to retrieving those multiple resultsets.


 [FunctionAttribute(Name = "dbo.Requirements_SelectByAssetSearch")]
        [ResultType(typeof(AssetsProject_SelectByAssetSearchResult))]
        [ResultType(typeof(AssetsRequirement_SelectByAssetSearchResult))]
        public IMultipleResults AssetsProjectRequirement(int projectId,int? requirementId, int? Id, string title,int owner)
        {
                IExecuteResult result = ExecuteMethodCall(this, ((MethodInfo)(MethodBase.GetCurrentMethod())), projectId, requirementId, Id, title, owner);
            if (result != null) return (IMultipleResults)(result.ReturnValue);
            return null;
        }



Step 5: Having we are done with manual invocation of Multiple resultset itz time to know how to invoke from the front end aspx page.


  using (SluiceDbDataContext sluiceDc = new SluiceDbDataContext())
                        {
                            IMultipleResults projectRequirement = sluiceDc.AssetsProjectRequirement(searchInfo.ProjectId, searchInfo.RequirementId, searchInfo.AssetId, searchInfo.Title, searchInfo.MemberId);

                            List projects =
                            projectRequirement.GetResult().ToList();

                            List requirements =
                            projectRequirement.GetResult().ToList();


                            rdgListAssetsProject.DataSource = projects;
                        }


For Refrence
http://beyondrelational.com/blogs/ibhadelia/archive/2010/07/17/how-to-get-multiple-result-set-of-procedure-using-linq-to-sql.aspx

For any queries you can very well email me...

Thursday, February 10, 2011

Connect your Facebook friends in your application

The Basics:

Facebook application can be developed using the following methods
1.       XFBML.
2.       Javascript with calls to the Javascript client library.
3.       Code in any language, with calls to the Facebook REST API.

I have implemented the facebook with the help of Facebook REST API for selecting the friends from your login and posting the invitation to the wall, the invitation is a url for getting connected to my achieve street site.
FYI: The XFBML is going to be expired in January and will be out of scope, so you think twice before getting it implemented.

Configuring Connect Application
Integrating/developing an application with Facebook requires an API key and a secret key with whom Facebook will authenticate your application on Facebook platform - this is called oauthentication.
FYI:   OAuth: The simplest definition can be OAuth protocol enables users to provide third-party access to their web resources without sharing their passwords

How to Retrieve the API Key and Secret Key
1.       Navigate to Facebook developer center and request for new application which can be obtained from your facebook login.
  1. Choose an appropriate application name (My application's name is AchieveStreet).
  2. Navigate to basic tab, there you can see API key/ secret key is given.
  3. Provide a small description about your application.
  4. Navigate to connect tab. Provide the applications full.
  5. Navigate to Advanced tab and on Advanced Settings, choose web.
  6. Choose sendbox mode enable/disable. Enable allows only the developers of application to see it.
  7. Save your settings.
The sample application for the facebook connect can be found in

How to make connection with the Facebook and Posting into the wall
API’s needed:
Facebook.Web.dll, Facebook.dll

How to establish the connection with Facebook
Api api = new Api(connectAuthentication.CurrentSession);

Posting to the wall
api.Stream.Publish(strbody, null, null, target user id, source user id);
the userid is the unsigned long int.

For posting into the wall you need to give permission for the login user to write the message into wall below is the code for that to do from the application

function setGrandPermission(isRead, isPublish) {

    try {
        FB_RequireFeatures(["Api"], function () {

            //Allow Permission for accessing the friends
            var api = FB.Facebook.apiClient;

            FB.Connect.requireSession(function () {
                var session = api.get_session();

                api.users_hasAppPermission("read_stream", function (hasRead) {
                    api.users_hasAppPermission("publish_stream", function (hasPublish) {

                        var permissions = [];


                        if (isRead)
                            if (!hasRead) permissions.push("read_stream");

                        if (isPublish)
                            if (!hasPublish) permissions.push("publish_stream");


                        if (permissions.length > 0) {                        
                            FB.Connect.showPermissionDialog(permissions.join(","), function (authorized) {                            
                            });
                        }
                    });
                });
            });
        });
    }
    catch (err) {throw err.Message;}
}


Using JQuery facebook Multi-Friend Selection Plugin using Javascript API, Graph API

I would like to thank Thiru and Kumuraguru for helping me to know this topic.

The Javascript API is used to get connected with the Facebook to do more things on Javascript API, to know more on this visit

The Graph API to retrieve the friends list, to know more about Graph API visit

To know more about the facebook api's feel free to email me.

Monday, February 7, 2011

Function to convert Html code to proper character.

Input   : it&#39;s where &#39; is a html code of '(oppostrope).
Output : it'z

ALTER FUNCTION [dbo].[HTMLDecode]
(@txt NVARCHAR(4000))
RETURNS NVARCHAR(4000)
AS
BEGIN
DECLARE @Start INT
DECLARE @HTMLCode NVARCHAR(5)
DECLARE @DecodeTxt NVARCHAR(4000)
SET @DecodeTxt = @txt
SET @Start = 32
WHILE @Start<=126
BEGIN
SET @HTMLCode = '&#' + CAST(@Start AS NVARCHAR(5))+';'
SELECT @DecodeTxt=REPLACE(@DecodeTxt,@HTMLCode,CAST(NCHAR(@Start) AS NVARCHAR(5)))
SET @Start = @Start + 1
END
RETURN @DecodeTxt
END

Note:
From 32  to 126 is the ascii character number so for each there is a equvilent character.
For each the character between 32 to 126 there is html value starting as &#32; to &#126; what we are doing is we are replacing this html value to the equivalent character.

For any questions you can mail me..







Thursday, February 3, 2011

Information about NUNIT

The NUNIT is a testing tool which is used to test your buisness logic.

1. Some of the buisness logic can be Insert, Update, IsProjectExists or IsRequirementExists.

2. The NUNIT contains the app.config for accessing the buissness and the test rules for testing the buisness logic.

3. Some of the tags which is used are

3.1 [TestFixtureSetUp] - To generate all the values needed for testing.

3.2 [SetUp] - Used to initialize the values.

3.4 [TearDown] - Every class should have a CleanUp which is empty.

3.5 [Test] - The function which is going to be tested should have this tag.

3.6 [TestFixtureTearDown] - Used to deallocate the resource.

Note: The items present in 3 is mandatory to run a test of NUNIT.

4. The NUNIT usually executes the function in the alphabetical order.

5. Assert - itz usually class used to test the values. some of them are AreEqual, AreNotEqual etc.

to know more about this you can email me..




Wednesday, February 2, 2011

Updating Sequence Records for each category using Join

Input:
Id ReqId ProjectId
1 NULL 1
2 NULL 1
3 NULL 2
4 NULL 2
5 NULL 2
6 NULL 3
7 NULL 3
8 NULL 3
9 NULL 3
10 NULL 4
11 NULL 4

Output
Id ReqId ProjectId
1 1 1
2 2 1
3 1 2
4 2 2
5 3 2
6 1 3
7 2 3
8 3 3
9 4 3
10 1 4
11 2 4

;
with cteSequence
as
(
select r.Id,ProjectId,r.DateCreated,row_number() over (partition by ProjectId order by r.DateCreated) as SequenceNo
from Projects p
inner join
Requirements r
ON
p.Id = r.ProjectId
)

UPDATE
Requirements
SET Requirements.RequirementId = s.SequenceNo
FROM
Requirements r
INNER JOIN
cteSequence s
ON r.Id = s.Id

Select ProjectID,ID,RequirementId from Requirements Order By ProjectID,RequirementId,Id