public bool appendShinkaBannerAd(ref MessageToSend messageToSend, MXit.User.UserInfo userInfo)
        {
            bool gotShinkaAd = false;

            try
            {
                if (AdvertConfig.isShowShinkaBannerAd)
                {
                    String MxitUserID = userInfo.UserId;
                    MXit.User.GenderType userGenderType = userInfo.Gender;
                    int displayWidth = userInfo.DeviceInfo.DisplayWidth;
                    int displayHeight = userInfo.DeviceInfo.DisplayHeight;
                    int userAge = AgeInYears(userInfo.DateOfBirth);

                    BannerAd adTodisplay;
                    gotShinkaAd = AdvertHelper.Instance.getBannerAd(MxitUserID, userGenderType, displayWidth, displayHeight, userAge, out adTodisplay);

                    if (gotShinkaAd)
                    {
                        if (adTodisplay.creativeType == "image")
                        {
                            IMessageElement inlineImage = MessageBuilder.Elements.CreateInlineImage(adTodisplay.adImage, ImageAlignment.Center, TextFlow.AloneOnLine, 100);
                            messageToSend.Append(inlineImage);
                        }

                        messageToSend.Append("Go to ", CSS.Ins.clr["light"], CSS.Ins.mrk["d"]);
                        messageToSend.AppendLine(MessageBuilder.Elements.CreateLink(adTodisplay.altText, ".clickad~" + adTodisplay.clickURL));
                        messageToSend.AppendLine();

                        //register impression for the bannerad display
                        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(adTodisplay.impressionURL);

                        req.UserAgent = "Mozilla Compatible mxit_client";
                        req.Headers.Add("HTTP_X_DEVICE_USER_AGENT", "Mozilla Compatible mxit_client");
                        req.Headers.Add("HTTP_X_FORWARDED_FOR", MxitUserID);
                        req.Headers.Add("HTTP_REFERER", AdvertConfig.appID);

                        req.Timeout = AdvertConfig.bannerAdTimeout;
                        req.Proxy = null;
                        req.KeepAlive = false;
                        req.ServicePoint.ConnectionLeaseTimeout = 1000;
                        req.ServicePoint.MaxIdleTime = 1000;

                        QueueHelper_HTTP.Instance.QueueItem(req);
                    }
                }
                //zama end
            }
            catch (Exception ex)
            {
                logger.Error("[" + MethodBase.GetCurrentMethod().Name + " - Error getting or showing Shinka ad: " + ex.ToString());
            }

            return gotShinkaAd; //so that the calling function knows if an ad was displayed
        }
 public void RedirectRequest(MXit.Navigation.RedirectRequest redirectRequest)
 {
     SharpConnectionHelperSingleton.Instance.RedirectRequest(redirectRequest);
 }
 public void RedirectRequest(MXit.Navigation.RedirectRequest redirectRequest)
 {
     try
     {
         //Todo
     }
     catch (Exception e)
     {
         Console.WriteLine(DateTime.Now.ToString() + " System Exception:" + e.ToString());
         logger.Error(MethodBase.GetCurrentMethod().Name + " - System Exception: " + e.ToString());
     }
 }
        public void ProcessOAuth2Token(MXit.OAuth2.TokenResponse tokenResponseReceived)
        {
            logger.Debug(MethodBase.GetCurrentMethod().Name + "() - START");

            bool isTokenResultSuccess = (tokenResponseReceived.Result == AsyncOperationResult.Success);

            if (isTokenResultSuccess) //We got a succesfull result:
            {
                bool isUserAllowed = (tokenResponseReceived.AuthorizationResult == AuthorizationResult.Allow);
                bool isUserAlwaysAllowed = (tokenResponseReceived.AuthorizationResult == AuthorizationResult.AlwaysAllow);

                if (isUserAllowed || isUserAlwaysAllowed) //We got permission:
                {
                    if ((String)tokenResponseReceived.Context == ".p")
                    {
                        MxitModel.FullProfile userProfile;

                        //Do something with the tokenReceived.AccessToken
                        this.GetUserMxitProfile(tokenResponseReceived.AccessToken, tokenResponseReceived.UserId, out userProfile);
                    }
                    else if ((String)tokenResponseReceived.Context == ".sf")
                    {
                        MxitModel.ContactList userContactList;

                        //Do something with the tokenReceived.AccessToken
                        this.GetContactList(tokenResponseReceived.AccessToken, tokenResponseReceived.UserId, out userContactList);

                        for (int i=0; i < userContactList.Contacts.Length; i++)
                        {
                            Console.WriteLine(userContactList.Contacts[i].DisplayName);
                        }
                    }
                    else if ((String)tokenResponseReceived.Context == ".f")
                    {
                        System.Net.HttpStatusCode responseCode;
                        //MXitConnectionModule.RESTConnectionHelper.Instance.SendMessageFromFriendToFriend(tokenResponseReceived.AccessToken, tokenResponseReceived.UserId, "m42992584002", "Merry Christmas! It's morning, and we've got nowhere to go. So wake me up in about an hour or so. It's Christmas day, and since we've got nowhere to be, stoke that braai and throw on another boerewors for me. It's Christmas night, and there's nothing I'd rather do than chill by the light of the Christmas tree with you.", out responseCode);

                        MessageToSend messageToSendToFriend = new MessageToSend(tokenResponseReceived.UserId, "m42992584002", DeviceInfo.DefaultDevice);
                        messageToSendToFriend.AppendLine("Light text", System.Drawing.Color.Black);
                        messageToSendToFriend.AppendLine("Bold text", System.Drawing.Color.Purple, new TextMarkup[] { TextMarkup.Bold });
                        messageToSendToFriend.AppendLine(MessageBuilder.Elements.CreateLink("Tip Link", ".tip"));

                        MXitConnectionModule.RESTConnectionHelper.Instance.SendMessageFromUserAToUserB(tokenResponseReceived.AccessToken, messageToSendToFriend);
                    }
                }
                else
                {
                    //Call a hook that will display a message to the user asking him to allow access to proceed.
                }
            }
            else
            {
                //Some error occured.
                if (logger.IsDebugEnabled) Console.WriteLine(DateTime.Now.ToString() + " Token request was not succesfull: " + tokenResponseReceived.Result);
                logger.Error(MethodBase.GetCurrentMethod().Name + " Token request was not succesfull: " + tokenResponseReceived.Result);
            }

            logger.Debug(MethodBase.GetCurrentMethod().Name + "() - END");
        }
        public bool appendShinkaBannerAd(ref MessageToSend messageToSend, MXit.User.UserInfo userInfo)
        {
            bool gotShinkaAd = false;

            try
            {
                if (AdvertConfig.isShowShinkaBannerAd)
                {
                    String MxitUserID = userInfo.UserId;
                    MXit.User.GenderType userGenderType = userInfo.Gender;
                    int displayWidth = userInfo.DeviceInfo.DisplayWidth;
                    int displayHeight = userInfo.DeviceInfo.DisplayHeight;
                    int userAge = AgeInYears(userInfo.DateOfBirth);

                    BannerAd adTodisplay;
                    gotShinkaAd = AdvertHelper.Instance.getBannerAd(MxitUserID, userGenderType, displayWidth, displayHeight, userAge, out adTodisplay);

                    if (gotShinkaAd)
                    {
                        if (adTodisplay.creativeType == "image")
                        {
                            int imageDisplayWidthPerc;

                            if (displayWidth <= 128)
                            {
                                imageDisplayWidthPerc = 99;
                            }
                            else
                            {
                                imageDisplayWidthPerc = 100;
                            }

                            IMessageElement inlineImage = MessageBuilder.Elements.CreateInlineImage(adTodisplay.adImage, ImageAlignment.Center, TextFlow.AloneOnLine, imageDisplayWidthPerc);
                            messageToSend.Append(inlineImage);
                        }

                        messageToSend.Append("Go to ", CSS.Ins.clr["light"], CSS.Ins.mrk["d"]);
                        String displayText = System.Net.WebUtility.HtmlDecode(adTodisplay.altText);
                        messageToSend.AppendLine(MessageBuilder.Elements.CreateBrowserLink(displayText, adTodisplay.clickURL));
                        messageToSend.AppendLine();

                        //register impression for the bannerad display
                        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(adTodisplay.impressionURL);

                        req.UserAgent = "Mozilla Compatible mxit_client";

                        Random random = new Random(DateTime.Now.Second);
                        int randomUpTo254 = random.Next(1, 254);
                        String tempIP = "196.11.239." + randomUpTo254;
                        req.Headers.Add("X-Forwarded-For", tempIP);

                        req.Referer = AdvertConfig.appID;

                        req.Timeout = AdvertConfig.bannerAdTimeout;
                        req.Proxy = null;
                        req.KeepAlive = false;
                        req.ServicePoint.ConnectionLeaseTimeout = 10000;
                        req.ServicePoint.MaxIdleTime = 10000;

                        QueueHelper_HTTP.Instance.QueueItem(req);
                    }
                }
                //zama end
            }
            catch (Exception ex)
            {
                logger.Error("[" + MethodBase.GetCurrentMethod().Name + " - Error getting or showing Shinka ad: " + ex.ToString());
            }

            return gotShinkaAd; //so that the calling function knows if an ad was displayed
        }
        private bool getBannerAd(String MxitUserID, MXit.User.GenderType userGenderType, int displayWidth, int displayHeight, int userAge, out BannerAd adDetail)
        {
            bool success = false;

            adDetail = new BannerAd();

            //Post back to openx
            String openXAdUnitToUse = AdvertConfig.OpenX_AdUnitID_120;
            String deviceName = "samsung/sgh"; //default to most popular device

            if (displayWidth >= 480)
            {
                openXAdUnitToUse = AdvertConfig.OpenX_AdUnitID_320;
                deviceName = "android";
            }
            else if (displayWidth >= 300)
            {
                openXAdUnitToUse = AdvertConfig.OpenX_AdUnitID_320;
                deviceName = "nokia/c3";
            }
            else if (displayWidth >= 240)
            {
                openXAdUnitToUse = AdvertConfig.OpenX_AdUnitID_240;
                deviceName = "nokia/5130%20xpressmusic";
            }
            else if (displayWidth >= 180)
            {
                openXAdUnitToUse = AdvertConfig.OpenX_AdUnitID_180;
                deviceName = "samsung/sgh";
            }
            else
            {
                openXAdUnitToUse = AdvertConfig.OpenX_AdUnitID_120;
                deviceName = "samsung/sgh";
            }

            string strOpenxUrl = AdvertConfig.OpenX_URL + openXAdUnitToUse;
            string strUserDetails = "&" + "c.device=" + deviceName + "&" + "c.age=" + userAge + "&" + "c.gender=" + userGenderType.ToString().ToLower() + "&" + "xid=" + MxitUserID + "&" + "c.country=za";
            string strCompleteUrl = strOpenxUrl + strUserDetails;

            //use the complete url on a mobile
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strCompleteUrl);

            req.UserAgent = "Mozilla Compatible mxit_client";

            Random random = new Random(DateTime.Now.Second);
            int randomUpTo254 = random.Next(1, 254);
            String tempIP = "196.25.101." + randomUpTo254;

            req.Headers.Add("X-Forwarded-For", tempIP);
            req.Referer = AdvertConfig.appID;

            req.Timeout = AdvertConfig.bannerAdTimeout;
            req.Proxy = null;//GlobalProxySelection.GetEmptyWebProxy(); // null;
            req.KeepAlive = false;
            req.ServicePoint.ConnectionLeaseTimeout = 1000;
            req.ServicePoint.MaxIdleTime = 1000;

            //if (AdvertConfig.isShowMessages)
            //{
            //    Console.WriteLine(DateTime.Now.ToString() + " URL: " + strCompleteUrl);
            //}

            string strResponse = "";

            try
            {

                logger.Debug("[" + MethodBase.GetCurrentMethod().Name + "()] - Starting to read server ad request...");

                using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader streamIn = new StreamReader(responseStream))
                        {
                            strResponse = streamIn.ReadToEnd();
                            streamIn.Close();
                        }
                        responseStream.Flush();
                        responseStream.Close();
                    }
                    response.Close();
                }

                logger.Debug("[" + MethodBase.GetCurrentMethod().Name + "()] - Finished reading server ad request...");

                if (strResponse.Contains("media"))
                {

                    //pass in the tags to remove

                    //Determine the ad type:

                    //We aren't using XML processing to try to save processing time, not having to prase the entire XML response into objects, etc. Instead we use basic string searches.
                    //Welcome for somebody to do a benchmark to see if XML parsing will be faster or slower.

                    adDetail.creativeType = Between(strResponse, "<ad ", "<html>", "type=", 0, ">");
                    bool isGotCreativeType = (!string.IsNullOrEmpty(adDetail.creativeType));

                    if (isGotCreativeType)
                    {
                        //Get the generic click and impression fields
                        adDetail.clickURL = Between(strResponse, "<click>", "</click>", "", 7, "");
                        adDetail.impressionURL = Between(strResponse, "<impression>", "</impression>", "", 12, "");
                        //adDetail.inView = Between(strResponse, "<inview>", "</inview>", "", 8, "");

                        //Do logic for image type ad:
                        if (adDetail.creativeType == "image")
                        {
                            adDetail.altText = Between(strResponse, "<creative", "<media>", "alt=", 0, "target");
                            if (!String.IsNullOrEmpty(adDetail.altText))
                            {
                                adDetail.adImageURL = Between(strResponse, "<media>", "</media>", "", 7, "");
                                success = true;

                            }
                            else
                            {
                                logger.Error(MethodBase.GetCurrentMethod().Name + " - " + "SHINKA ERROR: Could not find alt text in string: " + strResponse + " USING URL: " + strCompleteUrl);
                                success = false;
                            }
                        }
                        else if (adDetail.creativeType == "html")
                        {
                            //Use the altText field for the text ad body
                            String hrefHTMLText = Between(strResponse, "<media>", "</media>", "", 7, "");

                            int startIndex = hrefHTMLText.IndexOf("&gt;") + 4;
                            int endIndex = hrefHTMLText.IndexOf("&lt;/a&gt;");
                            int length = endIndex - startIndex;

                            adDetail.altText = hrefHTMLText.Substring(startIndex, length);
                            success = true;
                        }
                        else
                        {
                            logger.Error(MethodBase.GetCurrentMethod().Name + " - " + "SHINKA ERROR: Not a known creative type: " + adDetail.creativeType);
                            success = false;
                        }
                    }
                    else
                    {
                        logger.Error(MethodBase.GetCurrentMethod().Name + " - " + "SHINKA ERROR: Could not get creative type: " + strResponse + " USING URL: " + strCompleteUrl);
                        success = false;
                    }
                }
                else
                {
                    logger.Debug(MethodBase.GetCurrentMethod().Name + " - " + "SHINKA Warning: Empty ad response:" + strResponse + " USING URL: " + strCompleteUrl + " FOR USER: "******" - " + "Error doing Shinka Server Add Call: " + ex.ToString());
                logger.Error(MethodBase.GetCurrentMethod().Name + " - " + "Error with String: " + strResponse);
                success = false;
            }
            finally
            {
                req.Abort();
                req = null;
                GC.Collect();
            }

            if ((adDetail.creativeType == "image") && !String.IsNullOrEmpty(adDetail.adImageURL))
            {
                logger.Debug("[" + MethodBase.GetCurrentMethod().Name + "()] - Starting to read ad bitmap image...");
                //convert the url into an image and load to the bitmap
                adDetail.adImage = BitmapFromWeb(adDetail.adImageURL);
                logger.Debug("[" + MethodBase.GetCurrentMethod().Name + "()] - Finished reading ad bitmap image...");
                success = true;
            }

            //add banner to user session
            //userSession.CurrentBannerAd = adDetail;

            return success;
        }
        private bool getBannerAd(String MxitUserID, MXit.User.GenderType userGenderType, int displayWidth, int displayHeight, int userAge, out BannerAd adDetail)
        {
            //Default to no preselected ad unit
            String preselectedAdUnitID = "";

            return getBannerAd(MxitUserID, userGenderType, displayWidth, displayHeight, userAge, preselectedAdUnitID, out adDetail);
        }
        private void appendBannerImage(ref MessageToSend messageToSend, MXit.User.UserInfo userInfo, BannerAd adTodisplay)
        {
            if ((AdvertConfig.bannerCacheSize > 0) && (messageToSend.ToDevice.HasFeature(DeviceFeatures.Gaming)))
            {
                //use ImageStrips to allow caching of images on users device
                string bannerHash = GetImageHash(adTodisplay.adImage);
                int cachePosition;
                if (!bannerHashMap.ContainsKey(bannerHash))
                {
                    cachePosition = lastCachePosition;
                    //we create a dictionary of ImageStrips with the required sizes
                    AdvertStripCollection bannerStrips = new AdvertStripCollection(bannerHash, adTodisplay.adImage);

                    bannerStripCache[cachePosition] = bannerStrips;
                    //remove any other hashes that are using this position
                    foreach (string key in bannerHashMap.Keys)
                    {
                        if (bannerHashMap[key] == cachePosition)
                            bannerHashMap.Remove(key);
                        break;
                    }
                    //and assign this position to the hash
                    bannerHashMap[bannerHash] = cachePosition;

                    //advance the pointer of the last added imagestrip.
                    lastCachePosition++;
                    if (lastCachePosition == AdvertConfig.bannerCacheSize)
                    {
                        lastCachePosition = 0;
                    }
                }
                else
                {
                    cachePosition = bannerHashMap[bannerHash];
                }

                string userSize = GetUserSize(userInfo);
                //this doesn't allow client-side auto resizing of images, may want to consider server side resizing
                ITable boardAd = MessageBuilder.Elements.CreateTable(messageToSend, "ad-" + bannerHash + "-" + userSize, 1, 1);
                boardAd.SelectionMode = SelectionRectType.Outline;
                boardAd.Style.Align = (AlignmentType)((int)AlignmentType.VerticalCenter + (int)AlignmentType.HorizontalCenter);
                boardAd.Mode = TableSendModeType.Update;
                //Mxit SDK 1.4.6 shows Frames.Set as obsolete, to be replaced with Frames.Add, but will break compatibility with older SDK's
                boardAd[0, 0].Frames.Set(bannerStripCache[cachePosition].GetStrip(userSize), 0);
                messageToSend.Append(boardAd);
            }

            else
            {
                int displayWidth = userInfo.DeviceInfo.DisplayWidth;
                int imageDisplayWidthPerc;

                if (displayWidth <= 128)
                {
                    imageDisplayWidthPerc = 99;
                }
                else
                {
                    imageDisplayWidthPerc = 100;
                }

                IMessageElement inlineImage = MessageBuilder.Elements.CreateInlineImage(adTodisplay.adImage, ImageAlignment.Center, TextFlow.AloneOnLine, imageDisplayWidthPerc);
                //IMessageElement inlineImage = MessageBuilder.Elements.CreateInlineImage(adTodisplay.adImageURL, ImageAlignment.Center, TextFlow.AloneOnLine);
                messageToSend.AppendLine(inlineImage);
            }
        }
        public bool appendShinkaBannerAd(ref MessageToSend messageToSend, MXit.User.UserInfo userInfo, String preselectedAdUnitID)
        {
            bool gotShinkaAd = false;

            try
            {
                if (AdvertConfig.isShowShinkaBannerAd)
                {
                    String MxitUserID = userInfo.UserId;
                    MXit.User.GenderType userGenderType = userInfo.Gender;
                    int displayWidth = userInfo.DeviceInfo.DisplayWidth;
                    int displayHeight = userInfo.DeviceInfo.DisplayHeight;
                    int userAge = AgeInYears(userInfo.DateOfBirth);

                    BannerAd adTodisplay;
                    gotShinkaAd = AdvertHelper.Instance.getBannerAd(MxitUserID, userGenderType, displayWidth, displayHeight, userAge, preselectedAdUnitID, out adTodisplay);

                    if (gotShinkaAd)
                    {
                        if (adTodisplay.creativeType == "image" && userInfo.DeviceInfo.DisplayWidth >= 320)
                        {
                            //an extra check to see that the image was retrieved
                            //Eric changed: if (adTodisplay.adImage == null)
                            if (adTodisplay.adImage == null)
                            {
                                return false;
                            }
                            else
                            {
                                appendBannerImage(ref messageToSend, userInfo, adTodisplay);
                            }

                        }

                        //If the Alt text is empty then don't display the link below the image:
                        if (!String.IsNullOrEmpty(adTodisplay.altText))
                        {
                            messageToSend.Append("Go to ", CSS.Ins.clr["light"], CSS.Ins.mrk["d"]);
                            String displayText = System.Net.WebUtility.HtmlDecode(adTodisplay.altText);
                            messageToSend.AppendLine(MessageBuilder.Elements.CreateBrowserLink(displayText, adTodisplay.clickURL));
                            messageToSend.AppendLine();
                        }
                        else //Don't display Alt text link:
                        {
                            messageToSend.AppendLine();
                        }

                        //register impression for the bannerad display
                        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(adTodisplay.impressionURL);

                        req.UserAgent = "Mozilla Compatible";

                        Random random = new Random(DateTime.Now.Second);
                        int randomUpTo254 = random.Next(1, 254);
                        String tempIP = "196.11.239." + randomUpTo254;
                        req.Headers.Add("X-Forwarded-For", tempIP);

                        req.Referer = AdvertConfig.appID;

                        req.Timeout = AdvertConfig.bannerAdTimeout;
                        req.Proxy = null;
                        req.KeepAlive = false;
                        req.ServicePoint.ConnectionLeaseTimeout = 10000;
                        req.ServicePoint.MaxIdleTime = 10000;

                        QueueHelper_HTTP.Instance.QueueItem(req);
                    }
                }
                //zama end
            }
            catch (Exception ex)
            {
                logger.Error("[" + MethodBase.GetCurrentMethod().Name + " - Error getting or showing Shinka ad: " + ex.ToString());
            }

            return gotShinkaAd; //so that the calling function knows if an ad was displayed
        }
        public bool appendShinkaBannerAd(ref MessageToSend messageToSend, MXit.User.UserInfo userInfo)
        {
            //Default to no preselected ad unit id:
            String preselectedAdUnitID = "";

            return appendShinkaBannerAd(ref messageToSend, userInfo, preselectedAdUnitID);
        }
        public void handleUserClickedOnAdLink(MessageReceived messageReceived, MXit.User.UserInfo userInfo)
        {
            String adClickURL = messageReceived.Body.Split('~')[1];

            createAndQueueRequestToMobiApp(userInfo, adClickURL);

            //We need to wait a short while before calling the redirect to make sure the Mobi App has saved the URL to redirect to:
            Thread.Sleep(20);

            MXit.Navigation.RedirectRequest redirectRequest;
            String messageForMobiApp = ".gotourl~" + adClickURL;
            redirectRequest = messageReceived.CreateRedirectRequest(AdvertConfig.mobiAppServiceName, messageForMobiApp);

            //Redirect the users context

            //************* Replace with your own client.RedirectRequest based on where your client object resides: ***************
            MXitConnectionModule.ConnectionManager.Instance.RedirectRequest(redirectRequest);
            //****************************
        }
        //Need this so that we can show an intermediate page on a Mobi app until C# apps are allowed to show HTTP links
        //This will send a request to a HTTP service to save the URL that the user should go to, when he is redirected to the destination Mobi App.
        //This will only work if you have redirect permission from your C# App to the required Mobi App. Request this redirect permission from Mxit (Robert)
        public void createAndQueueRequestToMobiApp(MXit.User.UserInfo userInfo, String adClickURL)
        {
            String saveActionAPI_URL = AdvertConfig.mobiAppSaveActionURL;

            String saveActionToMobiAppURL =
                saveActionAPI_URL +
                "?mxituserid=" + userInfo.UserId +
                "&actiontype=" + "1" +
                "&action=" + adClickURL;

            //register impression for the bannerad display
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(saveActionToMobiAppURL);
            req.Headers.Add("X_MXPASS_MXIT_USERID", userInfo.UserId);
            req.Headers.Add("X_MXPASS_ACTION", adClickURL);
            //
            req.Timeout = AdvertConfig.bannerAdTimeout;
            req.Proxy = null;
            req.KeepAlive = false;
            req.ServicePoint.ConnectionLeaseTimeout = 1000;
            req.ServicePoint.MaxIdleTime = 1000;

            QueueHelper_HTTP.Instance.QueueItem(req);
        }