Saturday, January 30, 2010

LINQ queries for integer and string array

In this post i will show some basic queries which we can make on the array in .Net environment.

First of all we will see LINQ query for integer array.

 

   1:  int[] intArray = { 1, 5, 7, 15, 19, 20 };
   2:  var query = from i in intArray
   3:              where i % 5 == 0
   4:              select i;

 

In above example i had defined an integer array as intArray. above LINQ query will select all the integer value which can be divisible with 5.

So its output will be {5, 15, 20}

This was basically searching functionality. Now if you need to sum all the values within array, you can achieve it with below LINQ statement

   1:  int sum = intArray.Sum();

And it will give you sum of all the array

For average the array in LINQ you need to write

   1:  int avg = intArray.Average();

 

Now lets take another example of a string array.

   1:  string[] strArray = {"red", "blue","green", "black", "yellow" };
   2:  var query = from s in strArray
   3:              where s.StartsWith("b")
   4:              select s;

 

Now in this example i have an array of string containing various color name. Above LINQ query will select all the name that starting with be.

So its output will be {“blue”, “black”}

LINQ provide developers a great way to use logic that we can build in C# and LINQ will handle it.

There are much more functionality LINQ provides like concate, reverse, first, last, etc.

Google transliteration IME in 14 new indian languages - Fyoq News

Check out this article

 
 

Sent to you by Nirav Bhatt via Google Reader:

 
 

via Sci/Tech - Google News on 1/28/10


Little About (blog)

Google transliteration IME in 14 new indian languages
Fyoq News
Today Google India announced officially the availablity of Google transliteration in 14 languages. These fourteen Indian languages are Arabic, Bengali, Farsi (Persian), Greek, Gujarati, Hindi, Kannada, Malayalam, Marathi, Nepali, Punjabi, Tamil, ...
Google intros language translator applicationCIOL
Google launches applications to type in 14 languagesThe Hindu

all 16 news articles »

 
 

Things you can do from here:

 
 

Wednesday, January 27, 2010

Introduction to LINQ

Language Integrated Query (LINQ) is a great tool shipped with .net framework 3.5. With LINQ you can achieve a lot more functionality and save a lot of your development time.

What LINQ support?

LINQ to SQL Server: With LINQ you can directly connect to SQL server and write down your queries in C#. When you use LINQ to SQL classes, LINQ will automatically generate classes for your tables in the SQL server.

LINQ to XML: With LINQ to XML you can achieve XML programming in .Net framework.

LINQ to Dataset: With LINQ to Dataset you can connect LINQ to ADO.Net Databases

LINQ to Objects: With QINQ to Objects you can achieve any query on the collection of objects. This can help you to avoid loop for multiple conditions over a collection. You can use LINQ to Objects over Array, List etc.

Next article will be on basic LINQ queries.

Tuesday, January 19, 2010

Access Validation Controls with javascript

Asp.net Validation Controls:

Asp.net has many validation controls availables as native controls.this is the great way of validating INPUT controls at both   client side and server side.

some peoples hate this validation controls because they think that they are less managable from client side.but  this is not true.

when you  drop validation controls on the page and see SOURCE of that page. you can see that all validation stuff is shipped  as normal javascript variables. thus we can manage them from javascript easily.

i will show some useful methods/function in JAVASCRIPT  which may be  handy for us while using  validation controls .


(1) How to disable all validators:
  function DisaableAllValidators(sender)
  {

            var AllValidattors = new Array();
            AllValidators = Page_Validators;
            for (var i = 0; i < AllValidators.length; i++) {
                ValidatorEnable(AllValidators[i], false);
            }
 }
Here  Page_Validators is Asp.net generated array of validators.we can manipulate as we want in out javascript functions.
(2) Change validation messages:
 function ChangeValidationMessages()
 {

                var AllValidattors = new Array();
                AllValidators = Page_Validators;
                for (var i = 0; i < AllValidators.length; i++) {
                    AllValidators[i].errormessage = AllValidators[i].errormessage + "New";
                    AllValidators[i].innerHTML = AllValidators[i].innerHTML + "New";
                }           
 }
(3) Clear all validation Summaries:
 function ClearValidationSummaries()
 {

            var allSummaries = new Array();
            allSummaries = Page_ValidationSummaries;
            for (var i = 0; i < allSummaries.length; i++) {
                allSummaries[i].innerHTML = "";
            }
}
Here Page_ValidationSummaries is the Array of all validation summaries dropped on the page.you can manupulate all summaries using this array.
(4) Hide All validation messages:
   function HideAllValidators()
   {

            var AllValidattors = new Array();
            AllValidators = Page_Validators;
            for (var i = 0; i < AllValidators.length; i++) {
                if (AllValidators[i].display == 'Dynamic') {
                    AllValidators[i].style.display = 'none';
                }
                else {
                    AllValidators[i].style.visibility = 'hidden';
                }
            }
 }
(5)Force All validations to fired:
 function ForceAllValidation() {
            alert(Page_ClientValidate());
        }
Here Page_ClientValidate()  is the built-in function which is responsible to validate all validation controls on the page.
it accepts validationGroup as argument to validate  fire validation for particular validation group only.
(6)Force Single Validation to fired!:
   function ForceSingleValidation()
   {

            var tmpvalRequireMobile = document.all ? document.all["valRequireMobile"] : document.getElementById("valRequireMobile");
            ValidatorValidate(tmpvalRequireMobile);
            alert(tmpvalRequireMobile.isvalid);
    }
Here valRequireMobile Is ClientID of validator control and ValidatorValidate() is Built-in function which is accept validation control as argument and validate whether is is valid or not.

Thus,we can use Clientside validation library of validation controls to manepulate validation controls in custom javascript functions.



Thanks.

Wednesday, January 13, 2010

How to Use WCF Service in Web Application


Wcf Service:
There is new baby of microsoft  in the world.  called WCF service. But there is huge Question how to call it in webapplication. thoug it is as easy as we are doing with webservice.
there is a huge differance in the plateform on which webservice is built and on which WCF is service in built.
Differance:
The Main differance bet'n this two services (WebService/WCF) is   With WCF Service  SOAP messages can be transmitted over a variety of supported protocols including IPC (named pipes), TCP, HTTP and MSMQ. Like any distributed messaging platform,on the other hand in WebService SOAP message can only transmitted via HTTP.
How To Create WCF Service:
To Create WCF service Create 
1).Create  blank website 
2).Right-Click  > Add Item >WCF Service
 3). Add referance to
System.ServiceModel.
Three files will be created in solution .
A)  App_Code/IService.cs
Content:
using System.ServiceModel;// NOTE: If you change the interface name "IService" here, you must also update the reference to "IService" in Web.config.
[ServiceContract]
public interface IService
{
    [OperationContract]
    string DoWork();

}

B)  App_Code/Service.cs
Content:
using System;
using System.ServiceModel.Activation;
// NOTE: If you change the class name "Service" here, you must also update the reference to "Service" in Web.config.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class Service : IService
{
   public string DoWork()
    {

        return DateTime.Now.ToString();
    }
}
C) Service.svc
Content:
<%@ ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs" %>

And Following lines of Configuration will automatically added to Web.Config file of your web site.
<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="ServiceBehavior" name="Service">
        <endpoint address="" binding="wsHttpBinding" contract="IService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />   
  </system.serviceModel>
This are the steps to create WCF service.To call  WCF service in our application we have to Add bindings  in web.Config file & also have to create a class which acts  as proxy of WCF  service in our application.
How to Consume WCF service in WebApplication:
to call WCF service we have to add following service contract in our web.config file. please copy and paste below configuration tags  between  <system.serviceModel> </system.serviceModel> elements.
Service binding configuration:
 <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_IService" closeTimeout="00:01:00">
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:54464/SVCTest/Service.svc"
          binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService"
          contract="IService" name="WSHttpBinding_IService">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>
    </client>
Now we have done with configuration of WCF service configuration.now we have to create ClassLibrary which contains proxy class to call WCF service methods.
Steps to create  proxy is:
1) on solution Right-Click >Add New Project >Class Library.
2) Add Class and name it  ServiceCaller.cs.
3) Add Referance to  System.ServiceModel  in Class Library project.
4 ) Add following code in that class file.
namespace WCFServices
{
    [System.ServiceModel.ServiceContractAttribute(ConfigurationName = "IService")]
    public interface IService
    {

        [System.ServiceModel.OperationContractAttribute(Action = "http://tempuri.org/IService/DoWork", ReplyAction = "http://tempuri.org/IService/DoWorkResponse")] //This line is must
        string DoWork();
    }
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public partial class ServiceClient : System.ServiceModel.ClientBase<IService>, IService
    {

        public ServiceClient(){}
        public string DoWork()
        {

            return base.Channel.DoWork();
        }
    }
}
Finally now we are done with creating WCF service caller class.I have given sample code for service proxy and configuration elements.But you can also create configuration Using Command line Called svcutil.exe Automatically.
Steps to create configuration and proxy class using Command-line(svcutil.exe):
1) Open Visual Studio 2008 Command Prompt.
Service.cs and output.config will be automaticall create at
Program Files (x86)\Microsoft Visual Studio 9.0\VC.
you can use this Service.cs  as ServiceCaller and elements inside output.config as configuration elements for web.config file.
To call WCF service in our application is very easy now.
Just Create object of ServiceClient Class. and you will be able to call methos in WCF service.
Eg.
 protected void Page_Load(object sender, EventArgs e)
 {

        WCFServices.ServiceClient sc = new WCFServices.ServiceClient();
        string currentTime = sc.DoWork();
        Response.Write(currentTime);
        sc.Close();
        //Response.Write(DateTime.Now.ToString());

 }
Here we GO.
you can find more details of each and every class and terms and Namespace used here in following links.also can find more about making WCF service more secure from the referances given here.
Performance Comparision:
Consuming Wcf Service:
Hosting WCF Service in IIS:
Securing WCF Service:

Hope this will help you.

Thanks.


How to call WebService/ScriptService from javascript


Web service/Script Service:
With the release of .Net framework 3.5 they shipped a good way of communication with webservice.
Web service was also available in old version of .Net, but there was a lack of mechanism using which we can call web service using JavaScript. This new way of calling web service in JavaScript also called script services.
Web Method/Script Method:
As in web service we add [webmethod] attribute, t o call same web method in JavaScript you have to add [scriptmethod] attribute on the method.
[System.Web.Script.Services.ScriptMethod]   
    public string HelloWorld()
OR to make all method in the particular web service you can add [ScriptService] attribute above definition of web service.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
How Create Web Service/ScriptService:
It is simple to add web service using visual studio. When you add web service default template will be added in the solution. To make this web service to behave as scriptservice add Attribute [System.Web.Script.Services.ScriptService] on the WebService.cs Class.

How to consume web service (Script Service) using JavaScript:
To use webservice add referance of  WebService.asmx to ScriptManager.

(1)  <asp:ScriptManager ID="ScriptManager" runat="server">
        <Services>
            <asp:ServiceReference Path="~/WebService.asmx" InlineScript="true"/>
        </Services>
 </asp:ScriptManager>

(2)now on the page where you want to call web service add following script.

<script type="text/javascript" language="javascript">
        function CallHelloworld() {
            WebService. HelloWorld(OnSuccess, onFailed, null);
        }
        function OnSuccess(result) {
            alert(result);
        }
        function onFailed(err) {
            alert(err);
        }
</script>

How to consume web service (Script Service) Having SOAP Header using JavaScript:
For enhancing Security of the webservice some time we have to pass some sensitive information.
We have to pass this information in essence to call that method regardless of from where you are consuming it. It may from JavaScript or Server side code or in any other application.
How to set SOAP Header from server side code;

Suppose this is header added in the web service:

public class WebService : System.Web.Services.WebService
{
    public AuthHeader objAuthHeader = new AuthHeader();
    public class AuthHeader : SoapHeader
    {
        public string UserName;
        public string Password;
    }
.
.
.
And this is the method protected with that SOAP Header.
   
    [WebMethod]
    [SoapHeader("objAuthHeader")]
    public List<Company> GetEmployees()
    {
  if (objAuthHeader.Password == "MyPassword")
        {
            //Do Sensitive process
  }
    }

To Call this method we can use below code.

        localhost.WebService wc = new localhost.WebService();
        wc.AuthHeaderValue = new localhost.AuthHeader();
        wc.AuthHeaderValue.UserName = "MyName";
        wc.AuthHeaderValue.Password = "MyPassword";
        wc.GetEmployees();


How to set SOAP Header from Javascript/Client Side code;

We have to create a request object  in SOAP format with header value in it and then we have to send it to the server.in response thet soap request server will return result in XML Document format.to utilize output we have to process thet document in javascript.

Here is the requestTemplate:

function CallprotectedService() {

            var requestTemplate = '<?xml version=\"1.0\" encoding=\"utf-8\"?>' +
                                '<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">' +
                                  '<soap:Header>' +
                                    '<AuthHeader xmlns="http://InternetServices/WebServices/">' +
                                      '<Username>MyName</Username>' +
                                      '<Password>MyPassword</Password>' +
                                    '</AuthHeader>' +
                                  '</soap:Header>' +
                                  '<soap:Body>' +
                                     '<GetEmployee xmlns="http://InternetServices/WebServices/" />' +
                                  '</soap:Body>' +
                                '</soap:Envelope>';
            var request = new Sys.Net.WebRequest();
            request.set_url('../WebService.asmx');
            request.set_body(requestTemplate);
            request.set_httpVerb('POST');
            request.get_headers()['Content-Length'] = requestTemplate.length;
            request.get_headers()['SOAPAction'] = "http://InternetServices/WebServices/GetEmployees";
            request.get_headers()['Content-Type'] = 'text/xml; charset=utf-8';
            request.add_completed(onComplete);
            request.invoke();
        }

//Here is the function in which you have to traverse XML document to utilize //response returned by SOAP request.

function onComplete(response, args) {
            var contentType = response.getResponseHeader('Content-Type');
            if (contentType.startsWith('text/xml')) {
                result = response.get_xml();
            }
            else {
                result = response.get_responseData();
            }
            alert(result.documentElement.getElementsByTagName('GetEmployeesResult')[0].firstChild.childNodes[0].text);           
        }


While creating service please keep in mind that SOAP request template is case sensitive and make sure you have concatenation it properly.


Size of scripts exposed when you drop Script Manager on the Page is 400kb.please consider this when you implement in your application.

Hope this will help you.

Thanks.