Saturday, December 25, 2010

Paging Sorting Searching in MySQL Procedure

Hi All,

Lets do some mySQL programming in the last post i have shown how to do custom pagination from jQuery Data table and today i will share the procedure that i called at the back end to do the pagination stuff this one is in mySQL

USE `Database_Name`;

DROP procedure IF EXISTS `up_GlobalSearch`;



DELIMITER $$

USE `Database_Name`$$

CREATE PROCEDURE `scientestdb`.`up_GlobalSearch` (

IN pFreeText varchar(200), 

IN pStartRecord int, 

IN pSize int, 

IN pSortColumn varchar(20),

IN pSortDirection varchar(20)

)

BEGIN





SET @q := concat('select * from Table_Name where MATCH (Column_Name1,Column_Name2) AGAINST (\'', pFreeText ,'\'  IN BOOLEAN MODE)  ORDER By ', pSortColumn, ' ' , pSortDirection, ' limit ?,?');

PREPARE stmt1 FROM @q;

SET @recStrt = pStartRecord;

SET @recCount = pSize;

EXECUTE stmt1 USING @recStrt, @recCount;





END

$$



DELIMITER ;

Hope it helps.

Happy Coding.

Regards,
U

Thursday, December 16, 2010

Extending jQuery Datatable with server side processing and pagination.

Hi All,

Once again i came up with a blog for jQuery Datatable as i really liked this control and love to extend its functionality for .NET, in my previous blog i have bound jQuery Data table with dataset at once which might not be very useful then data is so large as fetching complete data in one hit is not a good job.

So Today we will do some bServerSide processing and make this data table more useful in fetching records from database with pagination and sorting enabled i am still not able to coupe with free text search in returned results but ill share that soon as well.

first step would be to create a handler / web service which we would be passing in the argument sAjaxSource of datatable.

Remember that the response should be a JSON formated text as datatable only reads JSON in adata parameter.

Lets start with the Handler.

<%@ WebHandler Language="C#" Class="Search" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Linq;
using System.Data;
using DAL.Modules;
using DAL;

public class Search : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        // Those parameters are sent by the plugin
        var iDisplayLength = int.Parse(context.Request["iDisplayLength"]);
        var iDisplayStart = int.Parse(context.Request["iDisplayStart"]);
        var iSortCol = int.Parse(context.Request["iSortCol_0"]);
        var iSortDir = context.Request["sSortDir_0"];


        IEnumerable<SearchResults> myResults = SearchResults.GetResults(iDisplayStart, iDisplayLength);

        // Define an order function based on the iSortCol parameter
        Func<SearchResults, object> order = rslt =>
        {
            if (iSortCol == 0)
                return rslt.Project_Name;
            else if (iSortCol == 1)
                return rslt.Project_Goal;
            else if (iSortCol == 2)
                return rslt.Proposed_Budget;
            else if (iSortCol == 3)
                return rslt.Status;
            else
                return rslt.Creation_Date;
        };

        // Define the order direction based on the iSortDir parameter
        if ("desc" == iSortDir)
        {
            myResults = myResults.OrderByDescending(order);
        }
        else
        {
            myResults = myResults.OrderBy(order);
        }


        // Remove Skip and Take when doing Custom Pagination from Database. 
        var result = new
        {
            iTotalRecords = myResults.Count(),
            iTotalDisplayRecords = myResults.Count(),
            aaData = myResults
                .Select(p => new[] { p.Project_Name, p.Project_Goal, p.Proposed_Budget, p.Status, p.Creation_Date, p.View_Details })
                .Skip(iDisplayStart)
                .Take(iDisplayLength)

        };

        var serializer = new JavaScriptSerializer();
        var json = serializer.Serialize(result);
        context.Response.ContentType = "application/json";
        context.Response.Write(json);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}


So parsing JSON would require a class structure.

public class SearchResults
{
    public string Project_Name { get; set; }
    public string Project_Goal { get; set; }
    public string Status { get; set; }
    public string Proposed_Budget { get; set; }
    public string Creation_Date { get; set; }
    public string View_Details { get; set; }

    public static IEnumerable<SearchResults> GetResults(int RecordId, int count)
    {
        DataSet ds = null;// Get you Dataset from Database by passing the two parameters for pagination. 

        if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                yield return new SearchResults
                {
                    Project_Name = Helper.ParseString(dr["Project_Name"]),
                    Project_Goal = Helper.ParseString(dr["Project_Goal"]),
                    Status = Helper.ParseString(dr["Status"]),
                    Proposed_Budget = Helper.ParseString(dr["Proposed_Budget"]),
                    Creation_Date = Helper.ParseString(DateTime.Now),
                    View_Details = "<a href='#'>View</a>"
                };
            }
    }
}

Now its time for the final step calling it in ASPX page.

the javascript for table would be

<script type="text/javascript">
        $(function () {
            $('#.datatable').dataTable({
                'bServerSide': true,
                "iDisplayLength": 2,
                "sPaginationType": "full_numbers",
                'sAjaxSource': '/Handlers/Search.ashx',
                "bFilter": false
            });
        });
    </script>

now finally we come to the last step which all of you must be familiar of is the HTML table which will turn into the jQuery Datatable.

<table cellpadding="0" cellspacing="0" border="0" class="datatable">
                    <thead>
                        <tr>
                            <th>
                                Project Name
                            </th>
                            <th>
                                Project Goal
                            </th>
                            <th>
                                Proposed Budget
                            </th>
                            <th>
                                Status
                            </th>
                            <th>
                                Creation Date
                            </th>
                            <th>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td colspan="5" class="dataTables_empty">
                                <img alt="Please Wait..." src="/images/loader.png" />
                            </td>
                        </tr>
                    </tbody>
                </table>

That's All if you find any query please leave a comment.

Happy Coding.

Wednesday, December 8, 2010

Get All Days/Months/Years/Quarters with in Two dates.

Hi All,

Today i am feeling soo great as i finally got what i needed the function that i am going to show now will return all the Dates with in two dates but wait its not this simple, i can have periods defined like difference would be in weeks / Months / Years / Quarters and so on....

What it will return in end is Minimum Date of reporting period Maximum date of reporting period and name of that Period.

CREATE FUNCTION [dbo].[GetReportingPeriods] (
  @StartDate DATETIME,
  @EndDate   DATETIME,
  @type varchar(20)
)
RETURNS @A TABLE (
  stdate datetime,eddate datetime, PartName varchar(30)
)
AS
BEGIN
/******************************************************************************
 * Author:      USMAN SHABBIR 
 * Create Date: 2010-11-20
 * Description: Create a table of dates between @StartDate and @EndDate
 *****************************************************************************/
  if @type = 'daily'
 begin 
  ;with cte as 
  ( select CONVERT(DATETIME,@startDate) AS DATE 
  UNION ALL 
  select Dateadd(dd,1,DATE) as date 
  from cte   
  where date <= @endDate - 1 
  )  
 
  insert into @a
  SELECT DATE, DATE + 1 - 1, 'Day ' + CAST(DatePart(dd, DATE) as varchar(10))  as Week_NO_Of_Year
  FROM CTE
  --Group by 'Day ' + CAST(DatePart(dd, DATE) as varchar(10))
  order by (DATE) ASC
  
  OPTION (MAXRECURSION 0)
 end

 else if @type = 'Weekly'
 begin 
  ;with cte as 
 ( select CONVERT(DATETIME,@startDate) AS DATE 
 UNION ALL 
 select Dateadd(dd,1,DATE) as date 
 from cte   
 where date <= @endDate - 1 
 )  
 
  insert into @a
  SELECT MIN(DATE), MAX(DATE), 'Week ' + CAST(DatePart(ww, DATE) as varchar(10))  as Week_NO_Of_Year
  FROM CTE
  Group by 'Week ' + CAST(DatePart(ww, DATE) as varchar(10))
  order by MIN(DATE) ASC
  
  OPTION (MAXRECURSION 0)
 end
 else if @type = 'Monthly'
  begin 
  
   ;with cte as 
 ( select CONVERT(DATETIME,@startDate) AS DATE 
 UNION ALL 
 select Dateadd(dd,1,DATE) as date 
 from cte   
 where date <= @endDate - 1 
 )  
  insert into @a
  SELECT MIN(DATE), MAX(DATE), CAST(DATENAME(month, DATE) as varchar(10))  as Week_NO_Of_Year
  FROM CTE
  Group by CAST(DATENAME(month, DATE) as varchar(10))
  order by MIN(DATE) ASC
  
  OPTION (MAXRECURSION 0)
 end
 else if @type = 'quarterly'
  begin 
  
 ;with cte as 
 ( select CONVERT(DATETIME,@startDate) AS DATE 
 UNION ALL 
 select Dateadd(dd,1,DATE) as date 
 from cte   
 where date <= @endDate - 1 
 )  
  insert into @a
  SELECT MIN(DATE), MAX(DATE), 'Quarter ' + CAST(DatePart(QQ, DATE) as varchar(10))  as Week_NO_Of_Year
  FROM CTE
  Group by 'Quarter ' + CAST(DatePart(QQ, DATE) as varchar(10))
  order by MIN(DATE) ASC
  
  OPTION (MAXRECURSION 0)
 end
 else if @type = 'yearly'
  begin 
  
 ;with cte as 
 ( select CONVERT(DATETIME,@startDate) AS DATE 
 UNION ALL 
 select Dateadd(dd,1,DATE) as date 
 from cte   
 where date <= @endDate - 1 
 )  
  insert into @a
  SELECT MIN(DATE), MAX(DATE), 'year ' + CAST(DatePart(yy, DATE) as varchar(10))  as Week_NO_Of_Year
  FROM CTE
  Group by 'year ' + CAST(DatePart(yy, DATE) as varchar(10))
  order by MIN(DATE) ASC
  
  OPTION (MAXRECURSION 0)
 end

  RETURN;
END



Hope it will help some one the same way as it did to me :)

Happy coding.

Kill all connections of a Database SQL server 2008

Hi All,

I was just trying to restore a DB and it was giving me error of Database in use so can not be restored. I googled a bit and found a nice solution so decided to share with you guys.

SET NOCOUNT ON
DECLARE @DBName varchar(50)
DECLARE @spidstr varchar(8000)
DECLARE @ConnKilled smallint
SET @ConnKilled=0
SET @spidstr = ''

Set @DBName = 'DATABASE_NAME'
IF db_id(@DBName) < 4
BEGIN
PRINT 'Connections to system databases cannot be killed'
RETURN
END
SELECT @spidstr=coalesce(@spidstr,',' )+'kill '+convert(varchar, spid)+ '; '
FROM master..sysprocesses WHERE dbid=db_id(@DBName)

IF LEN(@spidstr) > 0
BEGIN
EXEC(@spidstr)
SELECT @ConnKilled = COUNT(1)
FROM master..sysprocesses WHERE dbid=db_id(@DBName)
END

It worked like charm hope you enjoy it as well.

Happy Coding.

Sunday, October 3, 2010

Simplest way to use JQuery DataTable in ASP.net (C#)

Hi All,

Today i will be using JQuery dataTable in ASP.net c# code without any 'bProcessing' , 'bServerSide' and 'sAjaxSource'.

First of All what is Jquery Datatable, just Click and find out :).

After getting the basic structure of JQuery datatable you may find that all the server side examples on site is in PHP and the stuff done for ASP.net seems so difficult nor such newbies like me. so lets talk about a simpler solution.

First we create a simple HTML table. and the place where data will get populated just add an ASP Literal control. :)

<table class="datatable">
                        <thead>
                            <tr>
                                <th class="bSortable">
                                    <input type="checkbox" class="checkbox select-all" />
                                </th>
                                <th>
                                    First Name
                                </th>
                                <th>
                                    Middle Name
                                </th>
                                <th>
                                    Last Name
                                </th>
                               </tr>
                        </thead>
                        <tbody>
                            <asp:Literal runat="server" ID="ltData"></asp:Literal>
                        </tbody>
                    </table>


Now on the server side write a simple function to populate the literal with required data.

private void loadGrid()
    {
        StringBuilder sb = new StringBuilder();
        DataTable dt = MyData.GetAllUserData();
        if (dt != null)
            if (dt.Rows.Count > 0)
                foreach (DataRow dr in dt.Rows)
                {

                    sb.Append("<tr>");
                    sb.Append("<td>");
                    sb.Append("<input type='checkbox' class='checkbox' />");
                    sb.Append("</td>");
                    sb.Append("<td>");
                    sb.Append((dr["vchFirstName"]));
                    sb.Append("</td>");
                    sb.Append("<td>");
                    sb.Append((dr["vchMiddleName"]));
                    sb.Append("</td>");
                    sb.Append("<td>");
                    sb.Append((dr["vchLastName"]));
                    sb.Append("</td>");
                   
                    sb.Append("</tr>");

                }

        ltData.Text = sb.ToString();

    }

For initializing the data table you can refer to the site or use the following code and write it in document.ready() function of jQuery.

function LoadTable() {
 $('.datatable').dataTable({
  'bLengthChange': true,
  'bPaginate': true,
  'sPaginationType': 'full_numbers',
  'iDisplayLength': 5,
  'bInfo': false,
  'oLanguage': 
  {
   'sSearch': 'Search all columns:',
   'oPaginate': 
   {
    'sNext': '&gt;',
    'sLast': '&gt;&gt;',
    'sFirst': '&lt;&lt;',
    'sPrevious': '&lt;'
   }
  }
 });
}

At this point we are done with the basic grid view with just text data but what if we need to perform some functions like delete a particular row, Just don't worry about it create a webservice and write the deletion function in that service then use the following code to call it using jQuery.

function DeleteMe(string IdToBeDeleted){
var webMethod = 'DeleteRecord.asmx/DeleteUser'
var parameters = "{'ID':'" + IdToBeDeleted + "'}"

$.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {    
                alert('Success Deletion');
        },
        error: function(e){
                 alert('Failure Deletion');                         
        }
});

and for Datatable just create an other column and call this DeleteMe function with RowId as parameter to it and a nice deletion will occur.

Hope it helps.

Happy coding....

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.

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.