Wednesday, August 25, 2010

Calling WCF Service from your I PAD/ i Phone Application (Objective C)

Last Days i have been assigned a task to call an WCF service from an I PAD Application. For all the .Net Programmers this thing is quite simple just to add a reference and Job's done but its not that simple in Objective C we need to create a raw request and then a get a Response. Yet again the response is in raw format as well so we need to do some parsing on it as well.

Again the Tool that helped me lot is Fiddler. As you know that asmx service request and response can easily be obtained by just opening the service URL in browser but its not the case with WCF service you need to create request by your self.

In order to make the job simpler and understandable i used two things


  • Call the Web service in a c# web application and check all the parameters that it accepts. so that you get an idea of what needs to be sent in request

  • Secondly Open up fiddler and run the web application so that we can get the Request XML that is created when calling the web service

So we are done with the Environment part now lets start some Objective C portion.

First Create a simple View based application. open the Xib file of view controller place a button over there.

Navigate to the header file of view controller create an Outlet and an IBAction. Then register that action to the button.

Now we come to the .M file of view controller, suppose the function name was buttonClicked we create a string in that and paste the Request from fiddler with little modifications in that.

Note that i have passed three types of parameters to the Request
1. Array of String
2. Boolean
3. Integer Value


Also You will notice two tags
FUNCTION_NAME
PARAMETER_NAME

These two tags specify the function to be called from service and the list of parameters that is passed in this case i have passed a complex type parameter which contains from other normal parameters.



-(IBAction) buttonClicked:(id)sender{
 
 
 NSString *soapMsg = [NSString stringWithFormat:
       @"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
       "<SOAP-ENV:Envelope \n"
       "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" \n"
       "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n" 
       "xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" \n"
       "SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" \n"
       "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"> \n"
       "<SOAP-ENV:Body> \n"
       "<FUNCTION_NAME xmlns=\"http://tempuri.org/\">"
       "<PARAMETER_NAME xmlns:a=\"http://schemas.datacontract.org/2004/07/BBB.Model\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">"
       "<a:_x003C_BrandName_x003E_k__BackingField i:nil=\"true\" xmlns:b=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\"/>"
       "<a:_x003C_DisplayOnWeb_x003E_k__BackingField>false</a:_x003C_DisplayOnWeb_x003E_k__BackingField>"
       "<a:_x003C_IsFeatured_x003E_k__BackingField>false</a:_x003C_IsFeatured_x003E_k__BackingField>"
       "</PARAMETER_NAME>"
       "</FUNCTION_NAME> \n"
       "</SOAP-ENV:Body> \n"
       "</SOAP-ENV:Envelope>"];
 
 
 //NSLog(soapMsg);
 NSURL *url = [NSURL URLWithString: @"http://SERVICE_URL/Service.svc"];
 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
 
 NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMsg length]];
 [req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
 [req addValue:@"http://tempuri.org/ICommerceService/FUNCTION_NAME"
   forHTTPHeaderField:@"SOAPAction"]; 
 [req addValue:msgLength forHTTPHeaderField:@"Content-Length"];
 //---set the HTTP method and body--- 
 [req setHTTPMethod:@"POST"]; 
 [req setHTTPBody:[soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
 conn = [[NSURLConnection alloc] initWithRequest:req delegate:self]; if (conn) {
  webData = [[NSMutableData data] retain];
 }
 
}

-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
 [webData setLength: 0];
} 

-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data { 
 [webData appendData:data];
}
-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error {
 [webData release]; 
 [connection release];
}

-(void) connectionDidFinishLoading:(NSURLConnection *) connection { 
 
 NSLog(@"DONE. Received Bytes: %d", [webData length]);
 NSString *theXML = [[NSString alloc]
      initWithBytes: [webData mutableBytes] 
      length:[webData length] 
      encoding:NSUTF8StringEncoding];
 //---shows the XML--- 
 //NSLog(theXML);
 [theXML release];
 [connection release];
 [webData release];
}

The function will give the response in connectionDidFinishLoading which can then be parsed by any XML parser.

The Best XML parser that i found is COCOA With Love.

Hope It Helps.

Happy Coding....

Thursday, July 22, 2010

Show Popup when Application is installed for First time - Iphone

Hi All,

You might have seen the applications in I-phone that shows a welcome message only when you install the application for instance you might think that there is a Database at back end which is used to save some constants but most apps are without any database.

The most interesting way that i found in getting a popup message on application install is using NSUserDefaults this contains a set of constants that are related to a particular user. so what we will do is that when ever the user launches application for the first time we will add a new constant in NsUserdefault and from then on every time we will check the value of it so for every next time the value will be saved with constant name and hence no action will be taken.

Let me share a code snippet with you.

 1 - (void)viewDidLoad {
 2  int x = [[NSUserDefaults standardUserDefaults] integerForKey:@"CONSTANT_NAME"];
 3  if( x == 1 )
 4  {} 
 5  else
 6  {
 7   [[NSUserDefaults standardUserDefaults]setInteger:1 forKey:@"CONSTANT_NAME"];
 8   [[NSUserDefaults standardUserDefaults]synchronize]; 
 9   
10   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@
"Thank you for installing the iPhone application."
 delegate:self cancelButtonTitle:@"Later" otherButtonTitles:@"Okay" ,nil];
11   [alert show];
12   [alert release];
13  }
14     [super viewDidLoad];
15 }



Line 1: The function viewdidLoad will be called when the View controller is loaded.
Line 2: The first thing it will do is to check the constants name and save its value to a variable.

Line 3: A conditional statement will check if the value exists in constant.
Line 7: Save some value in NsUserDefault.
Line 10: Show an alert view as the constant is not set.

Happy coding.

Wednesday, April 28, 2010

CS 2008.5 Navigation in Telligent community 5

To restore the CS2008.5 navigation - where you specified navigation through the control panel.

1. Make a backup of your existing ~/utility/headerfragments/core/groupnavigation.ascx ~/themes/fiji/theme.config files and ~/controlpanel/settings/themeconfiguration.aspx files
2. Replace the ~/utility/headerfragments/groupnavigation.ascx file with the below


<%@ Control Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="CommunityServer.Components"%>

<script runat="server">
   
protected ThemeConfigurationData themeData = CSContext.Current.ThemePreviewCookie.IsPreviewing(SiteThemeContext.Instance()) ? ThemeConfigurationDatas.GetThemeConfigurationData(SiteThemeContext.Instance(), "fiji", CSContext.Current.ThemePreviewCookie.PreviewID, true) : ThemeConfigurationDatas.GetThemeConfigurationData(SiteThemeContext.Instance(), "fiji", true);

public bool IsOneBarNavigation()
{
    return themeData.GetBoolValue("onebarnavigation", false);
}
   
</script>

<div id="ParentGroupListContainer" class="parent-container" style="width: 100%" runat="server">
<div class="parent-sub-container">
    <CSControl:NavigationList runat="server" Property="navigationItems" Theme="<%= themeData.ThemeName %>" Level="0" RenderChildrenInContextMenu="false"  >  
        <LeaderTemplate>
            <div class="navigation-list-header"></div>
            <ul class="navigation-list parent">
        </LeaderTemplate>
        <ItemTemplate>
            <CSControl:ConditionalContent runat="server">
                <ContentConditions><CSControl:CSLinkPropertyValueComparison runat="server" ComparisonProperty="IsSelected" Operator="IsSetOrTrue" /></ContentConditions>
                <TrueContentTemplate><li class="navigation-item selected entry"></TrueContentTemplate>
                <FalseContentTemplate><li class="navigation-item entry"></FalseContentTemplate>
            </CSControl:ConditionalContent>
            <CSControl:CSLinkData runat="server" LinkTo="Link" Property="Text" />
        </ItemTemplate>
        <TrailerTemplate>
            </ul>
            <div class="navigation-list-footer"></div>
        </TrailerTemplate>
    </CSControl:NavigationList>
</div>
</div>
<CSControl:NavigationList runat="server" Theme="<%= themeData.ThemeName %>"  Property="navigationItems" Level="1" ShowHeaderFooterOnNone="false">  
    <DisplayConditions><CSControl:CustomCondition CustomResult="<%# !IsOneBarNavigation() %>" runat="server" /></DisplayConditions>
    <NoneTemplate></NoneTemplate>
    <HeaderTemplate>
        <div id="ChildGroupListContainer">
            <div class="navigation-list-header"></div>
            <ul class="navigation-list child">
    </HeaderTemplate>
        <ItemTemplate><CSControl:CSLinkData runat="server" CssClass="navigation-item entry" Tag="Li" LinkTo="Link" Property="Text" /></ItemTemplate>
        <FooterTemplate>
            </ul>
            <div class="navigation-list-footer"></div>
        </div>
    </FooterTemplate>
</CSControl:NavigationList>


3. Add the following into ~/themes/fiji/theme.config

<propertyGroup resourceName="Navigation" resourceFile="ThemeResources.xml">
    <property id="navigationItems" resourceName="NavigationItems" resourceFile="ThemeResources.xml" dataType="Custom" descriptionResourceName="NavigationItems_Description" descriptionResourceFile="ThemeResources.xml" controlType="CommunityServer.Controls.DynamicNavigationCustomControl, CommunityServer.Controls" maximumDepth="2" />
</propertyGroup>


4. Add the following into the <script> block at the top of /controlpanel/settings/themeconfiguration.aspx - this is to work around an issue with the Dynamic Navigation Configuration Control.
function ContentFragments_Update(cfConfigurationData) {
    if (cfConfigurationData != null && _contentFragments_currentContentFragmentId) {
        var cfState = document.getElementById('ContentFragments_' + _contentFragments_currentContentFragmentId);
        if (cfState)
            cfState.value = cfState.value.split(':')[0] + ':' + cfConfigurationData;
    }

   _contentFragments_currentContentFragmentId = null;
}     

Taken from the post of Alex Chrome "http://telligent.com/community/ideas/f/532/t/1057775.aspx"


Happy coding.

Wednesday, March 10, 2010

Screen Scrapping with HTTP request.

Hi All,

This posts is about the screen scrapping with out using any third party tool by using HttpWebRequest object.

So guys download fidler 2 here to get started. "http://www.fiddler2.com/fiddler2/"

Open up fidler 2 and click launch IE button in the top right corner. when the browser is launched open up the URL in the browser which needs to be scrapped.

and click on the inspector tab in right top column. there you will see several tabs of header , text view , web form for the request generated.
and in the right bottom column you will notice response in various formats select the tab web view in the bottom.

Create a .net application write the following code in MyPage.aspx.cs file

strURL = "http://www.rppsales.com/Properties.aspx";
string startDate = DateTime.Now.ToShortDateString();
string endDate = DateTime.Now.AddDays(1).ToShortDateString();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
request.Method = "POST";
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(new Uri(strURL), new Cookie("cookieName", "CookieValue"));


In this piece of code you will notice that i am using a cookie container for adding cookies that are made while requesting the site. you can check the cookies in Request > header Tab of filder under the tree view cookies / login

When the cookies are placed in the container we will try getting the request data to get that open up the second tab textview of fidler and use it in the code like.

string postData = "__EVENTTARGET=&__EVENTARGUMENT=&__LASTFOCUS="; //Paste data of textview here in double qoutes

then you have to post the data and will read the response. by using the following peice of code.

byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
this1.Text = ((HttpWebResponse)response).StatusDescription;
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.

this1.Text += responseFromServer;
////Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();



At this stage the response of the server is in your pocket. Apply regular expression to extract the data that you need. and save it any where you want.

Happy Coding.

Cheers.

Tuesday, March 9, 2010

Action Script 3.0 and .NET --- A Bridge

hi All,

In this post i will use AMF.net to create a bridge between action script(AS) and .NET code.

as an over view we will create the front end of the application in action script and will call the .net classes which are connected to the Database and will get the results back to action script after that we will be parsing the results to display in AS.

Step 1:

Create a .NET class library project with a class defined in it. Let us call it "MyClass"

namespace MyClasses
{
    public class MyClass
    {

        #region Constructor
        public MyClass()
        {

        }

        #endregion

        public static List<myclass> getAllNotes()
        {

            SqlParameter[] prams = null;
            List<myclass> words = new List<myclass>();
            IDataReader reader = null;

            using (DbManager db = DbManager.GetDbManager())
            {
                try
                {
                    // DB logic to return a List 
                }
                catch (Exception)
                {
                    // Exception logging needed
                }
                finally
                {
                    if (reader != null)
                        reader.Close();
                }
                return MyClass;
            }
        }
    }
}


After the class is done build the library project and add reference of it to the ASP.net Web site.

Step 2:

http://amfnet.openmymind.net/ Go to the URL and download the AMF.net classes and follow the first two steps mentioned in http://amfnet.openmymind.net/howto/index.php.

Step 3:

As we will be using AS 3.0 so we can not use the step 3 and 4 code mentioned in above link.

Create a flash application and write the following code in MXML file

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
backgroundColor="#FFFFFF"
applicationComplete="init();">
<mx:Script>
<![CDATA[
import mx.messaging.channels.StreamingAMFChannel;

import flash.net.Responder;

import mx.collections.ArrayCollection;
import mx.controls.Label;

private var rs:RemotingService;
private var _myArrayCollection:ArrayCollection;


private function init():void

{


rs = new RemotingService("http://localhost:50020/MyWeb/gateway.php");

var responder:Responder = new Responder(onResult, onFault);

var params:Object = new Object();

params.arg1 = "1";


rs.call("MyClasses.MyClass, Library.getAllNotes", responder);



}

private function onResult(result:Object):void

{

trace(result);

var s:String = "";


var length:int = result.length;
var tempArray:Array = [];



for(var i:int=0; i<length; i++)

{

s += result[i].word + " " + result[i].Property1;
s += result[i].word + " " + result[i].Property2;
//var tempObj:Object = {
//name:result[i].word,
//birthday:result[i].WordCategory
//}


//tempArray.push(tempObj);

}

myLabel.text = s.substring(0,50);
//_myArrayCollection = new ArrayCollection(tempArray);


}


private function onFault(fault:Object):void

{

trace(fault.toString());

}


]]>
</mx:Script>
<mx:Label id="myLabel" visible="true" x="200" y="150" color="#111111" text="thisss" >

</mx:Label>
<mx:Text id="myText" x="200" y="550" >

</mx:Text>
</mx:Application>




Step4:

In the above code the highlighted region is to be replaced with fully Qualified name that is "NameSpace.ClassName, LibararyName.FunctionToBeCalled"


Step 5:

rs.Call will have all the parameters that will be send to the function if the function accpets parameters.

Step 6:

In the function onResult() we will get the response object as in the above case we will be having a list which we will parse to show the desired result in string.


Hope it simplifies the Things

Happy coding.

Wednesday, February 17, 2010

Maintain Tab Position in AJAX tab control

there can be some time when AJAX tab control will open the default tab after postback in some other tab here is a sinple solution for it.

Write a javascript function
function OnChanged(sender, args) {
sender.get_clientStateField().value = sender.saveClientState();
}

Call this in TabContainer like.
<Ajax:TabContainer runat="server" EnableViewState="true" OnClientActiveTabChanged="OnChanged">

and you are done.

Happy Coding.

Monday, February 15, 2010

creating week view calendar.

here is a very simple week view calendar in C#.net

<table cellspacing="0" cellpadding="2" border="0" style="border: 1px solid White;
    width: 640px; height: 390px; font-size: 9pt; font-family: Verdana; color: Black;
    background-color: White; border-collapse: collapse;" title="Calendar" id="ctl00_content_ctl00_fragment_2698_ctl00_Calendar1">
    <tbody>
        <tr>
            <td style="border: 4px solid Black; background-color: White;" colspan="7">
                <table cellspacing="0" border="0" style="color: rgb(51, 51, 153); font-family: Verdana;
                    font-size: 12pt; font-weight: bold; width: 100%; border-collapse: collapse;">
                    <tbody>
                        <tr>
                            <td valign="bottom" style="color: rgb(51, 51, 51); font-size: 8pt; font-weight: bold;
                                width: 15%;">
                                <asp:linkbutton id="lbtnPrev" runat="server" onclick="lbtnPrev_Click">Previous</asp:linkbutton>
                            </td>
                            <td align="center" style="width: 70%;">
                                <asp:literal runat="server" id="ltMomthYear"></asp:literal>
                            </td>
                            <td valign="bottom" align="right" style="color: rgb(51, 51, 51); font-size: 8pt;
                                font-weight: bold; width: 15%;">
                                <asp:linkbutton id="lbtnNext" runat="server" onclick="lbtnNext_Click">Next</asp:linkbutton>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </td>
        </tr>
        <tr>
            <th align="center" style="font-size: 8pt; font-weight: bold;" scope="col" abbr="Monday">
                Mon
            </th>
            <th align="center" style="font-size: 8pt; font-weight: bold;" scope="col" abbr="Tuesday">
                Tue
            </th>
            <th align="center" style="font-size: 8pt; font-weight: bold;" scope="col" abbr="Wednesday">
                Wed
            </th>
            <th align="center" style="font-size: 8pt; font-weight: bold;" scope="col" abbr="Thursday">
                Thu
            </th>
            <th align="center" style="font-size: 8pt; font-weight: bold;" scope="col" abbr="Friday">
                Fri
            </th>
            <th align="center" style="font-size: 8pt; font-weight: bold;" scope="col" abbr="Saturday">
                Sat
            </th>
            <th align="center" style="font-size: 8pt; font-weight: bold;" scope="col" abbr="Sunday">
                Sun
            </th>
        </tr>
        <tr>
            <asp:literal runat="server" id="ltDays"></asp:literal>
        </tr>
    </tbody>
</table>

Now for the srever side events

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            loadCurrentWeek(DateTime.Now);
    }

    private void loadCurrentWeek(DateTime dateofWeek)
    {
        StringBuilder sb = new StringBuilder();
        DayOfWeek day = dateofWeek.DayOfWeek;
        int days = day - DayOfWeek.Monday;
        DateTime start = dateofWeek.AddDays(-days);
        DateTime end = start.AddDays(6);
        ViewState["start"] = start;
        ViewState["end"] = end;
        ltMomthYear.Text = start.ToString("ddd dd MMM") + " to " + end.ToString("ddd dd MMM");

        for (int i = start.Day; i <= end.Day; i++)
        {
            sb.Append("<td align='center' style='color: Black; width: 14%;'>");
            sb.Append("<a href='javascript:void(0);'>");
            sb.Append(i);
            sb.Append("</a>");
            sb.Append("</td>");
        }
        ltDays.Text = sb.ToString();
    }
    protected void lbtnNext_Click(object sender, EventArgs e)
    {
        if (ViewState["end"] != null)
        {
            DateTime dt = Convert.ToDateTime(ViewState["end"]);
            DateTime next = dt.AddDays(1);
            loadCurrentWeek(next);
        }

    }
    protected void lbtnPrev_Click(object sender, EventArgs e)
    {
        if (ViewState["start"] != null)
        {
            DateTime dt = Convert.ToDateTime(ViewState["start"]);
            DateTime prev = dt.AddDays(-2);
            loadCurrentWeek(prev);
        }
    }


You are done with Weekly calendar :)

Happy coding.