entity framework view not refreshing

November 23, 2015

https://christianarg.wordpress.com/2013/06/13/entityframework-refreshall-loaded-entities-from-database/

AsNoTracking

http://stackoverflow.com/questions/22177491/how-to-force-entity-framework-to-always-get-updated-data-from-the-database


Sqlserver : Saving changes is not permitted. The changes that you have made require the following tables to be dropped and re-created.

October 8, 2014

Saving changes is not permitted. The changes that you have made require the following tables to be dropped and re-created.
http://www.sql-server-performance.com/2009/saving-changes-not-permitted/
ERROR:

“Saving changes is not permitted. The changes that you have made require the following tables to be dropped and re-created. You have either made changes to a table that can’t be re-created or enabled the option Prevent saving changes that require the table to be re-created.”

This error happens because “Saving Changes is not permitted” when using SQL Server 2008 Management Studio to modify the structure of a table especially when SQL Server needs to drop and recreate a table to save the structural changes. It is always advised to make a structural change for a table using TSQL. However, it is a convenient option for database developers to use SQL Server Management Studio make such changes as the Prevent Saving Changes That Require Table Re-creation option is enabled by default in SQL Server 2008 Management Studio.

Disable “Prevent saving changes that require the table re-creation”

1. Open SQL Server 2008 Management Studio (SSMS). Click Tools menu and then click on Options… as shown in the snippet below.

2. In the navigation pane of the Options window, expand Designers node and select Table and Database Designers option as shown in the below snippet. Under Table Options you need to uncheck “Prevent saving changes that require the table re-creation” option and click OK to save changes.

This option when enabled prevents users from making structural changes to table using SQL Server Management Studio especially when SQL Server needs to recreate the table to save changes. By default, this option is checked and you need to uncheck this option to allow users to make any structural change through SSMS that require table recreation.


My Articles in different code sites

December 18, 2011

  http://www.c-sharpcorner.com/UploadFile/ambatisreedhar/MicrosoftGreatPlains03082009230301PM/MicrosoftGreatPlains.aspx

http://www.codeguru.com/csharp/.net/net_asp/miscellaneous/article.php/c15953/

My article on  “Creating Check All Uncheck All Grid view Web part with Paging, Sorting Functionalities in SharePoint 2007 in a Step by Step Manner ” was published in CodeProject.com site.

And the url is http://www.codeproject.com/KB/sharepoint/GridviewSharepoint.aspx

another article was published in CodeProject
 ”Creation of a SPGridview webpart having pagination, sorting , filtering functionalities in sharepoint site in step by step manner”. Link is http://www.codeproject.com/KB/sharepoint/SPGridviewWebpart.aspx

Codeproject article name is
Creating CheckAll UncheckAll Gridview webpart with Paging,Sorting functionalities in Sharepoint 2007 in step by
step manner
and the link is :
http://www.codeproject.com/KB/sharepoint/GridviewSharepoint.aspx

For evaluation I worked on 4 CMS ie Alfresco, DotNetNuke, Joomla, Drupal.
More pain in installation and configuring them.
I dont want others to repeat the same process of installation without concentrating on their core business.
I documented well.
 
On Alfresco my article was published
http://www.codeproject.com/KB/MCMS/Alfresco.aspx
 

 

Creation of a SPGridview Webpart having Pagination, Sorting, Filtering Functionalities in Sharepoint Site in Step by Step Manner   http://www.codeproject.com/KB/sharepoint/SPGridviewWebpart.aspx

Creating CheckAll UncheckAll Gridview Webpart with Paging, Sorting Functionalities in Sharepoint 2007 in a Step by Step Manner    http://www.codeproject.com/KB/sharepoint/GridviewSharepoint.aspx

Part 1: Installing Features and Adding Breadcrumbs to Custom Pages in Sharepoint Central Administrat

http://www.codeguru.com/csharp/.net/net_asp/miscellaneous/article.php/c15953__3/

 

 


SqlServer Lessons

December 4, 2011

INSERT INTO VALUES

The syntax for inserting data into a table one row at a time is as follows:

INSERT INTO “table_name” (“column1”, “column2”, …)
VALUES (“value1”, “value2”, …)

Assuming that we have a table that has the following structure,

Table Store_Information
Column Name Data Type
store_name char(50)
Sales float
Date datetime
and now we wish to insert one additional row into the table representing the sales data for Los Angeles on January 10, 1999. On that day, this store had $900 in sales. We will hence use the following SQL script:

INSERT INTO Store_Information (store_name, Sales, Date)
VALUES (‘Los Angeles’, 900, ‘Jan-10-1999′)
INSERT INTO SELECT

The second type of INSERT INTO allows us to insert multiple rows into a table. Unlike the previous example, where we insert a single row by specifying its values for all columns, we now use a SELECT statement to specify the data that we want to insert into the table. If you are thinking whether this means that you are using information from another table, you are correct. The syntax is as follows:

INSERT INTO “table1” (“column1”, “column2”, …)
SELECT “column3”, “column4”, …
FROM “table2”

Note that this is the simplest form. The entire statement can easily contain WHERE, GROUP BY, and HAVING clauses, as well as table joins and aliases.

So for example, if we wish to have a table, Store_Information, that collects the sales information for year 1998, and you already know that the source data resides in the Sales_Information table, we’ll type in:

INSERT INTO Store_Information (store_name, Sales, Date)
SELECT store_name, Sales, Date
FROM Sales_Information
WHERE Year(Date) = 1998

Here I have used the SQL Server syntax to extract the year information out of a date. Other relational databases will have different syntax. For example, in Oracle, you will use to_char(date,’yyyy’)=1998.

 ——————

SQL Server: INSERT INTO with SubQuery
October 11, 2008 by decoding

Introduction

This is a short tutorial on how to insert data with a subquery on SQL Server databases.
The reason I am writing about it is that the required syntax is not that obvious!

Sample tables and data

Let’s create two simple tables for this tutorial with the names ‘Customers’ and ‘Orders’.
view sourceprint?
1 CREATE TABLE [dbo].[Customers]( 

2     [id] [int] IDENTITY(1,1) NOT NULL, 

3     [name] [varchar](100) NOT NULL, 

4     [username] [varchar](20) NOT NULL

5 )
view sourceprint?
1 CREATE TABLE [dbo].[Orders]( 

2     [order_id] [int] IDENTITY(1,1) NOT NULL, 

3     [customer_id] [int] NOT NULL, 

4     [order_date] [datetime] NOT NULL

5 )

We are also going to insert a new row on table ‘Customers’:
view sourceprint?
1 INSERT INTO Customers 

2 VALUES (‘John Smith’,’john.smith’)

Inserting data with a subquery

The obvious syntax to insert data into the orders table with a subquery would be:
view sourceprint?
1 INSERT INTO Orders 

2 VALUES ((SELECT id FROM Customers WHERE username = ‘john.smith’), GETDATE())

However if you try the above query, you would end up with the following message:

Subqueries are not allowed in this context. Only scalar expressions are allowed.

The correct syntax to accomplish our task is:
view sourceprint?
1 INSERT INTO Orders 

2 SELECT id, GETDATE() FROM Customers 

3 WHERE username = ‘john.smith’

or if you would like to specify the columns:
view sourceprint?1 INSERT INTO Orders (customer_id, order_date) 

2 SELECT id, GETDATE() FROM Customers 

3 WHERE username = ‘john.smith’

————————————

Following three questions are many time asked on this blog.

How to insert data from one table to another table efficiently?
How to insert data from one table using where condition to anther table?
How can I stop using cursor to move data from one table to another table?

There are two different ways to implement inserting data from one table to another table. I strongly suggest to use either of the method over cursor. Performance of following two methods is far superior over cursor. I prefer to use Method 1 always as I works in all the case.

Method 1 : INSERT INTO SELECT
This method is used when table is already created in the database earlier and data is to be inserted into this table from another table. If columns listed in insert clause and select clause are same, they are are not required to list them. I always list them for readability and scalability purpose.
USE AdventureWorks
GO
—-Create TestTable
CREATE TABLE TestTable (FirstName VARCHAR(100), LastName VARCHAR(100))
—-INSERT INTO TestTable using SELECT
INSERT INTO TestTable (FirstName, LastName)
SELECT FirstName, LastName
FROM Person.Contact
WHERE EmailPromotion = 2
—-Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
—-Clean Up Database
DROP TABLE TestTable
GO

Method 2 : SELECT INTO
This method is used when table is not created earlier and needs to be created when data from one table is to be inserted into newly created table from another table. New table is created with same data types as selected columns.
USE AdventureWorks
GO
—-Create new table and insert into table using SELECT INSERT
SELECT FirstName, LastName
INTO TestTable
FROM Person.Contact
WHERE EmailPromotion = 2
—-Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
—-Clean Up Database
DROP TABLE TestTable
GO

Both of the above method works with database temporary tables (global, local). If you want to insert multiple rows using only one insert statement refer article SQL SERVER – Insert Multiple Records Using One Insert Statement – Use of UNION ALL.

Reference : Pinal Dave (http://blog.SQLAuthority.com)

———————————

sqlserver replace character in position :::::

Using REPLACE in an UPDATE statement

By Bill Graziano on 31 March 2010 | 12 Comments | Tags: UPDATE, Functions


This article covers using the REPLACE function to selectively replace text inside a string in SQL Server. The REPLACE function is easy to use and very handy with an UPDATE statment.

Replace searches for certain characters in a string and replaces them with other characters. So this statement:

 

SELECT Replace('SQLTeam.com Rocks!', 'Rocks', 'Rolls')

will return

SQLTeam.com Rolls!

REPLACE searches the the first string for any occurance of the the second string and replaces it with the third string. You can also do replacements of different sizes. For example,

 

SELECT Replace('SQLTeam.com Rocks!', 'Rocks', 'is cool')

gives us

SQLTeam.com is cool!

I replaced a five character string with a seven character string with no problem. If the string isn’t found, no changes will be made.

 

SELECT Replace('SQLTeam.com Rocks!', 'Yak', 'Tibetan bison')

returns exactly what we started with which is

SQLTeam.com Rocks!

If it doesn’t find anything to change it just returns the string unchanged. You can use REPLACE in an UPDATE statement. Using the pubs database we could write:

 

Update dbo.authors
Set    city = replace(city, 'Salt', 'Olympic');

There were two authors that had “Salt Lake City” in the CITY field. Now that field holds “Olympic Lake City” for those two authors. The CITY field is unchanged for all the other authors.

A more common approach is to use this in conjuntion with a WHERE clause like this:

 

UPDATE dbo.authors
SET    city = replace(city, 'Salt', 'Olympic')
WHERE  city LIKE 'Salt%';

This only affects the rows that start with ‘Salt’

—————————

  1. CREATE FUNCTION fnReplaceCharAtPos(@Str varchar(8000),@Pos int, @Chr char(1))
  2. RETURNS varchar(8000) AS  
  3. BEGIN 
  4. declare @Res varchar(8000)
  5. set @Res=left(@Str,@Pos-1) + @Chr  + right(@Str,len(@Str)-@Pos)
  6. return @Res
  7. END
  8.  

and call it in a query with

Expand|Select|Wrap|Line Numbers
  1. select dbo.fnReplaceCharAtPos(str,8,’Z’)
  2. from YourTable

—————————-

SQL Functions – STUFF() and REPLACE()

STUFF() can be used to stuff a string into another string. It inserts the string at a given position, and deletes the number of characters specified from the original string.

– © 2011 – Vishal (http://SqlAndMe.com)

DECLARE @string1 VARCHAR(20) = ‘Microsoft Server’

DECLARE @string2 VARCHAR(20) = ‘SQL Server 2005’

SELECT      @string1 + ‘ -> ‘ + STUFF(@string1, 11, 0, ‘SQL ‘)

            AS ‘String 1’,

            @string2 + ‘ -> ‘ + STUFF(@string2, 15, 1, ‘8 R2’)

            AS ‘String 2’

Result Set:

String 1                                 String 2

—————————————- ————————————-

Microsoft Server -> Microsoft SQL Server SQL Server 2005 -> SQL Server 2008 R2

(1 row(s) affected)

In the first string it inserts ‘SQL ‘ at specified position – 11, the third argument 0 indicated the number of characters to be deleted before inserting the new string.

For second string, we have deleted one (1) character starting from position 15, which deletes ‘5’, and then it inserts the new string at position 15 – ‘8 R2’.

REPLACE():

REPLACE() replaces all the specified characters with new characters.

DECLARE @string3 VARCHAR(35) = ‘sql 2005, sql 2008, sql 2008 r2′

SELECT @string3, REPLACE(@string3,’sql’,’SQL’)

Result Set:

———————————–      ———————————–

sql 2005, sql 2008, sql 2008 r2   SQL 2005, SQL 2008, SQL 2008 r2

(1 row(s) affected)

However, it is not limited to same number of characters:

DECLARE @string3 VARCHAR(35) = ‘2008 R2′

SELECT @string3, REPLACE(@string3,’20’,’SQL Server 2′)

Result Set:

————–       ————————

2008 R2              SQL Server 208 R2

(1 row(s) affected)

Hope This Helps! Cheers!

Reference : Vishal (http://SqlAndMe.com)

———————-

 

Create User defined function and how to call UDF
CREATE FUNCTION fx_SumTwoValues
( @Val1 int, @Val2 int )
RETURNS int
AS
BEGIN
  RETURN (@Val1+@Val2)
ENDThe structure of the CREATE FUNCTION statement is fairly straightforward. You provide an object name (fx_SumTwoValues), input parameters (@Val1 and @Val2), the type of data the function will return () and the statement(s) the function executes are located between the BEGIN…END block. The following SELECT statement calls the function. Note that the two-part name (owner.object_name) is required when calling this function.
SELECT dbo.fx_SumTwoValues(1,2) AS SumOfTwoValues

SumOfTwoValues
————–
3

 


C# 4.0-Dynamic Data Type, Difference between var and dynamic

November 21, 2011

C# 4.0-Dynamic Data Type, Difference between var and dynamic

 
http://www.facebook.com/plugins/like.php?href=http://www.dotnetjalps.com/2009/11/c-40-dynamic-data-type-difference.html&layout=standard&show_faces=false&width=90&action=like&font=arial&colorscheme=light inShare0
C# 4.0 introduces a new keyword called ‘Dynamic‘. It can consume any object anything. Let’s see some examples for that.dynamic intExample = 1;
Response.Write(intExample);dynamic floatExample = 2.5;
Response.Write(floatExample);

dynamic stringExample = “DotNetJaps”;
Response.Write(stringExample);

 

It will print out put on web page as following.

C#-4.0-Dynamic-Keyword-Diffrence-Between-Var-And-Dynamic-Type

Now, you will have question what’s new in that. It could be also done with var keyword . Yes, you can do same thing with var but dynamic keyword is slightly different then var keyword.

Diffrence between var and dynamic keyword:

var keyword will know the value assigned to it at compile time while dynamic keyword will resolve value assigned to it at run time. I know you guys don’t believe me without example. So let’s take example of string.

string s = “DotNetJaps-A Blog for asp.net,C#.net,VB.NET”;
var varstring=s;
Response.Write(varstring.MethodDoesnotExist());

 

Now try to compile above code it will not compile and it gives a error that ‘string’ does not contain a definition for ‘MethodDoesnotExist’ and no extension method ‘MethodDoesnotExist’ accepting a first argument of type ‘string’ could be found (are you missing a using directive or an assembly reference?’. So var keyword knows that what value or object or anything assigned to it. Now lets try to compile same code with dynamic example like following.string s = “DotNetJaps-A Blog for asp.net,C#.net,VB.NET”;
dynamic varstring=s;
Response.Write(varstring.MethodDoesnotExist());

 

This will compile. So it is the difference between dynamic and var keyword. With dynamic keyword anything assigned to it like property,objects operators anything that will be determined at compile time. It can be useful while we are doing programming with com,JavaScript which can have runtime properties.


Software Development Life Cycle Models

November 21, 2011

The General Model

Software life cycle models describe phases of the software cycle and
the order in which those phases are executed.  There are tons of
models, and many companies adopt their own, but all have very similar
patterns.  The general, basic model is shown below:
General Life Cycle ModelGeneralModel
Each phase produces deliverables required by the next phase in the
life cycle.  Requirements are translated into design.  Code
is produced during implementation that is driven by the design. 
Testing verifies the deliverable of the implementation phase against
requirements.

Requirements

Business requirements are gathered in this phase.  This phase
is the main focus of the project managers and stake holders. 
Meetings with managers, stake holders and users are held in order to
determine the requirements.  Who is going to use the system? 
How will they use the system?  What data should be input into the
system?  What data should be output by the system?  These are
general questions that get answered during a requirements gathering
phase.  This produces a nice big list of functionality that the
system should provide, which describes functions the system should
perform, business logic that processes data, what data is stored and
used by the system, and how the user interface should work.  The
overall result is the system as a whole and how it performs, not how it
is actually going to do it.

Design

The software system design is produced from the results of the
requirements phase.  Architects have the ball in their court
during this phase and this is the phase in which their focus
lies.  This is where the details on how the system will work is
produced.  Architecture, including hardware and software,
communication, software design (UML is produced here) are all part of
the deliverables of a design phase.

Implementation

Code is produced from the deliverables of the design phase during
implementation, and this is the longest phase of the software
development life cycle.  For a developer, this is the main focus
of the life cycle because this is where the code is produced. 
Implementation my overlap with both the design and testing
phases.  Many tools exists (CASE tools) to actually automate the
production of code using information gathered and produced during the
design phase.

Testing

During testing, the implementation is tested against the
requirements to make sure that the product is actually solving the
needs addressed and gathered during the requirements phase.  Unit
tests and system/acceptance tests are done during this phase. 
Unit tests act on a specific component of the system, while system
tests act on the system as a whole.

So in a nutshell, that is a very basic overview of the general
software development life cycle model.  Now lets delve into some
of the traditional and widely used variations.

 

Waterfall Model

This is the most common and classic of life cycle models, also
referred to as a linear-sequential life cycle model.  It is very
simple to understand and use.  In a waterfall model, each phase
must be completed in its entirety before the next phase can
begin.  At the end of each phase, a review takes place to
determine if the project is on the right path and whether or not to
continue or discard the project.  Unlike what I mentioned in the
general model, phases do not overlap in a waterfall model.
Waterfall Life Cycle ModelWaterFallModel
Advantages

  • Simple and easy to use.
  • Easy to manage due to the rigidity of the model – each phase has specific deliverables and a review process.
  • Phases are processed and completed one at a time.
  • Works well for smaller projects where requirements are very well understood.

Disadvantages

  • Adjusting scope during the life cycle can kill a project
  • No working software is produced until late during the life cycle.
  • High amounts of risk and uncertainty.
  • Poor model for complex and object-oriented projects.
  • Poor model for long and ongoing projects.
  • Poor model where requirements are at a moderate to high risk of changing.

 

V-Shaped Model

Just like the waterfall model, the V-Shaped life cycle is a
sequential path of execution of processes.  Each phase must be
completed before the next phase begins.  Testing is emphasized in
this model more so than the waterfall model though.  The testing
procedures are developed early in the life cycle before any coding is
done, during each of the phases preceding implementation.

Requirements begin the life cycle model just like the waterfall
model.  Before development is started, a system test plan is
created.  The test plan focuses on meeting the functionality
specified in the requirements gathering.

The high-level design phase focuses on system architecture and
design.  An integration test plan is created in this phase as well
in order to test the pieces of the software systems ability to work
together.

The low-level design phase is where the actual software components
are designed, and unit tests are created in this phase as well.

The implementation phase is, again, where all coding takes
place.  Once coding is complete, the path of execution continues
up the right side of the V where the test plans developed earlier are
now put to use.
V-Shaped Life Cycle ModelVShapedModel
Advantages

  • Simple and easy to use.
  • Each phase has specific deliverables.
  • Higher chance of success over the waterfall model due to the development of test plans early on during the life cycle.
  • Works well for small projects where requirements are easily understood.

Disadvantages

  • Very rigid, like the waterfall model.
  • Little flexibility and adjusting scope is difficult and expensive.
  • Software is developed during the implementation phase, so no early prototypes of the software are produced.
  • Model doesn’t provide a clear path for problems found during testing phases.

 

Incremental Model

The incremental model is an intuitive approach to the waterfall
model.  Multiple development cycles take place here, making the
life cycle a “multi-waterfall” cycle.  Cycles are divided up into
smaller, more easily managed iterations.  Each iteration passes
through the requirements, design, implementation and testing phases.

A working version of software is produced during the first
iteration, so you have working software early on during the software
life cycle.  Subsequent iterations build on the initial software
produced during the first iteration.
Incremental Life Cycle ModelSpiralModel
Advantages

  • Generates working software quickly and early during the software life cycle.
  • More flexible – less costly to change scope and requirements.
  • Easier to test and debug during a smaller iteration.
  • Easier to manage risk because risky pieces are identified and handled during its iteration.
  • Each iteration is an easily managed milestone.

Disadvantages

  • Each phase of an iteration is rigid and do not overlap each other.
  • Problems may arise pertaining to system architecture because not
    all requirements are gathered up front for the entire software life
    cycle.

 

Spiral Model

The spiral model is similar to the incremental model, with more
emphases placed on risk analysis.  The spiral model has four
phases: Planning, Risk Analysis, Engineering and Evaluation.  A
software project repeatedly passes through these phases in iterations
(called Spirals in this model).  The baseline spiral, starting in
the planning phase, requirements are gathered and risk is
assessed.  Each subsequent spirals builds on the baseline spiral.

Requirements are gathered during the planning phase.  In the
risk analysis phase, a process is undertaken to identify risk and
alternate solutions.  A prototype is produced at the end of the
risk analysis phase.

Software is produced in the engineering phase, along with testing at
the end of the phase.  The evaluation phase allows the customer to
evaluate the output of the project to date before the project continues
to the next spiral.

In the spiral model, the angular component represents progress, and the radius of the spiral represents cost.

 
Spiral Life Cycle Model
 

 

RUP

XP Programming

Agile Methodology


help notes

January 23, 2011

aMicrosoft JScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.

<body>
    <form id=”form1″ runat=”server”>
    <div>
   
    </div>
    <asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
    </asp:ScriptManager>
    <asp:UpdatePanel ID=”UpdatePanel1″ runat=”server”>
    <ContentTemplate>
    <asp:Label ID=”lbl” runat =”server”></asp:Label>
  <asp:Button ID=”Button1″ runat=”server” Text=”Button” OnClick =”Button1_Click”/>
   
    </ContentTemplate>
    </asp:UpdatePanel>
   
    </form>
</body>

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
      
Response.Write(“jaganath”)
 lbl.Text = “Jaganath”
    End Sub
Ans:you can not use Response.Write on your page when using AJAX.  I took it out (used a label instead) and it worked as expected.
————–

JQuery intellisense in vs 2008

http://weblogs.asp.net/scottgu/archive/2008/11/21/jquery-intellisense-in-vs-2008.aspx

Building Cascading DropDownList in ASP.Net Using jQuery and JSON
http://www.codedigest.com/Articles/jQuery/224_Building_Cascading_DropDownList_in_ASPNet_Using_jQuery_and_JSON.aspx

Creating a CascadingDropDown Using AJAX
http://aspalliance.com/1183_Creating_a_CascadingDropDown_Using_AJAX.3
———–

RenderControl method of Datagrid : Helps in exporting the grid data to excel.
But for dates,currencies, numbers it will automatically formats that data. The user has little or no control on that through code.
Say for eg: 123343423434 number converts into exponential number.

If the user doesnt deserves the formatting

either one has to preface the data with an apostrophe.

or select the column Format cells->General->Select the required one (Number ,Currency,Date) as per the requirement.

One cannot “set” Excel to stop thinking those are dates.

The work around is

For formatting the text use
mso-number-format:”\@”;

For formatting the currency use
mso-number-format:”022$022\#\,\#\#0\.00″;
Response.Cache.SetExpires(DateTime.Now.AddSeconds(1));
Response.ContentType = “application/vnd.ms-excel”;
Response.Charset = “”;
this.EnableViewState = false;
Response.Write(“<html xmlns:x=\”urn:schemas-microsoft-com:office:excel\”>”);
Response.Write(“\r\n”);
Response.Write(“<style>  .mystyle1 ” + “\r\n” + “{mso-style-parent:style0;mso-number-format:\””+@”\@”+”\“”+”;} ” + “\r\n” + “</style>”);
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
DataGrid1.RenderControl(hw);
Response.AppendHeader(“content-disposition”,”attachment;filename=x.xls”);
Response.Write(tw.ToString());
Response.End();

For example, to center and format ALL cells to text
following line should be added using response.write() at top of the page.

<style> td {mso-number-format:”\@”; text-align:center;} </style>

http://weblogs.asp.net/datagridgirl/archive/2003/04/14/5631.aspx
————————————–
Virtual directory not being configured as an application in IIS       
Written by Shabdar    
Monday, 24 November 2008 12:09 
Problem
Configuration ErrorDescription: An error occurred during the processing of a configurationfile required to service this request. Please review the specific errordetails below and modify your configuration file appropriately.Parser Error Message: It is an error to use a section registered as allowDefinition=’MachineToApplication’ beyond application level.  This error can be caused by a virtual directory not being configured as an application in IIS.Source Error:Line 53:Line 54:< authentication mode=”Windows” /> Line 55: Line 56:

Solution
Change authentication mode to ‘None’ in web.config.

Go to your web.config file and change following line
< authentication mode=”Windows” />to

< authentication mode=”None” />
This should solve this problem.

If above solution does not work then make sure that the directory from where you website is running is configured as an application in IIS. To do this, you need to go into IIS and find your project folder on the server, right click to Properties. Under Application Settings click Create. 
——————————–
TDMA and CDMA
What is TDMA and CDMA? why do we need them?
Over the years simultaneous cellular calls are increased over networks but no of accessible channels are limited. Hence there is a necessity of techniques which can solve this problem i.e increasing the number of simultaneous calls even though channels are limited. They expand the capacity of the radio channel.

There you got TDMA and CDMA. TDMA is a (Time division multiple access access)multiple access technology in which the channel is divided into sequential time slots.only a single user is using the channel at any given time. Here I would like introduce the term TDM(Time division multiplexing). Oh! then what is the difference between TDM and TDMA.
TDM is multiplexing technique and TDMA is multiple access technology. In TDM cetain time slot is dedicated forever for a given user even though he is not using it. ISDN is the example for this. In TDMA the time slot get freed up once the user finishes using the time. Here the time slots are dynamically allocated and the user may get different time slot each time accessing the network. GSM is an example for this. Of course GSM is not using ONLY TDMA.(FDMA as well clubbed with TDMA).
In TDMA the channel gets divided into 3 to 8 channels=8 simultaneous conversations.
Lets take an example for TDMA.
1) There are two stations and at each station 3 people. station1–A,B,C Station 2–D,E and F. Station1 and station 2 people want to exchange the messages.
2) The train with three carriages stops at station1 for some time.
3) All three people put the messages in three carriages.
4) The train goes to station 2 and the people there receives the messages from the carriages.
5) Again the train goes to station1 and the loop continues till the messages are completed.

Now coming to the CDMA(Code division multiple access) technology, It uses spread spectrum technology i.e a method in which a signal generated in a bandwidth is spread in the frequency domain resulting a signal with a wider bandwidth. In CDMA each caller will be given certain unique code so that others can not understand and allow multiple users use the same physical channel. The very common example for CDMA is In a room(considering as channel) several people want to communicate each other and each user will speak in different languages (Code divided) .
Now apply the same example to TDMA so that we understand the difference between these two. In TDMA all the people will take out certain time and speak one by one till every one finish their speech. In CDMA each user will speak in different languages. In FDMA each user will speak in different pitches.
Don’t confuse this CDMA (channel accessing method) with CDMA phones which is a mobile phone standard called cdmaone and CDMA2000(Reliance CDMA phones which are famous in India). GPS is the first application of this CDMA and qualcomm’s standard IS-95 published it as cdmaone and IS2000 as CDMA2000
———————–
find number of columns in a table in sql server
SELECT count(*) NoOfColumns FROM SYSCOLUMNS
WHERE id= (Select id from SYSOBJECTS where name = ‘TableName’)

—————-
In sqlserver 2008 if u want to modify the table structure in design mode it wont save and it will show an error message that file cannot be saved.

Solution:

Tools ->Options -> Designers
-> Table and Database Designers
-> Uncheck “Prevent saving changes that require table re-creation”

—————————————————————-

Ternary operator in VB.Net .There is no “?” like in c# in vb.net
If you are looking for ternary operator in VB.NET similar to C++,C#, Javascript etc if(expression?truepart:falsepart) then let me tell you that VB.NET offers a similar function to do that

you can write

Dim displayName As String = “FirstName”
Dim myName As String = IIf((displayName = “FirstName”), “Abhishek”, “Tiwari”)
Console.WriteLine(myName) ‘will write “Abhishek”
 myName = IIf((displayName = “SurName”), “Abhishek”, “Tiwari”)
Console.WriteLine(myName) ‘will write “Tiwari”
———————–
Refer

http://blog.lab49.com/archives/196
 Tips for reading Excel spreadsheets using ADO.NET
 Microsoft ADO.NET provides a handy, if quirky way to access Excel spreadsheets from Windows applications. The idea is to treat spreadsheets like databases, with each worksheet represented as a “table”. Worksheets are expected to be in a table-like format with column headings in the first row and rows of data beneath. For example, the following code reads worksheet “foo” from spreadsheet file C:\BAR.XLS into a DataTable:

problem : You have strings,integers,dates etc in an excel file. And if you are reading excel file using OLEDB then columns which are formatted may not be read and the output contains blank or null at their corresponding positions.
To resolve that : Use IMEX=1 in the JET provider.

One more issue : Unspecified error Excel:  (-2147467259)

Solution : its a security issue. the application account should be a administrator account.Means it should have full permissions.

My Computer->Manage(right click) -> Computer Management -> System Tools->Groups->
Add that user in administrator group
Imports System.Data.OleDb
Imports System.IO

Partial Public Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim myDataset As New DataSet()

        Dim strConn As String = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” & Server.MapPath(“cbofile.xls”) & “;” & _
         “Extended Properties=””Excel 8.0;IMEX=1;”””
        ”You must use the $ after the object you reference in the spreadsheet
        Dim myData As New OleDbDataAdapter(“SELECT * FROM [cbofile$]”, strConn)
        myData.TableMappings.Add(“Table”, “ExcelTest”)
        myData.Fill(myDataset)
     

        DataGrid1.DataSource = myDataset.Tables(0).DefaultView
        DataGrid1.DataBind()
     

    End Sub

End Class
If you want to process the data row by row rather than snarfing it into a DataTable, you can do it this way:
OleDbConnection dbConnection = new OleDbConnection (@”Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\BAR.XLS;Extended Properties=””Excel 8.0;HDR=Yes;”””);
dbConnection.Open ();
try
{
    OleDbCommand dbCommand = new OleDbCommand (“SELECT * FROM [foo$]”, dbConnection);
    OleDbDataReader dbReader = dbCommand.ExecuteReader ();

    // Say we are interested only in the columns “YearOfBirth” and “Country”:
    int yearOfBirthIndex = dbReader.GetOrdinal (“YearOfBirth”);
    int countryIndex = dbReader.GetOrdinal (“Country”);

    while (dbReader.Read ())
    {
 string yearOfBirth = dbReader.GetValue (yearOfBirthIndex).ToString ();
 string country = dbReader.GetValue (countryIndex).ToString ();

 // …
    }
}
finally
{
    dbConnection.Close ();
}But what if you don’t know the name of the sheet you want to read? As you can see from the examples, the ADO.NET interface requires you to name the worksheet – but in many cases you just want to read the first worksheet regardless of its name. It would be cool if ADO.NET provided a suitable notation like this:
// I WISH THIS WORKED
OleDbCommand dbCommand = new OleDbCommand (“SELECT * FROM [0#]”, dbConnection);… but it doesn’t. You must tell ADO.NET the specific name of the sheet you want to read. The solution is therefore to read the spreadsheet schema to find out the sheet names, thus reducing the second problem to the first one, like this:
OleDbConnection dbConnection = new OleDbConnection (@”Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\BAR.XLS;Extended Properties=””Excel 8.0;HDR=Yes;”””);
dbConnection.Open ();
try
{
    // Get the name of the first worksheet:
    DataTable dbSchema = dbConnection.GetOleDbSchemaTable (OleDbSchemaGuid.Tables, null);
    if (dbSchema == null || dbSchema.Rows.Count < 1)
    {
        throw new Exception (“Error: Could not determine the name of the first worksheet.”);
    }
    string firstSheetName = dbSchema.Rows [0] [“TABLE_NAME”].ToString ();

    // Now we have the table name; proceed as before:
    OleDbCommand dbCommand = new OleDbCommand (“SELECT * FROM [” + firstSheetName + “]”, dbConnection);
    OleDbDataReader dbReader = dbCommand.ExecuteReader ();

    // And so on…
}
finally
{
    dbConnection.Close ();
}The main quirk about the ADO.NET interface is how datatypes are handled. (You’ll notice I’ve been carefully avoiding the question of which datatypes are returned when reading the spreadsheet.) Are you ready for this? ADO.NET scans the first 8 rows of data, and based on that guesses the datatype for each column. Then it attempts to coerce all data from that column to that datatype, returning NULL whenever the coercion fails!
I suppose that makes a twisted kind of sense if you have spent a lot of time working with relational databases, but there are some unfortunate consequences of this design which aren’t obvious at first. For example, say your spreadsheet contains the following columns:
YearOfBirth    Country PostalCode
1964        USA 10005
1970        USA 10001
1952        Canada K2P1R6
1981        Canada L3R3R2
1974        USA 10013ADO.NET will correctly guess that the YearOfBirth column is numeric, and that the Country column is of type string. But what about the PostalCode column, which contains a mix of numbers and strings? In this case ADO.NET chooses the type based on the majority of the values (with a tie going to numeric). In this example 3 of the 5 postal codes are numeric, so ADO.NET will declare the column to be numeric. Therefore it will attempt to cast each cell to a number, which will fail for the Canadian postal codes – which will therefore come out as NULL values. Ha ha. Isn’t that fun?
Even more entertaining, there is absolutely no way to make this 100% reliable – although with some pain, you can improve the situation. Here’s what you need to do. First add the “IMEX=1″ option to your connection string like this:
OleDbConnection dbConnection = new OleDbConnection (@”Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\BAR.XLS;Extended Properties=””Excel 8.0;HDR=Yes;IMEX=1;”””);That tells ADO.NET to honor the following registry key when reading the spreadsheet:
Hkey_Local_Machine/Software/Microsoft/Jet/4.0/Engines/Excel/ImportMixedTypesThis registry key tells ADO.NET what to do when it encounters mixed types in the first 8 rows. It can either be set to the string “Majority Type” (for the default behavior) or to “Text” (which forces the column to be of type string). Note that you are still screwed if the first 8 postal codes are numeric and the 9th is Canadian. (Not to mention that the “Text” option invokes handling that fails on strings over 255 characters, but let’s skip that for now.)
There’s also a second relevant registry setting (which is honored regardless of the IMEX option):
Hkey_Local_Machine/Software/Microsoft/Jet/4.0/Engines/Excel/TypeGuessRowsThat says how many rows to scan to guess the datatype. The default is 8, but you can set it anywhere from 0-16 decimal (0 meaning “scan the first 16384 rows”, and all other values meaning what they say). Putting this all together, the most reliable way to read a US/Canadian postal code is to use the following registry settings:
TypeGuessRows = 0
ImportMixedTypes = TextThat’s pretty close to perfect, although it will still fail if the first 16384 postal codes are numeric and any of the subsequent ones aren’t.
This is a Bad Design for so many reasons I don’t know where to start. First, the behavior of the spreadsheet importer should not depend on global registry settings – that is just inviting mysterious, data-dependent errors whenever other applications or users change those settings. All of those settings should be in the connect string and nowhere else. Second, there should be an option to say “I’m not sure what data is coming, but I want all of it – please coerce everything to something universal like an arbitrary-length string”. Third, the interface should be stream-based, not file-based. If you are reading the spreadsheet data from the network, you shouldn’t have to save it to a temporary file in order to parse it. Fourth, you shouldn’t have to read the spreadsheet schema if you just want to select the worksheet by index (e.g. you want to read the first worksheet, whatever it happens to be called).

————————————————
ur log size is increasing. u want to delete the log file which is of 10 gb

How to close connections in sqlserver management studio

First right click on database ->tasks->Detach->select checkbox dropconnections.
Then it wil be removed from the left side of sqlserver
now u successfully closed the connections

now go to C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data   delete the [db_log] file
now u successfully delete  the unwanted log

Now u can attach the mdf file again by right click -> Attach to C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data mdf file.

———–