Welcome to MSDN Blogs Sign in | Join | Help

[Closed] Job Posting: Software Development Engineer

I have few job openings in my team for Silverlight, AJAX, WCF, WPF and SQL Server developers. Here's the job description.

 “Do you like dynamic challenges in web application development? A large scale internet applications on the world’s top commercial web site sounds interesting to you? Do you want to work on cutting edge web application using state of the art Web 2.0 technologies? If you answer yes to any of the above questions, here is the opportunity for you.

Marketing Center Of Excellence (Global Marketing Platform) division’s World Wide Events & Profile Center team is looking for a self motivated and seasoned senior web UI developer. This is an application that allows partners to create live, in-person and live meeting events via the partners’ extranet application, and these events are exposed on external internet facing site http://msevents.microsoft.com to the users who might be interested in registering and attending the events. Team is working on renovating the Web UI and Middle Tier. In addition to the current features, next generation system includes streaming videos and rich UX via Silverlight, integration with adCenter, contextual display of events on third party sites, communities integration, pluggable controls for other Microsoft.com properties etc. This is a great opportunity to impact the external customers with first hand code. Some of the highlights of the project includes Web UI instrumentation for analyzing user’s cognitive behavior and collecting usage, performance and error data directly from the client side XMLHTTP calls, Web UI and Middle Tier based on modern design patterns, WCF (Indigo) and Web Services based contracts between Middle Tier and the adopters, individually testable and scalable layered architecture.

The required skills for this opening are: proficiency in OOP and C# (2.0), ASP.NET (Controls, Life cycle, Integration, Performance and Payload optimizations), DHTML, XML/XSL, JavaScript (Object Oriented), Web Services, WSE, AJAX (strong custom and Atlas/’ASP.NET AJAX’ implementations).

Knowledge of KAF/ECHO Automation, XAML/Silverlight, SQL Server 2005 (TSQL, Profiler) is desirable. A BA/BS degree in Computer Science, Electronics or Mathematics, 8+ years or an MS in similar fields with 7+ years of professional experience is required.

 If it interests you and you have desired qualification, please contact me.

Posted by samar | 1 Comments

Basic C# coding guidelines

C# 2.0

-     Use generic collections instead of Hashtables and ArrayList types

-     If using Generic types, then refrain from using foreach loop on the collection. Rather use ForEach method to loop through via an anonymous method predicate (much faster because doesn’t create the Iterator). For non generic types try to use for loop instead of foreach if the data being traversed is huge

 

List<string> list = new List<string>();

list.Add("aa");

list.Add("bb");

 

//option 1:

foreach(string str in list)

   Console.WriteLine(str);

 

//option 2: RECOMMENDED

list.ForEach(delegate(string str) {

 Console.WriteLine(str);

});

 

-    Nullify unused objects (doesn’t collect, but marks for collection and ceases from getting promoted into next generation)

-    IF conditions having just one item in if and else, should be used as ternary operator (? Sign)

e.g. instead of the code:

 

int i;

if(someConditionTrue)

        i = 3;

else

        i = 4;

 

It is better to write the above 5 lines into just one:

 

int i = someConditionTrue ? 3 : 4;

 

-     Use ‘as’ operator instead of direct typecast using parenthesis with the exception of overloaded explicit cast operator, it saves from NullReferenceException and InvalidCastException

-     Refrain from XmlDocument usage for navigational purpose, please either use XmlTextReader for sequential access or XPathDocument for XPath based data retrieval               

-     For server side XSL transformation, Use XslCompiledTransform instead of XslTransform (Please check http://blogs.msdn.com/antosha/archive/2006/07/24/677560.aspx ). For client side transformation, try to load Xsl file asynchronously whenever possible via XMLDOM or XsltProcessor (Geckos)

-     Always join your threads in a web page, if used (otherwise the page will be rendered and workers will continue operating at the server cost, and ofcourse the results will be unpredictable)

Let's say you opened two threads in a web page using the following:

 

Thread AThread  = new Thread(new ThreadStart(CallProcOne));

AThread.Start();

                                   

Thread CThread  = new Thread(new ThreadStart(CallProcTwo));

CThread.Start();

 

//Now it is recommended to do this:

AThread.Join();

CThread.Join();

 

-    Always do NULL checking before operating on an object, NullReferenceException is widely occurring exception in most applications and only a preventive programming can help us get the real error

-     Handle most specific (expected) exceptions in the catch blocks before deciding towards general Exception, and please don’t use catch without an exception object if you’re not really writing P/Invoke in C#

Posted by samar | 1 Comments

Creating custom wrapper for all JavaScript functions

There might be scenarios when all JavaScript side initiated function calls need to be intercepted for logging and error reporting purposes on the client. Two approaches exist, one, calling an intermediary function and then initiating call to real function, but that could be harder to manage. Since JavaScript allows real flexibility in extending its base objects (such as String, Array, Function etc), it is quite manageable to create a custom wrapper in the base Function object and all functions will go through this route. You might decide to use this feature on as-needed basis.

In the example below, a custom wrapper known by its name is created under Function by extending the prototype property. Normal JavaScript functions (such as func and printObjects in following example) don't need to change their implementation. Only at the time of calling the real function, just replace the real function name with function name + .wrapper and pass arguments as you would normally do, starting with the "this" which is required for remembering who is the original caller of this function. e.g. a sample call could be

onclick="myFunction.wrapper(this,'x','arg2',{2,2});"

<!-- #### Code below -->
<script>
Function.prototype.wrapper = function(sender)
{
 alert("In Wrapper function first; Logging starts here");
 alert(arguments.length > 1 ? "First argument of real function is " + arguments[1] : "no additional args")
 try {
  this.apply(sender,arguments); //real function call
 }catch(exception)
 {
  //log exception on server side using XMLHTTP and/or display a generic message to user
 }
 alert("In Wrapper function; Logging ends here");
}

function func(sender)
{
 alert("Real function called");
}

function printObjects(sender)
{
 document.write("<pre>");
 for(var i in document)
  document.writeln(i + " << " + typeof(i));
}
</script>

<input onclick='func.wrapper(this,"hello",new Object());' type=button id=b value=Press NAME="b"/>
<input onclick=printObjects.wrapper(this); value=PrintObjects type=button ID="Button1" NAME="Button1"/>  
Posted by samar | 0 Comments
Filed under:

Auxiliary Saver Technique in Web Forms

As we all know state management is a big deal in web applications. We might have web forms that send important data to the server where might lie some validations in addition to the client side JavaScript validations. General challenge is to restore all the client controls to their previous selections. ViewState use can help, however there are two issues in controling state

1. If you're conservative to keep your page size to low, you may not use ViewState.
2. The controls were built using client side script and/or their data was populated dynamically (such as AJAX or XML DSO etc), these bindings will need to happen once again when page is rendered back after the error or the status check

Is it really needed to Postback when saving data using webforms? Answer is No. Because we can utilize an auxilliary "form saver" page/handler that will be posted data from the client using XMLHTTP asynchronously, and whenever it finishes processing, it can return back the XML as a response metadata. This XML response will tell whether the operation to save form data succeeded or not. Also we can customize it to return some status codes (may be used to redirect after saving data etc) and meta language to perform post-save processing on the client side using JavaScript.

Posted by samar | 0 Comments
Filed under:

True Asynchronous Payload

For rendering content and feature rich web pages, here are the questions that we have in front of us:

1. How to speed up the process of data fetch/load at the server to rendering it to the web client.
2. Reduce the markup

I discussed point 2 in my previous post (another way to reduce markup is to not "Generate" X/HTML on the server, do it using XSLT on client). Anyhow 2. is also indirectly correlated to 1.

As a proposed solution, what we need here is the true asynchronous loading of the web page that is feature/content rich. So how do we achieve that!? Ironically the answer lies in both the developer's mind (what data to async) and the methodology I'm about to discuss. Here is my thought process for manually dividing the payload distribution

1. Logically separate the different data units of the web page (viz. in a news site, breaking news, stock ticker and weather information can be considered isolated if they all come from different data sources or in other words they have be explicitly loaded by using a DB call)
2. Render the page from server with placeholder markup for these logical data units (i.e. no data, no DB calls have been made so far) and a small JavaScript block containing boolean variables values set to true for which [data units] content needs to be loaded later.
3. After the server request has returned lightweight payload (missing data) and quicker response (server didn't have to do much processing cause most importantly DB calls were skipped), go through the JavaScript boolean variables set by the server, each of them signifies a data units. which ever is set to true, make AJAX call to grab data from the server and populate in the respective placeholders of data units.
4. Next is upto the developer to either render X/HTML out of the data retrieved using plain JavaScript or XSLT. Tip: If using XSL, remember they can also be loaded asynchronously! So higher performance can be achieved if the XSL is large and heavy markup is rendered out of it.
5. In the end, page will appear as being loaded asynchronously and much faster than it would have using a single server send. It's like using multiple small funnels instead of a big one, that is sequential.

Posted by samar | 0 Comments
Filed under:

Determine the Payload division

Lately I've been thinking about devising a mechanism to determine the division of the Payload between the content that is rendered to client web browser (including markup) and the one that client browser can load, hold and process in its memory. The logic behind this idea is to reduce the network traffic on the wire in PLT-1. And then grab the rest of the [required] data using hidden XMLHTTP calls and keep in browser's memory variables. Certain ActiveX (such as XMLHTTP, XMLDOM) can process the data received through AJAX (XMLHTTP/WinHTTP) call and render to the screen. It saves us two things

1. Processing these records on the web server (saving CPU)
2. Rendering markup from server on the HTTP wire (which can be processed and rendered by a cheaper mechanism on the client browser such as XSLT/JS)

And costs us this

1. More server requests (lightweight though)

However to partially get around the cost mentioned above, we need to keep once loaded data into browser memory variables and not make the request if same thing is being requested again.

Coming back to the main issue, to determine how much data should be rendered by the server, and how much responsibility can be given to the client to load (XML) and process without causing IE memory leaks/overruns. Next is to devise an algorithm to determine this division factor on the basis of size of total renderable data.

let d=data; t=time

d(c) + d(s) = d(tl)      ... (1)

t(c) + t(s) = t(tl)         ... (2)

However, in (2) t(s) is a variable and t(c) is constant [assuming all clients have as usual near about high amount of memory and CPU available]. In order to find the value of d, use of induction could be handy, if performance can be optimized or at least standardized as acceptable. I'll post what I find out of this experiment.

Posted by samar | 1 Comments
Filed under:

Encrypt at client side and decrypt at server

There might be situations where the content from thin client that is accessible via internet, needs to be encrypted (without storing the encryption logic at the client) and subsequently be decrypted on the server side code that doesn't run on SSL. Here is one thought how to do that with help of JavaScript and XMLHTTP ActiveX object (replacement available for Mozilla family browsers as well).

First we'll write a JavaScript function that makes a synchronous POST call to a web page(Reform.aspx) that contains the encryption logic and returns the encrypted value to client and this web page should run on SSL. This function thus provides encryption for parameters on need basis without putting the whole location/webpage on SSL that will include the overhead of encryption for all form data including the hefty ViewState (if not being stored in Session using Page.SavePageStateToPersistenceMedium.

//########JavaScript for calling ASPX page and encrypting ###########

function changeParam(str)
{
 str = "dataToReform="+escape(str);
  if(window.XMLHttpRequest) {
   request = new XMLHttpRequest();
  }
else if(window.ActiveXObject) {
  
request = new ActiveXObject("Microsoft.XMLHTTP");
}

 if(request)
 {
 
request.open("POST", "Reform.aspx",false);
  request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  request.setRequestHeader("Content-length",str.length);
  
request.send(str);
 
return request.responseText;
 }
}

Above function call be called by passing a string to be encrypted. Now let's have a look at the server page that contains the logic to encrypt and decrypt. It can by any custom encryption logic depending upon developer's choice.

//######## C# class that defines encrypting/decrypting ###########

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Collections.Specialized;
using System.Xml;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
namespace YourNamespace
{
public class Reform : Page
{
public override void Page_Load(object sender, System.EventArgs e)
{
Response.Write(Encrypt(Request["dataToReform"]));
Response.End();
}

public static string Encrypt(string source)
{
byte[] initializer = Encoding.ASCII.GetBytes("@1B2c3D4e5F6g7H8");
byte[] stringiation = Encoding.ASCII.GetBytes("5uM1+4m4~"); //flavor for the encryption
int size = 192;
byte[] bytStr = Encoding.UTF8.GetBytes(source);
PasswordDeriveBytes pwdItem =
new PasswordDeriveBytes("p455W0~d*(*)",stringiation,"SHA1",5); //password code for encrypting in SHA1 or anything else
byte[] bytKeys = pwdItem.GetBytes(size/8);
RijndaelManaged rmEncryption =
new RijndaelManaged();
rmEncryption.Mode = CipherMode.CBC;
//cipher block chaining
ICryptoTransform encryptor = rmEncryption.CreateEncryptor(bytKeys,initializer);
MemoryStream stream =
new MemoryStream();
CryptoStream cryptoStream =
new CryptoStream(stream,encryptor,CryptoStreamMode.Write);
cryptoStream.Write(bytStr, 0, bytStr.Length);
cryptoStream.FlushFinalBlock();

byte[] bytSource = stream.ToArray();
stream.Close();
cryptoStream.Close();
string ciphered = Convert.ToBase64String(bytSource);
return ciphered;
}

public static string Decrypt(string ciphered)
{
byte[] initializer = Encoding.ASCII.GetBytes("@1B2c3D4e5F6g7H8");
byte[] stringiation = Encoding.ASCII.GetBytes("5uM1+4m4~");
byte[] bytStr = null;
int size = 192;

try
{
bytStr = Convert.FromBase64String(ciphered.Replace(" ","+"));
}
catch(Exception ex){System.Diagnostics.Debug.WriteLine(ex.Message);}

PasswordDeriveBytes pwdItem = new PasswordDeriveBytes("p455W0~d*(*)",stringiation,"SHA1",5);
byte[] bytKeys = pwdItem.GetBytes(size/8);
RijndaelManaged rmEncryption =
new RijndaelManaged();
rmEncryption.Mode = CipherMode.CBC;
//cipher block chaining
ICryptoTransform decryptor = rmEncryption.CreateDecryptor(bytKeys,initializer);
MemoryStream stream =
new MemoryStream(bytStr);
CryptoStream cryptoStream =
new CryptoStream(stream,decryptor,CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[bytStr.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
stream.Close();
cryptoStream.Close();

string
plainText = Encoding.UTF8.GetString(plainTextBytes,0,decryptedByteCount);
return plainText;
}

}
}

Now at the server side where the parameter encrypted by calling changeParam(str) was sent, can be decrypted by making a static call to Reform.Decrypt(string)

Posted by samar | 1 Comments
Filed under:

Web Services: Revolutionize your business

Industry is talking of Web Services to the height of Petronas Towers. For an IT
professional unaware of Web Services following questions come up,
1. How practical is it when it comes to implementation?
2. Are they real, or hype?
3. Why Web Services?
4. Who will be benefited?

Before answering the above questions, let’s present a small scenario, when some
ISV or an organization had to sell their services in the form of components, they
would write component compile it and make available on the stores (websites).
Potential consumers of the product, needed to know where the product is available,
after they search it, they incorporate it in their business application. It sounds quite
straightforward, but the story is not over yet. Proceeding with the change in the
product, provider had to modify the component and remarket with changes. This is
a perfect example of providing reusable components that could be used by varying
enterprises.

Coming on to intra enterprise application management scenario, where locations are
spread physically and geographically, application required remote access to services
running on physically distributed terminals. It evolved the concept that’s known with
varying names in various technologies viz. “Remote Method Invocation”, “Remote
Procedure Call”, “Distributed Component Object Model”, “Common Object Request
Broker Architecture” and many more. Making remote calls phenomenon added great
value to the distributed computing. However, all of these technologies required a
dedicated connection to be maintained to bind, listen, send and receive data.

Considering the limitations of two different approaches discussed above, industry felt
the need of having some mechanism that would allow
1. Remote Method Calls without maintaining dedicated connections
2. A centralized way of managing the change in components
3. Better advertising and selling perspectives
4. Cross platform, Robust and Extensible access 

Microsoft, IBM, Sun, Ariba along with other companies came up with an extension to a
common data exchange mechanism that was already being used for data
interchange in EDI and EFT, namely XML. The standard was first named as SDL
(Service Description Language) by MS, but the industry agreed upon a common
name of WSDL (Web SDL). Theoretically, a web application running on any platform,
container or server needed to generate a common format of data for response to a
service request. WSDL is a SOAP (Simple Object Access Protocol) based standard
that encapsulates the functionality within an XML document.

What are Web Services after all? Web Services are web applications available
through HTTP (that is a stateless protocol and allows asynchronous requests), and
can be requested by any client running on any platform and application, and in
response to the request WS will return data in the form of WSDL, which can then be
utilized to generate a “proxy” or representation library of the web service.
Subsequently, this library can be used in the implementing application and web
service’s methods can be invoked. The mechanism sounds quite similar to RPC and

RMI, but with significant differences of being operated on stateless protocol HTTP
and being able to execute on any platform. Web Services have solution to all the desired functionalities stated as desired.

We’ll now see the answers to questions discussed at the start:
How practical are web services when it comes to implementation: Despite of short
span of Web Services inception, most of the corporates, ISVs and other entities have
started to provide some of their business components’ functionalities through Web
Services. Bablefish Translation provider is a perfect example, which is provided by
legendry search engine Alta Vista. Other examples include WhenU.com’s world
weather service. The benefit implementer gets is the ease of use and freedom to use
in any kind of software.

Are they real, or hype? Whenever a new technology is introduced in the market, it’s
nothing but hype. But as the time grows and technology matures stakeholders
understand the real stand of the technology. Since Web Services concept was
support by industry legends like MS, IBM, Sun, it started in its winning spree within
these organizations, but in a short span all of the other stakeholders understood the
benefits it provides. Oracle.com published a massive article in Oracle magazine that
was titled “Web Services are Real”. The objective was of course to market their
Oracle Portal Server in context of Web Services, but it provided insights of actual
implementation of a Secure Architecture that uses J2EE and Oracle to provide robust
business services. Since the industry is adopting Web Services at a geometric rate, it
is relevant to say “They are Real !”

Why Web Services: It provides an independent, flexible, robust, scalable and
industry wide standard that makes distributed computing peanuts. More benefits are
already discussed.

Who is benefited? : Web Services provide one stop solution to businesses,
developers, consumers and UDDI business registry nodes that “host” the “logical
repository” of web services. Businesses feel more comfortable in version control of
the component/service while developers just have to know the URI of the WSDL of
web services. More significantly they can programmatically search the UDDI registry
using simple SDKs provided by most of the vendors. Ultimate consumers of the web
service can make a SOAP request to the WSDL, ROPE (Remote Object Proxy Engine)
generates a proxy on the fly and remotely methods of the service can be invoked,
there are no hiccups of installation, registration and distribution of the components.

At last we can conclude that Web Services are all set to revolutionize the modern
businesses that deal with distributed computing.
Posted by samar | 2 Comments
Filed under:

Publish, Discover and Invoke Web Services using SOAP and UDDI

Introduction
The project contains code that allows to Describe, Discover and Invoke a web service in .NET using SOAP SDK 3.0 and UDDI SDK 2.0 beta on .NET SDK 1.1.

Background
UDDI (Universal Description Discovery and Integration) is a standard that defines common registry where web service providers register themselves and describe/publish their services and details thereof including the URIs to access services. The authority that provides centralised UDDI services is known as Business Registry Node. There could be a public or private node, public being accessible to everyone over the internet. Some commonly used public nodes include microsoft (uddi.microsoft.com), IBM, SAP and others. We'll be making use of Microsoft Test UDDI node (test.uddi.microsoft.com) for our testing purposes. The public UDDI node can be searched by an API that conforms with a UDDI specification set by UDDI.org. e.g. Microsoft's UDDI SDK 2.0 beta can be used in .NET environment to make inquiry and publish requests to microsoft uddi site.

SOAP (Simple Object Access Protocol) is a communication standard based on XML and used in communications between web service calls. Microsoft's SOAP SDK facilitates to invoke web service methods without creating a proxy class for the web service. We'll be making use of SOAP SDK 3.0 for our testing environment.

Code Usage

As discussed earlier, we'll communicate with microsoft's test uddi node, in order to publish our business and services we need to have a passport ID and need to register ourselves as a service provider manually at the https://test.uddi.microsoft.com/register.aspx . I'm going to use a web service written by someone that converts/translates the supplied string to a funny word.

Following are related to UDDI and SOAP SDKs

using Microsoft.Uddi;
using Microsoft.Uddi.Api;
using MSSOAPLib30;

After including the appropriate namespaces, define the initial parameters.

string passportUserId="uddisoap@hotmail.com",
passportPassword=@"/find?\//",
inquireUrl="http://test.uddi.microsoft.com/inquire",
publishUrl="https://test.uddi.microsoft.com/publish", //mind the HTTPS for
publishing
webService=
"http://www.aspxpressway.com/maincontent/webservices/piglatin.asmx"; string serviceProvider= "SOAP UDDI WS
Testers";
//our test service provider name

Publishing a service provider and the service.

private void publish_Click(object sender, System.EventArgs e)
{
try
{
Publish.Url = publishUrl;
Publish.User = passportUserId;
Publish.Password = passportPassword;

SaveBusiness sb = new SaveBusiness();

sb.BusinessEntities.Add();
sb.BusinessEntities[0].Names.Add(serviceProvider);

sb.BusinessEntities[0].Descriptions.Add("en", "This business is all about testing web services.");

sb.BusinessEntities[0].CategoryBag.Add("Washington", "US-WA", "uuid:4e49a8d6-d5a2-4fc2-93a0-0411d8d19e88");

// Add contact details for responsible/support people
sb.BusinessEntities[0].Contacts.Add();
sb.BusinessEntities[0].Contacts[0].PersonName = "Sumit Amar";
sb.BusinessEntities[0].Contacts[0].UseType = "Programmer";
sb.BusinessEntities[0].Contacts[0].Addresses.Add("#code", "PBMS");
sb.BusinessEntities[0].Contacts[0].Addresses[0].AddressLines.Add("35 Downing Street");
sb.BusinessEntities[0].Contacts[0].Addresses[0].AddressLines.Add("New London");
sb.BusinessEntities[0].Contacts.Add("Veronica","CTO"); //UseType specified in IInd parameter

// Add service details
sb.BusinessEntities[0].BusinessServices.Add();
sb.BusinessEntities[0].BusinessServices[0].Names.Add("pigLatin");
sb.BusinessEntities[0].BusinessServices[0].Descriptions.Add("Pig Latin funny!");

// Specify a binding where the service can be located
sb.BusinessEntities[0].BusinessServices[0].BindingTemplates.Add();
sb.BusinessEntities[0].BusinessServices[0].BindingTemplates[0].AccessPoint.Text = webService;
sb.BusinessEntities[0].BusinessServices[0].BindingTemplates[0].AccessPoint.URLType = Microsoft.Uddi.Api.URLType.Http;
sb.BusinessEntities[0].BusinessServices[0].BindingTemplates[0].Descriptions.Add("Converts the text to funny pig latin");

// Send the built save business request
BusinessDetail businessDetail = sb.Send();

// Print the generated business key
Response.Write("Business: " + businessDetail.BusinessEntities[0].Names[0].Text);
Response.Write("Key: " + businessDetail.BusinessEntities[0].BusinessKey);
Response.Write("Service published in Microsoft test UDDI site");
}
catch (UddiException ex)
{
if(ex.Number==UddiException.ErrorType.E_accountLimitExceeded)
Response.Write("UDDI Exception: Service Provider "+serviceProvider+" already exists");
else if(ex.Number==UddiException.ErrorType.E_unknownUser)
Response.Write("UDDI Exception: Passport authentication failed, double check your userId ("+passportUserId+") and password ("+passportPassword+")");
else
Response.Write("UDDI exception: " + ex.Number + " - " + ex.Message); }
catch (Exception ex)
{Response.Write("Other exception: " + ex.Message);}

}

Discovering the web service provider and service
private void discover_Click(object sender, System.EventArgs e)
{
try
{

Inquire.Url = inquireUrl;

// Create an object to find a business
FindBusiness fb = new FindBusiness();
fb.Names.Add(serviceProvider);

// Send the prepared find business request
BusinessList businessList = fb.Send();

if (businessList.BusinessInfos.Count>0)
{
GetBusinessDetail detailObject = new GetBusinessDetail();

// Associate the business key with detailObject, returned by fb.Send call
detailObject.BusinessKeys.Add(businessList.BusinessInfos[0].BusinessKey);
// Send the request to the UBR node
BusinessDetail businessDetail = detailObject.Send();

//Scan through all business entities returned
if (businessDetail.BusinessEntities.Count>0)
{
// Scan categories specified for this business
for (int i=0; i < businessDetail.BusinessEntities[0].CategoryBag.Count; i++)
{
Response.Write(" Categories: ");
Response.Write("Name : " + businessDetail.BusinessEntities[0].CategoryBag[i].KeyName);
Response.Write("Value : " + businessDetail.BusinessEntities[0].CategoryBag[i].KeyValue);
Response.Write("tModel : " + businessDetail.BusinessEntities[0].CategoryBag[i].TModelKey);
}

// Scan identifiers for the same
for (int j=0; j < businessDetail.BusinessEntities[0].IdentifierBag.Count; j++)
{
Response.Write("Identifiers:");
Response.Write("Name : " + businessDetail.BusinessEntities[0].IdentifierBag[j].KeyName);
Response.Write("Value : " + businessDetail.BusinessEntities[0].IdentifierBag[j].KeyValue);
Response.Write("tModel : " + businessDetail.BusinessEntities[0].IdentifierBag[j].TModelKey);
}

// scan contacts
for (int k=0; k < businessDetail.BusinessEntities[0].Contacts.Count; k++)
{
Response.Write("Contact ("+(k+1)+"):" );
Response.Write("Name : " + businessDetail.BusinessEntities[0].Contacts[k].PersonName);
Response.Write("Type : " + businessDetail.BusinessEntities[0].Contacts[k].UseType);
}

// Scan through business services
for (int m=0; m < businessDetail.BusinessEntities[0].BusinessServices.Count; m++)
{
Response.Write("Services:");
Response.Write("Name : " + businessDetail.BusinessEntities[0].BusinessServices[m].Names[0].Text);
// There might be multiple access points for this service
for (int n=0; n < businessDetail.BusinessEntities[0].BusinessServices[m].BindingTemplates.Count; n++)
{
//display and put the AccessPoint in variable wsUri
Response.Write("Access point : " + (businessDetail.BusinessEntities[0].BusinessServices[m].BindingTemplates[n].AccessPoint.Text));
wsUri=businessDetail.BusinessEntities[0].BusinessServices[m].BindingTemplates[n].AccessPoint.Text;
}
}
}
}
}
catch (UddiException er)
{Response.Write("UDDI exception: (" + er.Number + ") - " + er.Message);}
catch (Exception er)
{Response.Write("Other exception: " + er.Message);}
}




Invoking the web service: Now we'll invoke the web service method using the SOAP SDK provided by microsoft. Invoking services using SoapClient(n) class is fairly easy. Here n means the major version appended to the classes. this number is not associated with SOAP SDK's previous versions than 3.0.
MSSoapInit method in SoapClient(n) class initialises the web service for the given WSDL and accepts service name and service port.

private void invoke_Click(object sender, System.EventArgs e)
{
SoapClient30 sc = new SoapClient30();
string translateText=textToTran.Text;
string wsdl=null;
try
{
if(wsUri==null)
throw new Exception("Please Discover the service first");
if((new Regex("(wsdl)$")).IsMatch(wsUri)) //check if it's the real WSDL
wsdl=wsUri;
else
wsdl=wsUri+"?wsdl"; //otherwise append WSDL to the service

sc.MSSoapInit(wsdl, "piglatin", "piglatinSoap",""); //specify the service name and port name
Type type =sc.GetType();

object []args = {translateText}; //specified service accepts just one argument (textToTranslate)
Response.Write("Invoking method using MS SOAP SDK ...");
object ox = type.InvokeMember("toPigLatin", BindingFlags.InvokeMethod,null,sc,args); //Dynamic Invocation No Proxy class, no web reference
Response.Write("Translated String "+ox.ToString());
}
catch(Exception sEx){Response.Write("Exception occurred "+sEx.Message);}
}




Further Enhancements
This sample code might be further enhanced to present a dashboard for testing web services and it's methods in UDDI registry.

Sumit Amar
Posted by samar | 0 Comments
Filed under: ,

Retrieving SOAP Envelope from WebException

Web Services might be invoked using HttpWebRequest. If the invocation raises a service specific exception, the WebException’s Message property gives “Internal Server Error (500)”. There exists a need to parse the WebException object to retrieve the original SOAP Envelope with fault details. Here is the solution:

catch(WebException wEx)
{
string str=wEx.ToString();
if(wEx.Response == null ) //If not SOAP Exception
throw new Exception(wEx.Message);
WebResponse webResp = wEx.Response;
Stream receiveStream = webResp.GetResponseStream();
System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(receiveStream, encode);

XmlDocument xmlResponseDoc = new XmlDocument();
xmlResponseDoc.Load(readStream);
Debug.Write(readStream.ReadToEnd());
readStream.Close();
webResp.Close();
str = xmlResponseDoc.InnerXml; //str contains the SOAP Envelope

//parse the str using LoadXml method of XmlDocument class
// …
}
catch(Exception otherException)
{
//do something else
}
Posted by samar | 0 Comments
Filed under: ,

Granting EXECUTE privilege on group of stored procedures to a specified user

CREATE proc grants(@procs varchar(100),@user varchar(100)) as
declare curse cursor for select name from sysobjects where type='P' and name like @procs

OPEN CURSE
declare @proc varchar(100)
declare @stmt nvarchar(200)

fetch next from curse into @proc
while @@fetch_status=0
begin
set @stmt='grant execute on '+@proc+' to '+@user
exec SP_EXECUTESQL @STMT
print @stmt
fetch next from curse into @proc
end

close curse
deallocate curse
GO

grants 'sptest%','bnbuser'
go
Posted by samar | 0 Comments
Filed under:

Working with custom sections in app|web.config

Requirement may arise to define a custom section in app.config or web.config configuration file(s), to load a related but dynamic data for configuration purpose.

Following is an example of how this can be achieved; element contains a sub element where sections can be declared with
element. The important thing about custom sections is the ability to define multiple name-value pairs and load’em at once in the .NET code. Here is the sample configuration file with aforementioned (and henceforth defined custom) elements.



<configuration>
<configSections>
<section name="Partners" type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<Partners> <!-- custom section-->
<add key="000001" value="eBay Inc."/>
<add key="000002" value="Amars Inc."/>
</Partners>

<appSettings>
<add key="dbStr" value="Data Source=localhost;uid=user;pwd=password;database=master"/>
</appSettings>
</configuration>
Posted by samar | 0 Comments
Filed under:

Intercepting Downloads in ASP.NET

There might be general situations when developer needs to provide a download link to users for any kind of document that may include but not limited to doc, pdf, zip etc. However, the scenarios do exist when developer wants to authenticate the users before they could even reach at the source of the document, or there might be a requirement to log all the downloads performed on the website. Also the developer might not wish to give a direct URL of the document to any user at any time. Direct URLs may lead to unnecessary overhead, as the authors of other websites may provide a direct link of the document on their website.

It arises the need of a download interceptor that could control, record and monitor the activities of the downloads performed.

For implementing such an interceptor, all we need is the data entity for the documents to be presented to download and an ASPX page that will be requested instead of the original name of the document.

The provided URL for the document to download might look like the following on port 80, where documentId is the document ID or number, which the interceptor will use as reference to lookup the document name from the documents table.

http://yourHost/yourApp/download.aspx?documentId=1

Assuming the document table contains at least two fields, one the document’s ID and the other one its Name. Now let’s see how do we code the download.aspx and its code behind. The front end page doesn’t include anything, just leave it intact.

public class download : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
string document;

//retrieve static strings from the configuration file.
string connStr=System.Configuration.ConfigurationSettings.AppSettings["dbStr"];
protected string absUploadPath=System.Configuration.ConfigurationSettings.AppSettings["absPath"]+"\\upload",
uploadUrl=System.Configuration.ConfigurationSettings.AppSettings["siteUrl"]+"/upload";

private void Page_Load(object sender, System.EventArgs e)
{
//Authentication routine goes here. You can put your authentication checks here so that no one other than the allowed user accesses this section
if(!IsPostBack)
{
try
{
con=new SqlConnection(connStr);
con.Open();
cmd=new SqlCommand("select documentPath from tblDocuments where dId=@dId",con);
cmd.Parameters.Add("@dId",Request.QueryString["documentId"]);

object obj=cmd.ExecuteScalar();
document=(obj!=null)?obj.ToString():null;
//Authorisation routine can also be put to validate the user against individual documents, just as ACLs

if(System.IO.File.Exists(absUploadPath+"\\"+document) && document.Length!=0)
{
Response.ContentType="application/unknown";
Response.AppendHeader("Content-Disposition","attachment; filename="+document); //attach the file to force download
Response.WriteFile(absUploadPath+"\\"+document);
Response.Flush();
//User user=(User)Session["userDetails"]; //custom class that stores user information in the session
}
else
{
Response.Write("<font face=tahoma size=-1><b>The file you requested doesn't exist </b><br><br> Sit tight, You're being taken back to the User Section.");
Response.AddHeader ("Refresh", "3; URL=previousPage.aspx"); //redirect to the previous page after a delay of 3 seconds
}
}
//In case of any trouble redirect!
catch(SqlException sEx){Response.Write(sEx.Number + " " + sEx.Message); Response.AddHeader ("Refresh", "3; URL=previousPage.aspx");}
catch(Exception ex){Response.Write(ex.Message); Response.AddHeader ("Refresh", "3; URL=previousPage.aspx");}
finally{con.Close();}
}
}

}

The above discussed practice can be customised as per the requirements. The authentication and authorisation routines can be put into operation by retrieving the user information from the session or other state maintenance utility.

Sumit Amar
Posted by samar | 0 Comments
Filed under:

Selecting XML nodes defined with namespaces

While isolating nodes with custom namespace definition, it might be problematic to retrieve the nodes using XPath (SelectSingleNode or SelectNodes methods). Because if the target XML document contains a URN prefix in the node, that has to be defined and explicitly and specified in the SelectSingleNode call. Here is the way to get it into work.

XmlNamespaceManager nsmgr=null; //Declare Namespace manager to track all URNs and prefixes used in target document.

try
{
nsmgr=new XmlNamespaceManager(xdoc.NameTable); //xdoc contains the returned SOAP envelope if successful

nsmgr.AddNamespace("prfx", "http://MyURN.com/"); //add entry about the custom prefix

nsmgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); //add entry about default soap prefix available in the SOAP envelope.

}
catch(NullReferenceException nex){Console.WriteLine(nex.Message);} //In case the XML doc wasn’t accessible

XmlNode result = xdoc.SelectSingleNode("//prfx:Operation",nsmgr); //result will now contain the prfx:Operation element or attribute as the case may be.
Posted by samar | 0 Comments

HTA (HyperText Applications): Caveats and Features

Caveats:
1. Security: HTAs bypass the Internet Explorer's advanced settings to disable/enable active scripting, which leads to vulnerability in system to malfunction. However, since the HTAs interact with local system (using ActiveXObjects) for file/DB manipulation, the caveat is limited to the user's system. Also because browser doesn't come into picture for HTAs, use of SSL is not taken into consideration, unless the HTA is loaded with a remote frame (which perhaps defeats the purpose of HTA).
2. Icon: Individual HTA can not be associated with *an icon, if it's modified the icon takes over for all the HTAs in the system. However an icon can be put in the control menu of the title bar.
3. Porting: HTAs may NOT be transferred through email, because most of the antivirus systems consider HTAs as scripts that contain malicious code. It is so, because of HTAs' capabilities to have full control on system's file system (where they are being kept).


Features:
1. File System: HTAs provide strong file manipulation capabilities. VBScript users can make use Scripting.FileSystemObject in CreateObject method while J/avaScript users may instantiate ActiveXObject with the same component name to control file system.
2. WSH Support: HTAs are open to make use of Windows Scripting Host just as the direct VBS or JS files would. Common WSH operations (WScript.Shell) include Reading/writing file system, windows registry and devices (In case of WMI). Other WSH operations (WScript.Network) include Reading network information and mapping drives etc.
3. DB Access: HTAs can manipulate databases using SQLOLEDB or OLEDB Jet interfaces for almost all databases and text files (using text/csv drivers).
4. MS Office: HTAs can make use of COM to manipulate MS Office documents such as Excel, Word, Outlook. Manipulations include porting and formatting data, charts and images etc.
5. FTP Access: Seem less FTP Support is provided.
6. Splash Screen: HTA can be used to display a splash screen for few seconds while the whole application loads.
7. Context Menus: Regulation right click context menu (as appears in IE) can be disabled in HTA and a custom context menu can be displayed instead.
8. HTA:Application: element allows us to customise the HTA application, customisation includes setting/unsetting/modifying a control/sys menu, border specifications, icon, version, title/caption bar, scrolling, context menu and others. Making it all very handy.


<HTA:APPLICATION
ID = "objApp"
APPLICATIONNAME = "HTA App Name"
BORDER = "thick"
CAPTION = "yes"
ICON = "any.ico"
SHOWINTASKBAR = "yes"
SINGLEINSTANCE = "yes"
SYSMENU = "yes"
WINDOWSTATE = "normal"
SCROLL = "yes"
SCROLLFLAT = "yes"
VERSION = "1.0"
INNERBORDER = "yes"
SELECTION = "no"
MAXIMIZEBUTTON = "yes"
MINIMIZEBUTTON = "yes"
NAVIGABLE = "yes"
CONTEXTMENU = "yes"
BORDERSTYLE = "normal"
>


As you can see above, the HTA:Application element is an empty element and contains numerous useful attributes. Most of the attributes are self-explanatory. Setting SCROLLFLAT to true causes HTAs use Internet Explorer style of flat scrollbars. Elements, like frames, that have their own scrollbars inherit this style. For normal scrollbars this attribute can be set to false. ID objApp can be used in scripting language to manipulate the attributes etc.

Icon appears in the control/sys bar or the application. SINGLEINSTANCE will not allow users to spawn another window if one is already open. CAPTION, BORDER and INNERBORDER can be reset to create a splash screen like window.


Sumit Amar
Posted by samar | 0 Comments
More Posts Next page »
 
Page view tracker