Saturday, October 2, 2010

JQuery menu anchor tag click problem

Hi All,

Once again a new problem with another solution. If you have ever tried to create a JQuery menu whose click pops out another sub menu and you have to place an anchor tag with in that submenu, you wont find the anchor tag click to be working.

Suppose i have the following structure.

<div class="menu">
    <ul>
        <li><a href="#">My Parent Menu</a>
         <ul>
            <li><a href="myPage.aspx">My Title</a></li>
            <li><a href="#">another Title</a></li>
         </ul>
       </li>
    </ul>
</div>

and you need the internal UL to pop out on clicking external LI. The JQuery sample is.

$('.menu ul li').click(function () {
  submenu = $(this).find('ul');
  if (submenu.is(':visible'))
   submenu.slideUp(150);     
  else
                submenu.slideDown(200);         
  return false;
 });

So what you need to do is to stop propagation of external li item to the anchor tag by

$('.menu li ul li a').click(function(e) {
        e.stopPropagation();
    });

An now you can do your click and pop Ins/pop outs at the same time.

Happy Coding.

Click Server button problem in jquery Model popup ASP.NET

Hi All,

If you have ever used JQuery model popup with server side controls on it you might face problem when clicking a server button on it, That the server event is not fired when and hence you can not open perform any server activity inside that popup.

The reason is that JQuery models are designed in a way that they should contain a form tag as an ASP.net server page but when the popup appears div gets out from document object model and gets attached to the end of page and hence it never contained a form tag which stops "runat=server" to work so server events didn't gets fired.

The solution is very simple just add the model popup to the parent form and you are done. i have also attached the sample code.

jQuery(function() {
   var myDialog= jQuery("#DialogName").dialog({ 
                        // SET Properties here 
          });
  // Adding Dialog to Parent form will do the Job
  myDialog.parent().appendTo(jQuery("form:first"));
});


Also Take care of one thing that the addition of model dialog to page must b done inside the page it this is done in external javascript file it wont work.

Happy Coding.

Tuesday, September 7, 2010

Split view Controller, Calling Detail view controller from Navigation view controller.

You might find lots of Blogs and Books to use Split view controller in a normal way with one root view controller and a detail view controller like a really nice tutorial can be seen here. You might also find a tutorial that will tell you how to call different detail view controllers from root view controller here.

But when it comes to call detail view controller from a controller other then Root view controller help just diminish. As we can use navigation controller in root view controller that will navigate to a controller which is not defined in app delegate for split view controller then comes the real deal of calling it from last controller in navigation.

The solution that i proposed here is to use NSnotifications to broad cast a message with proper name and then use that message in detail view controller to call a function in detail view controller and for the detail item that is to be passed use the Object: parameter on NSnotification to send an object to it which can be utilized in detailview controller.

Lets check some code snippits for better elaboration.

Here is a root view controller didSelectRowatindexPath function from which mostly detail view controller is called but we need some navigation so i am calling a TestViewController by using navigation of root view controller.

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 int index = [indexPath row];
 
 Category *category = [categories objectAtIndex:index];
 
 
 TestViewController *shopList = [[TestViewController alloc] initWithNibName:@"TestViewController " bundle:[NSBundle mainBundle]];
 shopList.categoryId = category.categoryId;
 [[self navigationController]  pushViewController:shopList animated:YES];
 [shopList release];

}


Now to Reach to a test view controller from which a detail view controller needs to be called in the didSelectRowatindexPath function of this viewcontroller we will be broadcasting an NSTotification

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 int index = [indexPath row];
 
 [[NSNotificationCenter defaultCenter] postNotificationName:@"dealNotification" object:[article;

}

That all for a new controller in navigation controller. now we move to detail view controller where in ViewdidLoad an observer is added and the function that needs to be called is passed to selector.

- (void)viewDidLoad {

 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(iamcallingyou:) name:@"dealNotification" object: nil];
    [super viewDidLoad];
}

Now finally the function whose name is given in selector.

- (void) iamcallingyou:(NSNotification *)pNotification
{
 
 NSLog(@"hi");
// This is a Class Object that i have passed in to object parameter when broadcasting notifications.
 article = (Article *)[pNotification object];
  
 if (popoverController != nil) {
        [popoverController dismissPopoverAnimated:YES];
    } 
 

}


And we are done with it... do some memory management in final touches and we are good to go

Happy Coding.

Monday, September 6, 2010

Memory Exception EXC_BAD_ACCESS, Tracking with NSZombie

Hi All,

I am just a beginner to Objective C and I phone but Apple takes your brain out once you start coding for them and the biggest brainstorming occurs when its about the memory and its allocation / de allocation.

So i was stuck in same kind of exception and wasted many hours for that but then NSzombie helped me a lot actually when NSZombie is enabled the GDB is interreped when ever we try to access an object that is deallocated from memory.

Its just simple to Enable NsZombie.

1. Goto Executables in project tree


executable


2. Add a Name value pair NSZombieEnable and value equals to YES.


executable



Hope it will also help you,

Happy Coding.

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.