Tuesday, February 15, 2011

Oracle Connection with Visual Studio 2010

Pretty Simple Huh? not really.

here are the common tasks that you would like to do

(LINQ to SQL and entity framework not supported – Don’t even try it)

a. Connect the DB from VS to run some selects.

b. Create connection in code and get some data on web page.

There are 3 ways to go

1. Client side – System.data.OracleClient –> this is going away soon. so don not build you fortune apps on this. However, Visual studio uses this to connect. here is what you need (learned hard way)

  • Open VS, Data->Add new data source and select Dataset.
  • In add new connection dialog, you need to know the Host name of the Oracle server. (typically “HOST=” in your tnsnames.ora – on Oracle server)
  • you also need to know the SID which is nothing but the service ID. (typically “SERVICE_NAME=” in your tnsnames.ora – on Oracle server)

image

  • make sure that you enter servername/SID and use the test connection. – Success!

2. ODP.NET – oracle Data provider for .NET – a world in itself. More details and downloads here

http://www.oracle.com/technology/sample_code/tech/windows/odpnet/howto/connect/index.html

<- Note that this is the way to go. make sure that you do connection pooling to save money on performance consultant Smile

3. .NET data provider for Oracle – From .NET side. pretty much OLEDB stuff. Didn’t go good on performance front for Obvious reasons, last choice for me.

Thursday, September 30, 2010

Grid View – Ilist & Dataset

we all know that with c# 3.5 & now 4, we have generics and LINQ – which makes it incredibly easy to Bind grid View to ilist that you get from a LINQ query when you use the entity data model.

However, After binding this data to Grid, you want to use the template columns to update the individual rows, also you want to save the data on post backs. I found that Ilist is not the best way to go (very much depends upon situation). Here the old friend – Dataset comes to rescue.

You can bind the dataset, Cache it and update the columns after every update. [ Think about this only for Selects] as you loose entity connections when you go the dataset way (There are ways to keep this dataset and entity in Sync but i will not talk about it now)

 

So, here is a small extension function to Ilist

[Uses Reflection ]

 

public static DataSet GetDataSet<T>( IList<T> list)
    {
        Type elementType = typeof(T);
        DataSet ds = new DataSet();
        DataTable t = new DataTable();
        ds.Tables.Add(t);

        //add a column to table for each public property on T
        foreach (var propInfo in elementType.GetProperties())
        {
            Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;

            t.Columns.Add(propInfo.Name, ColType);
        }

        //go through each property on T and add each value to the table
        foreach (T item in list)
        {
            DataRow row = t.NewRow();

            foreach (var propInfo in elementType.GetProperties())
            {
                row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
            }

            t.Rows.Add(row);
        }

        return ds;
    }

Tuesday, July 20, 2010

REST and SOAP

As we all know that this is more of a Architectural decision, there are few things that I would like to keep handy while deciding among two. These should help me taking the right design decision for right type of end point.

Here I am trying to Simplify the WCF stuff. There are 2 Major type of services and clients that you would need to know for majority of the Services consumers.

- For using WS* and all the high end transactional features of WCF, USE SOAP

Easy to consume – sometimes
Rigid – type checking, adheres to a contract

- For light weight, simple XML, if you can take care of security user REST

Lightweight – not a lot of extra xml markup
Human Readable Results

Examples -

REST - Twitter, Yahoo’s web services , Flickr, del.icio.us, pubsub, bloglines, technorati best is? – Craigslist !

SOAP - Google is consistent in implementing their web services using SOAP, with the exception of Blogger, which uses XML-RPC.

Both? -  eBay and Amazon

Now REST vs SOAP - 

1 API Flexibility & Simplicity – Rest is simple and SOAP is not

2. Rest APIs are lightweight – less bandwidth – SOAP requires Bunch of XML wrapped around where as for 4 digit stock price we dont need this overhead :)

3. Security- Posts using SOAP across organizational boundaries are safe, However RESTs Get are can always be consider safe because technically it can not modify an data. SOAP typically uses the POST to communicate with service. analyzing HTTP command in firewall is simple and REST can benefit out of it. However, to do this with SOAP you have to open the SOAP packet which makes it resource consuming. There is no way to know just by looking at the request if it wants to get or delete etc.

On the other hand, think about sending SSN as parameter in Query string. there rest goes down. Again Large data  becomes difficult

4. Authentication and Authorization – For SOAP its all upto developer. For REST – through use of certificates, common identity mgmt services like LDAP developers can make use of this

Clients – easier to create a Client for SOAPs that REST but this depends on how the framework is. Testing and troubleshooting is very easy with HTTP API than SOAP as building request is far simpler.

Caching – easer with REST as it is consumed with GET, intermediate proxies can cache the responses easily. 

Server Side complexity – SOAP is easier to code on server side, nearly all high level langs and framework makes it easy to create a  SOAP endpoints. With REST you are exposing objects methods as HTTP API and requires serialization of output to XML. Also you need to map the URI path to specific handlers.

Wednesday, June 30, 2010

Async Calls in C# – Should I blog about this?

Well, this may be for me to keep track but thought it would be usefull as I see more more and junior developer who do not understand the importance of Async programming and make blocking calls and it is frustrating especially in Web or Online apps.

There are too many frameworks available that you can take advantage of today. Another great video here I just wanted to give a very very simple steps to get this whole asynchronous business going. I assume that you know all the delegate concepts. Even if you dont know, dont worry, you really dont need to.

------------------------------------------------------------------------------------------------------

Scenario 1- Simplest of all. You want to call a function without blocking the main thread and dont care about return value dont want to know when called function finishes execution

a. Create a delegate –

 public delegate string  GetName (string myname);     –> note that you generally know what function to call and so you can decide on the delegate signature.

b. Then create object of delegate

GetName nameGetter = new GetName(GetMyRealName); <— GetMyRealName  is the actual function we want to call in Async manner.

c. Then Simply do

IAsyncResult result = nameGetter.BeginInvoke(name,null,null); <- Param 1 is parameter to original function, first null is Callback (explained latter) and last is object state (explained later)

A method GetMyRealName will be called without blocking your main thread. This is as simple as that.

*note that if your called function throws exception it will not come up

------------------------------------------------------------------------------------------------------

Scenario 2-  You want to call a function without blocking the main thread, At the same time do something else and then see what is the result of your async function

------------------------------------------------------------------------------------------------------

Scenario 3-  You want to call a function without blocking the main thread, then have another function called when your called function finishes execution

Tuesday, June 22, 2010

Showing HTML as is in Text box for ASP.NET 4.0

1. Simple thing but may get very annoying sometimes :)

2. you stored an HTML in DB. you want to show it as in Text box.

3. Note – Label and literal controls will show them as they encode by default. However Text box will not.

4. Fix – use HTML encode for the text box

ASP.NET Validate Request with .NET 4.0 – some breaking news

From old days -

1.  if you want to store HTML in DB – may be script you encode and store.

2. While post back you will get “potentially dangerous Request.Form value was detected” – To fix this you go ahead and make validateRequest=false on your page.

3. With .NET 4.0 this will not work Because this is now in the BeginRequest phase of a HTTP request, pages with validationRequest=”false”  will still get the dreaded message

Fix?

Set requestValidationMode=”2.0″ in which case the page setting will apply.

Put <httpRuntime requestValidationMode=”2.0″ /> in your web.config’s <syste.web> section

good article can be found here

Wednesday, June 16, 2010

SQL Server 2010 Express SP1 full install OR SQL Server 2010 Managements studio Express install After VS 2010

 

Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

Hello all,

I had this nasty thing that came in my way when trying out SP1 for SQK 2k8 after VS 2010 install in Win 2k8 or Win7

Here are the steps

1. Start the install.

2. Let the UAC prompt come up and then say yes.

3. Install will start. Keep clicking next ok etc..the goal is to get to the Error dialog box

4. Once you get the error dialog, stop and do not click “OK”.  Instead go to c:"{GUID} and then copy the folder to some location. If you click ok the temp folder will be cleaned up

SQL Setup

5. Run the setup from this folder. For Win2k8, “Run as Administrator”

6. There are some more solutions given here but this worked for me 99% of the time

Thursday, January 07, 2010

Case sensitive "=" or like clause in SQL Query analyzer

In your query in query analyzer - Put this next to the case sensitive word that you querying


COLLATE SQL_Latin1_General_CP1_CS_AS


For Ex  - 

select * from EntryMain where customer = 'XXXxxxxXXXX' COLLATE SQL_Latin1_General_CP1_CS_AS



Here XXXxxxxXXXX is case sensitive.


You can also set the Collation to default using system store procs permanently.

Wednesday, November 18, 2009

IIS Web Core Notification - BeginRequest Handler Not yet determined Error Code 0x800700b7 Config Error Cannot add duplicate collection entry of type 'add' with unique key attribute 'name' set to 'ScriptHandlerFactory'

 

Situation

1. Visual studio 2008 SP1

2. IIS 7

3. Hosting WCF within site with a VDir.

This happens typically when you are hosting with hosting provider.

If you create a website in main folder (Which will be by default ) and you host a ASP.NET web site. Doesn't matter if it is AJAX or simple website. With SP1, we have 'ScriptHandlerFactory' with any web application.The site works perfectly.

 

Now if you are creating a service say a WCF service under a Vdir in this site, you will have a different Web.config for your service. Service will run fine locally. When hosted, The website will inherits the settings form parent level . This should be the reason of this issue. You can check if there is a web.fig file in the parent web content folder and an duplicate collection entry in it.

Typically a duplicate entry from services config needs to be removed.

Monday, September 07, 2009

Google App Engine – Can it replace Microsoft share Point?

It was fun reading the article at http://googleappengine.blogspot.com/2009/09/app-engine-sdk-125-released-for-python.html

Google app engine is now supported over windows as well. here are my observations -

1. Go to world with your web application within minuets. Could not find any Microsoft product / service in competition to this. 

2. Use Goggle’s Infrastructure to host, bandwidth and CPU time upto 5 million users per months for FREE!!!

3. Pay as you use after that.

4. Extensive integration with Eclipse and one click deployments.

5. Super cool UI with Google analytics and dashboard and I was feeling like I am in datacenter with my laptop.

6. Here is the Kicker – User JDO (Java data objects) and Google Authentication to use authenticate your users.

7. URL mapping off-course. Users wont even know that your www.xyz.com is hosted on Google servers.

I was thinking if any one can use the templated Servlet to create a team site like in sharepoint, then there is no licensing, now no more deployments and developmet and UI? is just like you any web development. On top of that you can convert the old apps as Google app engine app and host it on Google.

Is this a Google’s answer to sharepoint and Microsoft Cloud computing?

Tuesday, September 01, 2009

New Trend in Application development for IT organizations.

Just wanted to put a quick note on a great article that I came across here.

This is a poll conducted by Gilbane Group on Facebook for finding out the future of collaboration technology in near future.

This un-official  poll was for 1000 users and for different age group 18-24 and 25- 34

here are the results - gilbane_facebook_poll_6_19_07

Here is what I think -

1. People want to take the collaboration technology in their everyday business. More younger people would do this more Look at the SMS text Mode.

2. Social networking and Blogs are not very Popular – Will today’s Tons of Startups in social networking survive?

3. Future information worker will try to use new modes of IT not only as communication medium but in their everyday life and at work .

4. IT organizations should recognize this trend and seek to provide solutions with the flexibility to meet the technology demands of information workers.

Silverlight3 GridView Binding, LoadingRow events and Textblock traps

Those from ASP.NET background, moving forward to silverlight3 and playing around with Grid view my get frustrated at times. Grid view is one of the most widely used controls and we do want to change the contents of the Grid when we Bind the data. Sounds very simple but could be tricky at times.

I was developing prototype in Silverlight and Found few interesting things and thought I would share.

  1. So you bind the data to a grid, using AutoGenerate columns or not, Doesnt matter. To track the "GridView.RowDataBound" on row data bound event you create a backend event handler like this.
    grdEntries.LoadingRow += new EventHandler(grdEntries_LoadingRow);
  2. Getting event handler is tricky, here is how you get it working.  Note the 3 methods of getting the cell content in C# code. image

About this get parent function – this casts the cell to appropriate type – Note the way this function is called recursively.

The Above code may not work when you scroll the grid, for some wired reason it keeps binding the data again and again. For this, Alternative solution could be to use the individual column loaded even. Here is how you do it.

Both type of columns are shown here

<!--<data:DataGridTextColumn Binding="{Binding Date}" Header="Entry Date" Width="175"/>--> regular column which works with LoadingRow event handler

<data:DataGridTemplateColumn Header="Date" SortMemberPath="Date">
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Loaded="TextBlock_Loaded" x:Name="txtDate" Text="{Binding Date}">
</TextBlock>
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>

In the code behind, track the column and change the text or whatever you want to do.

void TextBlock_Loaded(object sender, EventArgs e)

     {

          TextBlock tb = sender as TextBlock;

          tb.Text = "Amol";

      }


Now why we have so many options? There are some performance reasons in data grid and it all depends which one to use whe. Typically, if you want to change data every time you bind grid, go with Loading row handler. If it static change and grid is not going to change then use the column loaded event.

Thanks

Friday, August 28, 2009

Passing Parameters to Silverlight 3 Application from ASP.NET

Steve has excellent article here

However, For starters, I thought I would put down the steps quickly here

1. biggest change and where I struggled, How to create a parameter in ASP.NET page, the control is gone. Well, is here to help us. In the Object Tag, add line  -



2. in Code behind in ASPX, use this control to set the property on any event. 2 things to remember here, Use the ".Text" to set the key value pair like this.
Source.Text ="Param1="+ Param1.ToString();

3. In App.xaml.cs, in Application_Startup event, simply add  2 lines, and your total code should look like
this.RootVisual = new MainPage();
foreach (var data in e.InitParams)
   this.Resources.Add(data.Key, data.Value);

4. In MainPage.xaml.cs you want to access this, Simply use following construct.
App.Current.Resources["Param1"].ToString();
Note - Create a Loaded even in MainPage.xaml otherwise we will get. Final code should look like


public MainPage()

{    InitializeComponent();
    this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}


void MainPage_Loaded(object sender, RoutedEventArgs e)
{     string param 1 = App.Current.Resources["Param1"].ToString();
}

Tuesday, March 10, 2009

The 'Microsoft.Jet.OLEDB.12.0' provider is not registered on the local machine !!

This is rather simple error to Fix if you are a developer and building small scale application.

Error comes becase you dont have Office 2007 installed on machine. Most of developers install it and goet going :)

Few other they go for http://www.microsoft.com/downloads/details.aspx?familyid=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en - Better way,

PROBLEM -

1. Lets say you are hosting your web site on shared host server. Hosting company may not install this Driver!!!!!

2. Another bigger problem, if your application is load balanced, how do you or hosting company know where to install this driver? On all nodes?

There is a intersesting solution to this problem, Cant share here. Hope microsoft will address this with MDAC and OS install :)

Saturday, October 18, 2008

SQL Server 2008 Alter Table - Saving Changes Not Permitted ???

Do you get this error and freak out?






























Saving changes is not permitted. The changes 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.




LETS NOT GET INTO WHY IT IS LIKE THIS :)




Do this instead




Go to tools - Options and do as pointed out. - Thanks























Monday, October 13, 2008

T-SQL - If the Day is week day OR week end

Many Application needs this so trying to post this.

( I am not the author of this bu thought to help all by posting it here)

create function fn_IsWeekDay
(
@date datetime
)
returns bit
as
begin
declare @dtfirst int
declare @dtweek int
declare @iswkday bit
set @dtfirst = @@datefirst - 1
set @dtweek = datepart(weekday, @date) - 1
if (@dtfirst + @dtweek) % 7 not in (5, 6)
set @iswkday = 1 --business day
else
set @iswkday = 0 --weekend
return @iswkday
end


Short and sweet.

Now you can simply do this: (USAGE)


if dbo.fn_IsWeekDay(@date) = 1
begin
--do some magic here ;-)
end
--or
select a.SomeFieldsForCalculation from table a where dbo.fn_IsWeekDay(a.SomeDateField) = 1



and all is good.

Thursday, September 25, 2008

Simple Memory Management Stuff.


I belive that Once the code is written it lives for ever. Write it best for the first time. No One lakies to refactor it.
consider yourself fortunate if you are getting opportunity to wrte the code from scratch ang follow these simple things.
More to come

Monday, September 22, 2008

UNICEF - Be a member. It really helps

Hello,

Here I am to request who ever read this post. We all know that there are some among us that cant even think of looking at computer. I really feel bad about those who are disabled and its not their fault.

I have joined UNICEF. Its my urge to you all to join.

It doesn't take that much from your life an pocket.

http://www.unicef.org/

thanks

Thursday, September 18, 2008

How can I maintain the format of text in a multiline textbox when saving to sql server ie new lines paragraphs etc in ASP.NET

Very common scenario - Here are my Thoughts

1. If you are using multiline text box (built in asp.net) - You can only save the New lines.

here is a quick c# code.

string FinalString = MultilineTextBox.Text.Replace("\r\n","");

and then save it in regular fashion in SQL server. Make sure to turn off the page validation request. i.e. ValidateRequest="false" at page level.

-------------------------------------------------------------------------------

2. Very Elgant, Less time consuming, and FREE way to do it.

a. Go to Free Text Box and download.
b. Put the DLL in Bin of your website.
c. Add a tag in your page.

<FTB:FreeTextBox id="txtDesc"
ToolbarLayout="ParagraphMenu, FontFacesMenu, FontSizesMenu, FontForeColorsMenu,
FontForeColorPicker, FontBackColorsMenu, FontBackColorPicker, Bold, Italic, runat="Server" Width="800px"/
>


d. This is server side control and directly give you HTML when you acesses the Text property in code behind. Save it in the SQL server as nvarchar and you are good to go.

thanks.

(Leave a comment if this helped you)