Periodically update webpage with server data - Simulate pushing data from server to client

by Admin 2. February 2010 04:23

JavaScript has a function, setInterval(code, timeout) that can be used to periodically update a visitors web browser. Using this feature you could simulate pushing updates from the server side to the clients browser using AJAX.

The setInterval(<code>, <timeout>) function call takes 2 parameters. <code> which is the javascript call to run and <timeout> is the interval at which to periodically make that call. The call specified as the <code> parameter can be an AJAX call to fetch the data and update the browser part.

function pageLoad(sender, args) { 
   setInterval('UpdatePage();', 2000); 
}

For example, the above  javascript function can be set to run on page load, which in turn will call the UpdatePage() Javascript call every 20 seconds.

for a complete example, take a look at the 4 guys site @ http://aspnet.4guysfromrolla.com/articles/012109-1.aspx

Tags: , , ,

.NET | Ajax | ASP.Net | JavaScript

Call a webservice from TSQL (Stored Procedure) using MSXML

by Admin 22. December 2009 10:13

I am working on a n integration project that required me to call a webservice through a stored procedure in the SQL database. After proving my concept using the CLR integration features in Sql Server, I learned that the production database was actually running on Sql Server 2000 compatibility level. There went my proof of concept.

 

So now I have to resort to doing web service calls the old way, making post requests using MSXML. This is what my stored procedure looks like. 

CREATE proc [dbo].[spHTTPRequest] 
      @URI varchar(2000) = '',      
      @methodName varchar(50) = '', 
      @requestBody varchar(8000) = '', 
      @SoapAction varchar(255), 
      @UserName nvarchar(100), -- Domain\UserName or UserName 
      @Password nvarchar(100), 
      @responseText varchar(8000) output 
as 
SET NOCOUNT ON 
IF    @methodName = '' 
BEGIN 
      select FailPoint = 'Method Name must be set' 
      return 
END 
set   @responseText = 'FAILED' 
DECLARE @objectID int 
DECLARE @hResult int 
DECLARE @source varchar(255), @desc varchar(255) 
EXEC @hResult = sp_OACreate 'MSXML2.ServerXMLHTTP', @objectID OUT 
IF @hResult <> 0 
BEGIN 
      EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT 
      SELECT      hResult = convert(varbinary(4), @hResult), 
                  source = @source, 
                  description = @desc, 
                  FailPoint = 'Create failed', 
                  MedthodName = @methodName 
      goto destroy 
      return 
END 
-- open the destination URI with Specified method 
EXEC @hResult = sp_OAMethod @objectID, 'open', null, @methodName, @URI, 'false', @UserName, @Password 
IF @hResult <> 0 
BEGIN 
      EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT 
      SELECT      hResult = convert(varbinary(4), @hResult), 
            source = @source, 
            description = @desc, 
            FailPoint = 'Open failed', 
            MedthodName = @methodName 
      goto destroy 
      return 
END 
-- set request headers 
EXEC @hResult = sp_OAMethod @objectID, 'setRequestHeader', null, 'Content-Type', 'text/xml;charset=UTF-8' 
IF @hResult <> 0 
BEGIN 
      EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT 
      SELECT      hResult = convert(varbinary(4), @hResult), 
            source = @source, 
            description = @desc, 
            FailPoint = 'SetRequestHeader failed', 
            MedthodName = @methodName 
      goto destroy 
      return 
END 
-- set soap action 
EXEC @hResult = sp_OAMethod @objectID, 'setRequestHeader', null, 'SOAPAction', @SoapAction 
IF @hResult <> 0 
BEGIN 
      EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT 
      SELECT      hResult = convert(varbinary(4), @hResult), 
            source = @source, 
            description = @desc, 
            FailPoint = 'SetRequestHeader failed', 
            MedthodName = @methodName 
      goto destroy 
      return 
END 
declare @len int 
set @len = len(@requestBody) 
EXEC @hResult = sp_OAMethod @objectID, 'setRequestHeader', null, 'Content-Length', @len 
IF @hResult <> 0 
BEGIN 
      EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT 
      SELECT      hResult = convert(varbinary(4), @hResult), 
            source = @source, 
            description = @desc, 
            FailPoint = 'SetRequestHeader failed', 
            MedthodName = @methodName 
      goto destroy 
      return 
END 
/* 
-- if you have headers in a table called RequestHeader you can go through them with this 
DECLARE @HeaderKey varchar(500), @HeaderValue varchar(500) 
DECLARE RequestHeader CURSOR 
LOCAL FAST_FORWARD 
FOR 
      SELECT      HeaderKey, HeaderValue 
      FROM RequestHeaders 
      WHERE       Method = @methodName 
OPEN RequestHeader 
FETCH NEXT FROM RequestHeader 
INTO @HeaderKey, @HeaderValue 
WHILE @@FETCH_STATUS = 0 
BEGIN 
      --select @HeaderKey, @HeaderValue, @methodName 
      EXEC @hResult = sp_OAMethod @objectID, 'setRequestHeader', null, @HeaderKey, @HeaderValue 
      IF @hResult <> 0 
      BEGIN 
            EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT 
            SELECT      hResult = convert(varbinary(4), @hResult), 
                  source = @source, 
                  description = @desc, 
                  FailPoint = 'SetRequestHeader failed', 
                  MedthodName = @methodName 
            goto destroy 
            return 
      END 
      FETCH NEXT FROM RequestHeader 
      INTO @HeaderKey, @HeaderValue 
END 
CLOSE RequestHeader 
DEALLOCATE RequestHeader 
*/ 
-- send the request 
EXEC @hResult = sp_OAMethod @objectID, 'send', null, @requestBody 
IF    @hResult <> 0 
BEGIN 
      EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT 
      SELECT      hResult = convert(varbinary(4), @hResult), 
            source = @source, 
            description = @desc, 
            FailPoint = 'Send failed', 
            MedthodName = @methodName 
      goto destroy 
      return 
END 
declare @statusText varchar(1000), @status varchar(1000) 
-- Get status text 
exec sp_OAGetProperty @objectID, 'StatusText', @statusText out 
exec sp_OAGetProperty @objectID, 'Status', @status out 
select @status, @statusText, @methodName 
-- Get response text 
exec sp_OAGetProperty @objectID, 'responseText', @responseText out 
IF @hResult <> 0 
BEGIN 
      EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT 
      SELECT      hResult = convert(varbinary(4), @hResult), 
            source = @source, 
            description = @desc, 
            FailPoint = 'ResponseText failed', 
            MedthodName = @methodName 
      goto destroy 
      return 
END 
destroy: 
      exec sp_OADestroy @objectID 
SET NOCOUNT OFF 

GO

 

The stored procedure takes the following parameters:

  1.  @URI: the URI of the web service
  2.  @MethodName: this would be ‘GET’ or ‘POST’
  3.  @RequestBody: this is your SOAP xml that you want to send
  4. @SoapAction: this the operation that you want to call on your service
  5. @UserName: NT UserName if your web service requires authentication
  6. @Password: the password if using NT Authentication on the web service
  7. @ResponseText: this is an out parameter that contains the response from the web service

 

Here is a sample call to my service 

declare @xmlOut varchar(8000)
Declare @RequestText as varchar(8000);
set @RequestText=
'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
   <soapenv:Header/>
   <soapenv:Body>
      <tem:CreateOrder>
         <!--Optional:-->
         <tem:OrderRequest>
            <tem:OrderId>200</tem:OrderId>
            <!--Optional:-->
            <tem:OrderName>something</tem:OrderName>
         </tem:OrderRequest>
      </tem:CreateOrder>
   </soapenv:Body>
</soapenv:Envelope>'
exec spHTTPRequest 
'http://localhost/testwebservices/helloworldservice.asmx', 
'POST', 
@RequestText,
'http://tempuri.org/CreateOrderForMe',
'', '', @xmlOut out
select @xmlOut 

The stored procedure runs and selects the response from my service call which in my case is:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <soap:Body>
  <CreateOrderForMeResponse xmlns="http://tempuri.org/">
   <CreateOrderForMeResult>
    <Message>Order Created for me</Message>
   </CreateOrderForMeResult>
  </CreateOrderForMeResponse>
 </soap:Body>
</soap:Envelope>

Note that the stored procedure automatically adds the appropriate http headers for Content-Type, SoapAction and Content-Length. If you need to pass additional http headers with your request, refer the section in the center of the stored procedure which is commented out. Basically you need a table in your database called RequestHeaders with 3 columns; HeaderKey, HeaderValue, Method. Populate this table with the keys and values for the additional headers. The Method column will contain GET or POST depending on what method you are using.

Another thing to note here is that I tried the above calls with MSXML2.XMLHTTP and Microsoft.XMLHTTP but did not succeed with either. I kept getting an error from msxml3.dll or msxml6.dll with message "The parameter is incorrect". I believe this to be a bug with msxml that requires the request body text to be in a specific format that is not available through a sql data type and hence cannot be used via TSQL. THese will hoever work fine when performing a simple http request (non- SOAP) or a SOAP request that does not need a request body. for performing SOAP requests from within TSQL the only component that worked for me was MSXML2.ServerXMLHTTP. There are some third-party components that I came across, some paid, but MSXML2.ServerXMLHTTP worked just fine for me.

The next step is to actually take the SOAP response that I recieved and extract the appropriate data from it - that will be another post.

Tags: , , ,

.NET | C# | SQL | SQL Server Management Studio

Passing JavaScript Objects to the CLR

by Admin 16. December 2009 08:19

Passing JavaScript Objects to the CLR

Asp.Net 3.5 makes it easy to pass JavaScript Objects to the CLR for AJAX calls. Here it is...

For this example, I created an ASP.Net Web Service Application which gave me a simple web service to start off with called Service1.asmx. The sample service has a single sample web method called HelloWorld() which just returns the text “Hello World”. For this example, since we want to pass something to the service method, I modify the service method a little bit so it looks like below:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Services; 
namespace JSAjaxTest 
{ 
    /// <summary> 
    /// Summary description for Service1 
    /// </summary> 
    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [System.ComponentModel.ToolboxItem(false)] 
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService] 
    public class Service1 : System.Web.Services.WebService 
    { 
        [WebMethod] 
        public string HelloWorld(string text) 
        { 
            return text; 
        } 
    } 
}

 Basically I just modified the method to accept a string and return that same string back.

Now add an application page to the project, default.aspx, which will contain the javascript that makes the AJAX call. The default.aspx page contains a script manager, a html button and a piece of javascript that gets called when the button is clicked to make the AJAX call. This is what the page looks like:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="JSAjaxTest._default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title></title>

    <script type="text/javascript">

        function CallService() {

            JSAjaxTest.Service1.HelloWorld("Hello World", function(response) { alert(response); });

        }

    </script>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        &nbsp;<asp:ScriptManager ID="ScriptManager1" runat="server">

            <Services>

                <asp:ServiceReference Path="/Service1.asmx" />

            </Services>

        </asp:ScriptManager>

        <input type="submit" value="hitme" onclick="javascript:CallService();" /></div>

    </form>

</body>

</html>

 

Looking at the javascript on the page, the call is really made here:

JSAjaxTest.Service1.HelloWorld("Hello World", function(response) { alert(response); });

The call to the webservice through javascript uses the script manager to make the call, pass in the javascript argument and specifies the inline call back function which gets called when the AJAX call is complete. The inline function simply has an alert statement that displays the response.

When you run the project, clicking on the button will pass the text, “Hello World” to the “HelloWorld()” method of the web service via AJAX. There is no postback.

Tags: ,

.NET | C#

Field type <blah> is not installed properly. Go to the list settings page to delete this field. - When trying to use custom field types developed using VseWss 3.0 v1.3

by admin 14. November 2009 23:17

When developing a custom field type using VseWSS 3.0 v1.3, I encountered a strange problem. The field type compiled successfully and deployed successfully as well, but whenever I tried to use the custom field type, I just got a generic error in SharePoint: “Field type <blah> is not installed properly. Go to the list settings page to delete this field.” Looking into the event log, the SharePoint logs and the vsewss log didn’t come up with anything useful either.

 

After searching a while online and coming up with a bunch of different solutions documented by other people, I found nothing worked. I went back to reading the VseWss 3.0 v1.3 release notes a couple of times over; especially the following couple of lines under the “Known Issues” section:

  • Custom Field Controls
    • During packaging additional XML configuration code will be added to the fldtypes_FieldControlName.xml file. To ensure the correct deployment of your field control you must add (if not already present) and Guid attribute to your SPField derived class. 

Example:[Guid("f5627588-e216-402e-844f-f85a0db34aa5")]
public class MyFC1Field : SPFieldText 

  • After packaging your project you must modify the fldtytypes_FieldControlName.xml file and synchronize the following element with your class's Guid:

<Field Name="FieldTypeClass">f5627588-e216-402e-844f-f85a0db34aa5</Field> 

·         Field control items are not able to be deployed due to a GUID being inserted instead of the type in the XML. This is a known issue , you can manually add the correct entry which will result in two entries in the fldTypes*.xml file 

I wasn’t entirely sure what this meant by when comparing the fldtypes_blah.xml that gets generated for the field type at C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\XML and the fldtypes_blah.xml in my vsewss project, there was a difference.

The vsewss fldtypes_blah.xml contained:

<?xml version="1.0" encoding="utf-8"?>

<FieldTypes>
 <FieldType>
  <Field Name="TypeName">LogFieldFieldControlField</Field>    
  <Field Name="TypeDisplayName">LogFieldFieldControlField</Field>
 
<Field Name="TypeShortDescription">LogFieldFieldControlField</Field>   
  <Field Name="ParentType">Text</Field>
 
<Field Name="UserCreatable">TRUE</Field>
 
<Field Name="FieldTypeClass">b2931c02-1f9c-4eeb-8839-421be14a38d5</Field>
 
</FieldType>
</FieldTypes> 

The generated fldtypes_blah.xml that gets put in the 12 hive contained:

<?xml version="1.0" encoding="utf-8"?>
<FieldTypes>  
 <FieldType>    
 <Field Name="TypeName"BlahFieldControlField</Field>   
 <Field Name="TypeDisplayName">BlahFieldControlField</Field>   
 <Field Name="TypeShortDescription">BlahFieldControlField</Field>   
 <Field Name="ParentType">Text</Field>   
 <Field Name="UserCreatable">TRUE</Field>   
 <Field Name="FieldTypeClass">blah.blahcontrolfield</Field> 
 </FieldType>
</FieldTypes> 

Looks like the FieldTypeClass field node that contained the guid of the field type class gets replaced by the class name on deployment. But the class name is not fully qualified like most manual steps state that it should be.

I replaced it in the deployed fldtypes_blah.xml so that the xml node now looked like:

<Field Name="FieldTypeClass">Blah.BlahFieldControlField, blah, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8adae1dce348f885</Field> 

i.e. the value is namespace.classname, assembly name, version, culture, publickeytoken  

Then restart IIS

that got my custom field type working. So what you need to do is deploy the solution using vsewss 3.0 v1.3, then go into C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\XML, find your fldtypes_blah.xml and replace the FieldTypeClass node text which contains the class name to contain the fully qualified class name. Then restart IIS. So far this is what has worked for me, but if I come up with a better way, I’ll update this post.

Tags: , , , , , , ,

Sharepoint

ssms tools pack - Auto Generate CRUD stored Procedures for your database and more

by admin 1. June 2009 19:53

Just found a great tool that will hopefuly save me tons of work...

It can auto-generate the CRUD stored Procedures for your tables - that was the most useful to me. Plus there are a lot of other useful features for the IDE.

  • Window Connection Coloring.
  • Query Execution History (Soft Source Control) and Current Window History.
  • Search Table or Database Data.
  • Uppercase/Lowercase keywords and proper case Database Object Names.
  • Run one script on multiple databases.
  • Copy execution plan bitmaps to clipboard.
  • Search Results in Grid Mode and Execution Plans.
  • Generate Insert statements for a single table, the whole database or current resultsets in grids.
  • Text document Regions and Debug sections.
  • Running custom scripts from Object explorer's Context menu.
  • CRUD (Create, Read, Update, Delete) stored procedure generation.
  • New query template.

http://www.ssmstoolspack.com/

Tool to build WSP solutions for MOSS/Sharepoint Projects

by admin 10. September 2008 18:46

The tool is called STSDEV. I found it on codeplex. The tool allows you to generate Visual Studio Projects & Solutions to facilitate building of MOSS deployement solutions. Its a simple command line utility that allows you to select the kind of deployment you are trying to do. The hoices include, empty solutions, features, webparts etc. By simply selecting the type of solution and clicking a button, it creates the visual studio project templates for building the WSP. You can drag and drop all of your deployment files into a predefined 12 hive structure. Hitting build on your solution, atomatically create sthe manifest file and builds the wsp. Till now I was building the mannifests and wsps by hand and that is a pain.

There are a number of build configurations generated for you that allow you to retract, deploy, redeploy, install the solutions directly to MOSS without needing to use stsadm. Its a great little tool for development and debugging.

 The project can be found at http://www.codeplex.com/stsdev.

 Here are some sceen casts that are very helpful in getting you started: http://www.codeplex.com/Release/ProjectReleases.aspx?ProjectName=stsdev&ReleaseId=10119

 

 

Tags: , ,

.NET | Sharepoint | MOSS

Another iPhone App - Guitar Chords on the iPhone - iChords - http://www.ichords.vishalseth.com

by admin 29. July 2008 03:47

Ok, I added another one. This one is a great app that allows you to find almost any guitar chords by name. Not only that, it allows for finding many variations of the same chord, left handed and right handed chords, different tuning scales etc. the url is http://www.iphone.vishalseth.com. I just submitted it on Apple's website and will post a link to the listing when it shows up.

Tags: , , ,

.NET | C# | iPhone | iPod

Adding AdSense on an Office Live Site

by admin 23. July 2008 04:10

I recently tried to add google adsense ads on my office live page at http://www.vishalseth.net. It wasn't straightforward but you can do it. Initially, I saw the HTML module available in the site designer and thought I could just use that; but if you've tried it that doesnt work either... or atleast did not work for me. I had to use an iframe... This is what I finally did to make it work:

  1. Create an empty html file e.g. AdSense.htm on my computer
  2. paste the AdSense code from google including the script tags into the htm file using notepad. The html file at this point only contains the code in the script tags and nothing else (no <html>, <head> or <body> tags either.)
  3. save and close the file
  4. upload the file to to your documents folder in your office live account. when logged into site builder, the link to the document library should be available on the left. Clicking on it should alloow you to upload any files into the library.
  5. in the site builder, open the page onto which you wish to add the adsense ads. add a html module onto the page.
  6. for the html, insert the following: <iframe  frameborder="0" scrolling="no" src="http://yoursite.com/Documents/adsense.htm" width="770" height="110"></iframe>. Save.
    1. yoursite.com is the base url of your site
    2. height, width can be set to suit the dimensions of the ads you're displaying.

The ads should now be visible on your site...

Tags: , ,

.NET | General | office live

iPhone App - iNGPOD - National Geographic Magazine's photo of the day.

by admin 21. July 2008 19:24

This iPhone development thing is addictive. seriously. It's hard for me to have a little time on my hands and not want to write another fun app that shows up on my home screen. This one just pulls and displays the Photo of the day from National Geographic Magazine's website. It's something I have on my google home screen and just like to look at daily and thought it would be fun if I could have it on my phone as well. The url is http://www.iNGPOD.vishalseth.com. You can see it published in Apple's web application directory by clicking here 

 Update: The application is offline for now due to problems with making httprequests in my medium trust hosting environment.

Tags: , , , ,

.NET | C# | General | iPhone | iPod

Another new iPhone App - iSigns - Mobile Horoscopes from astrology.com

by admin 20. July 2008 18:18

I created a new app this weekend because I had a little bit of time. My wife likes to check her daily horoscope on astrology.com and I thought it would be cool if I could make an app that shows the daily horoscope. Whats even better is that they have daily horoscopes in many different categories like for example, general, health, couples, singles, home & garden, work and even a baby, dog and cat horoscope! Now I can just pull up the daily horosocopes anytime; kind of fun. I just submitted the app on apple's iPhone webapps directory so I'll post a link to the listing when it appears. Meanwhile, the link to the app, if you want it on your phone is, http://www.iSigns.vishalseth.com. For now its only customized to the apple mobile safari browser.

Update: See the application published in apple's web app directory by clicking here.

 

 Update: The application is offline for now due to problems with making httprequests in my medium trust hosting environment.

Tags: , , , , , ,

C# | .NET | iPhone | C# | iPod | iPhone | iPod