Monday, April 7, 2014

Download file using javascript/Jquery

On aspx page add this:

<iframe id="hiddenDownloaderForPdf" style="display:none" ></iframe>


on Javascript file:

function downloadFile (url) {
        var hiddenDownloaderForPdf= 'hiddenDownloaderForPdf'
        iframe = document.getElementById(hiddenDownloaderForPdf);
//if iframe isnt available create one dynamiclly
    if (iframe === null) {
        iframe = document.createElement('iframe');
        iframe.id = hiddenDownloaderForPdf;
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
    }
    iframe.src = url;
}

using jQuery:
function downloadFile (url) {
        var hiddenIFrameID = 'hiddenDownloaderForPdf'

       $('#'+ iframe).attr('src' ,url);
  }

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


Way to rename table without changing references of Table


Some time problems are not that easy to resolve because we got stuck in our think box. But how can we think out of box if we sit in a cube( jokes apart).
Today we are faced an issue where we have to rename table name and add new column in it so that we can differentiate existing data with new added records. But it wasn't possible because this table is used as first table in joins.

for example :

tblX
id name description

tblB
Bid Xid Values


select * from tblX a
inner join tblB  b on a.id=b.Aid 
and i am doing this kind of thing hundred of places in my SPs.

Now my requirement is something like that

Rename table to tblX to tblXYZ and add new column CategoryType.
Update all records with CategoryType 'X'

tblXYZ
id name description category

 so for making existing code work i may need to change above queries like that:

select * from tblXYZ a
inner join tblB  b on a.id=b.Aid 
where a.CategoryType='X'

but this isnt possible for me so what i can do?????

Solution:

instead of changing queries in SP what we can do we can create  a new VIEW
with same name tblX and define it as :

select * from tblXYZ
where CategoryType='Y'


by using this VIEW we doesn't require to change SP's .

This is the best approach in fount till now ,, if there will anything new i'll let you know.


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










Monday, July 22, 2013

Is Reflection breaks Encapsulation

"Today, I learn a big lesion  that what ever we know isnt surely only truth. We may know what is true but there may be other true that are different from what we know. And sometime no one tells us that what is truth either because they dont know them selves or we might be not a level to understand that."

Whatever i write down above is just what i felt about knowing that we can call or access private members of class regardless of that can break the concept of encapsulation.

So as i told you reflection can used to access private members.Let assume we have a class Cat.
For eg.

 public class Cat
    {

        private int NoOfLegs = 4;
    }

now we will use to reset the value of NoOfLegs using reflection.

   Cat c = new Cat();
            Type  t= typeof(Cat);

            t.GetField("NoOfLegs", BindingFlags.Instance | BindingFlags.NonPublic)
         .SetValue(c,567);
            Console.Write(t.GetField("NoOfLegs", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(c));
            Console.ReadLine();

So myth creaked  that reflection cant access private members.

"So If some is saying that private members aren't accessible by outside you can prove him/her wrong".

As explained above encapsulation is a design technique to make design clean and structured. If some wants to take full responsibility by changing private members he is on risk of getting exception.
For eg someone can set value to null using reflection so our job as developer is to make sure we are handling null and throwing exception. As we cannt trust on other developers or user of providing expected inputs.
This solution is provided because we may need to test private member of our class.

Dynamic:

Somehow Dynamic datatype is popular as alternative of reflection but it isnt. Dynamic datatype allows as to check property and fields are runtime. Some rules remain unbreakable like object of a class can access only public members of class.
So if someone is thinking to do something similar we did with reflection then he must be ready to get unhandled exception like RuntimeBinderException With msg"'RefdynEncApp.Cat.NoOfLegs' is inaccessible due to its protection level ".


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





Friday, July 19, 2013

Create date using two dates

Here is the logic to create a date using two dates:

For eg:

We have 2 dates Tdate1 and Tdate2. And we want to create a new datetime using these 2 dates, in which we will take date part from Tdate1 and time part from Tdate2. So we can do this using  below query:

 Convert(datetime, CONVERT(VARCHAR(500), Tdate1, 110)
                                + ' '
                                + CONVERT(VARCHAR(50), Tdate2, 108) )

Compare dates :
if we have to check interval(day,month,year,min,hour) between 2 dates than we can use logic defined below:

MONTH:

Tdate1: 7 June 2013 00:00:00
Tdate2: 5 July 2013 00:00:00

select 'Difference',DATEDIFF(month, convert(datetime, Tdate1,Tdate2)
Result:  Difference,1

 MONTH:(-ve)
Tdate1: 7 June 2013 00:00:00
Tdate2: 5 May 2013 00:00:00

select 'Difference',DATEDIFF(month, convert(datetime, Tdate1,Tdate2)
Result:  Difference,-1

 YEAR:

Tdate1: 7 June 2013 00:00:00
Tdate2: 5 July 2013 00:00:00

select 'Difference',DATEDIFF(Year, convert(datetime, Tdate1,Tdate2)
Result:  Difference,0

 HOUR:
Tdate1: 7 June 2013 00:00:00
Tdate2: 7 June 2013 05:06:07

select 'Difference',DATEDIFF(Hour, convert(datetime, Tdate1,Tdate2)
Result:  Difference,5

 MINUTE:
Tdate1: 7 June 2013 00:00:00
Tdate2: 7 June 2013 05:06:07

select 'Difference',DATEDIFF(Minute, convert(datetime, Tdate1,Tdate2)
Result:  Difference,6

 SECOND:
Tdate1: 7 June 2013 00:00:00
Tdate2: 7 June 2013 05:06:07

select 'Difference',DATEDIFF(Second, convert(datetime, Tdate1,Tdate2)
Result:  Difference,7

Let me know if i am missing anything or we have to make any change in this Post.

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


Tuesday, July 16, 2013

Scripts for Self updated Table using multiple Join

Here we have described how to update a table using multiple joins on table

1. Create a Table Variable:

Declare @tblR as Table
(
    RID int,
    SID uniqueidentifier,
    BID uniqueidentifier
)

2. Insert demo data into New Created Table Variable





insert into @tblR values (1, null, null)
insert into @tblR values (2, null, null)
insert into @tblR values (3, null, null)
insert into @tblR values (4, null, null)
insert into @tblR values (5, null, null)
insert into @tblR values (1, null, null)
insert into @tblR values (2, null, null)
insert into @tblR values (6, null, null)
insert into @tblR values (7, null, null)
insert into @tblR values (8, null, null)

3.  Update Table using alias name and Using multiple INNER JOIN





update t set t.BID = b.BID, t.ID = s.ID
from @tblR t
inner join R r on r.ID = t.RID
inner join B b on b.BID = r.BID
inner join S s on s.SID = b.SID

4. Select data from table Variable to check updated data






select * from @tblR

This is just an example for a simple update using inner join.

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




Wednesday, July 3, 2013

Get Id of latest inserted Record in Table

Dear Reader,

One of issue we always worried about was how to get id of latest inserted record.
1. One option was to perform select on that table after inserting latest record.
2. Use or ScopeIdentity
3. Get Inserted id using OUTPUT INSERTED

assuming we have a table tblDemoTable (IDField, Field1,Field2,Field3)
Details on different ways to get ids

1.
 After insert new record we can get if it integer identifier by fetching maximum id values

Declare  @InsertedId int
select top 1 @InsertedId  =Max(IDField)
from tblDemoTable

Note: It doesnt work for Uniqueidentifier column.

And we can also select values based on any date sorting or something if we have any identifier to sort it and take latest record.

2. SCOPE_IDENTITY(),@@IDENTITY :

 SCOPE_IDENTITY() will provide us the last identity value created in a particular session, but it will also limit it to your current scope as well.
 Link for better understanding-1


3. OUTPUT INSERTED :

This is very useful to get list of Id's inserted in current session inside a loop or in batch.
Limitation: It will work in current session only.

Declare @InsertedID as table
                            (
                                Id int
                            )
                            Declare @ID int
                            Insert into tblDemoTable( Field1,Field2,Field3)
                                                        OUTPUT INSERTED.[IDField] INTO @InsertedID
                                                        Values
                                                        ( @Field1,@Field2,@Field3)

Thank you Rohit Rao for providing solution to me.


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

Monday, May 20, 2013

Way to search string in all tables in database

 

Some time we get requirement to find a particulare sting across tables in a data base.
One of my friend was cought in same situation this the first solution we found on net


Search string in all tables-Ist Solution

but not tried yet we'll continue work on this and let you know once we get something new.
Here is a way to search string in all tables in database this is one of the solution tried by my friend Rohit Rao and it is working solution all credit goes to him.


DECLARE @SearchStr NVARCHAR(100)

SET @SearchStr = 'search string here'

CREATE TABLE #results
  (
     columnname  NVARCHAR(370),
     columnvalue NVARCHAR(3630)
  )

SET nocount ON

DECLARE @TableName  NVARCHAR(256),
        @ColumnName NVARCHAR(128),
        @SearchStr2 NVARCHAR(110)

SET @TableName = ''
SET @SearchStr2 = Quotename('%' + @SearchStr + '%', '''')

WHILE @TableName IS NOT NULL
  BEGIN
      SET @ColumnName = ''
      SET @TableName = (SELECT Min(Quotename(table_schema) + '.'
                                   + Quotename(table_name))
                        FROM   information_schema.tables
                        WHERE  table_type = 'BASE TABLE'
                               AND Quotename(table_schema) + '.'
                                   + Quotename(table_name) > @TableName
                               AND Objectproperty(Object_id(Quotename(table_schema) + '.'
                                                            + Quotename(table_name)), 'IsMSShipped') = 0)

      WHILE ( @TableName IS NOT NULL )
            AND ( @ColumnName IS NOT NULL )
        BEGIN
            SET @ColumnName = (SELECT Min(Quotename(column_name))
                               FROM   information_schema.columns
                               WHERE  table_schema = Parsename(@TableName, 2)
                                      AND table_name = Parsename(@TableName, 1)
                                      AND data_type IN ( 'char', 'varchar', 'nchar', 'nvarchar',
                                                         'int', 'decimal' )
                                      AND Quotename(column_name) > @ColumnName)

            IF @ColumnName IS NOT NULL
              BEGIN
                  INSERT INTO #results
                  EXEC ( 'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) FROM ' + @TableName + ' (NOLOCK) ' + ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2 )
              END
        END
  END

SELECT columnname,
       columnvalue
FROM   #results

DROP TABLE #results  



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