How to call web API login action from Windows form app - javascript
I have a simple web API with registration, login, and call API module. I want to call each functionality from Windows form application.
In web API, I use the following script in JavaScript to call login method:
self.login = function () {
self.result('');
var loginData = {
grant_type: 'password',
username: self.loginEmail(),
password: self.loginPassword()
};
$.ajax({
type: 'POST',
url: '/Token',
data: loginData
}).done(function (data) {
self.user(data.userName);
// Cache the access token in session storage.
sessionStorage.setItem(tokenKey, data.access_token);
}).fail(showError);
}
my controller actions are as follows
// POST api/Account/AddExternalLogin
[Route("AddExternalLogin")]
public async Task<IHttpActionResult> AddExternalLogin(AddExternalLoginBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
AuthenticationTicket ticket = AccessTokenFormat.Unprotect(model.ExternalAccessToken);
if (ticket == null || ticket.Identity == null || (ticket.Properties != null
&& ticket.Properties.ExpiresUtc.HasValue
&& ticket.Properties.ExpiresUtc.Value < DateTimeOffset.UtcNow))
{
return BadRequest("External login failure.");
}
ExternalLoginData externalData = ExternalLoginData.FromIdentity(ticket.Identity);
if (externalData == null)
{
return BadRequest("The external login is already associated with an account.");
}
IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(),
new UserLoginInfo(externalData.LoginProvider, externalData.ProviderKey));
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
// POST api/Account/RemoveLogin
[Route("RemoveLogin")]
public async Task<IHttpActionResult> RemoveLogin(RemoveLoginBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
IdentityResult result;
if (model.LoginProvider == LocalLoginProvider)
{
result = await UserManager.RemovePasswordAsync(User.Identity.GetUserId());
}
else
{
result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(),
new UserLoginInfo(model.LoginProvider, model.ProviderKey));
}
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
// GET api/Account/ExternalLogin
[OverrideAuthentication]
[HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)]
[AllowAnonymous]
[Route("ExternalLogin", Name = "ExternalLogin")]
public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null)
{
if (error != null)
{
return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error));
}
if (!User.Identity.IsAuthenticated)
{
return new ChallengeResult(provider, this);
}
ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
if (externalLogin == null)
{
return InternalServerError();
}
if (externalLogin.LoginProvider != provider)
{
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
return new ChallengeResult(provider, this);
}
ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
externalLogin.ProviderKey));
bool hasRegistered = user != null;
if (hasRegistered)
{
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
}
else
{
IEnumerable<Claim> claims = externalLogin.GetClaims();
ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
Authentication.SignIn(identity);
}
return Ok();
}
// GET api/Account/ExternalLogins?returnUrl=%2F&generateState=true
[AllowAnonymous]
[Route("ExternalLogins")]
public IEnumerable<ExternalLoginViewModel> GetExternalLogins(string returnUrl, bool generateState = false)
{
IEnumerable<AuthenticationDescription> descriptions = Authentication.GetExternalAuthenticationTypes();
List<ExternalLoginViewModel> logins = new List<ExternalLoginViewModel>();
string state;
if (generateState)
{
const int strengthInBits = 256;
state = RandomOAuthStateGenerator.Generate(strengthInBits);
}
else
{
state = null;
}
foreach (AuthenticationDescription description in descriptions)
{
ExternalLoginViewModel login = new ExternalLoginViewModel
{
Name = description.Caption,
Url = Url.Route("ExternalLogin", new
{
provider = description.AuthenticationType,
response_type = "token",
client_id = Startup.PublicClientId,
redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri,
state = state
}),
State = state
};
logins.Add(login);
}
return logins;
}
I am using the following code in winform to call the login action:
HttpClient client = new HttpClient();
Uri baseAddress = new Uri("https://localhost:44305/");
client.BaseAddress = baseAddress;
ArrayList paramList = new ArrayList();
user u = new user();
u.username = username;
u.password = password;
paramList.Add(u);
HttpResponseMessage response = client.PostAsJsonAsync("api/product/SupplierAndProduct", paramList).Result;
In the above code I tried to call controller actions but failed. To accomplish my goal even calling the JavaScript from winform app is fine.
HttpClient client = new HttpClient();
Uri baseAddress = new Uri("http://localhost:2939/");
client.BaseAddress = baseAddress;
ArrayList paramList = new ArrayList();
Product product = new Product { ProductId = 1, Name = "Book", Price = 500, Category = "Soap" };
Supplier supplier = new Supplier { SupplierId = 1, Name = "AK Singh", Address = "Delhi" };
paramList.Add(product);
paramList.Add(supplier);
HttpResponseMessage response = client.PostAsJsonAsync("api/product/SupplierAndProduct", paramList).Result;
Following answer will helpfull to you
call web api from c sharp
I usually use HttpWebRequest and HttpWebResponce in cases like yours:
//POST
var httpWebRequest = (HttpWebRequest)WebRequest.Create("path/api");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = WebRequestMethods.Http.Post;
httpWebRequest.Accept = "application/json; charset=utf-8";
//probably have to be added
//httpWebRequest.ContentLength = json.Length;
//do request
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
//write post data
//also you can serialize yours objects by JavaScriptSerializer
streamWriter.Write(json);
streamWriter.Flush();
}
//get responce
using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
//read
using (Stream stream = httpResponse.GetResponseStream())
{
using (StreamReader re = new StreamReader(stream))
{
String jsonResponce = re.ReadToEnd();
}
}
}
//GET
var httpWebRequest = (HttpWebRequest)WebRequest.Create("path/api");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json; charset=utf-8";
//get responce
using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
//read
using (Stream stream = httpResponse.GetResponseStream())
{
using (StreamReader re = new StreamReader(stream))
{
String jsonResponce = re.ReadToEnd();
}
}
}
Also you sould read this SO answer
//GET
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://160.114.10.17:85/api/Inventory/GetProcessDataByProcessName?deviceCode=OvCHY1ySowF4T2bb8HdcYA==&processName=Main Plant");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json; charset=utf-8";
//get responce
using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
//read
using (Stream stream = httpResponse.GetResponseStream())
{
using (StreamReader re = new StreamReader(stream))
{
String jsonResponce = re.ReadToEnd();
}
}
}
Related
How to POST Data from HTML Page via WebApi in MVC Controller
Function which is use to take input data from HTML function saveclickdata() { var allData = { InvNo:document.getElementById('TbInvNo').value, GrossSale:document.getElementById('TbOrderTotal').value, discount:document.getElementById('TbDiscount').value, CusCash:document.getElementById('TbCash').value, CusBal:document.getElementById('TbBalance').value, }; $.ajax({ url: "\Controllers\POSController.cs\SaveData", type: 'POST', data: allData, success: function (res) { alert("success"); }, error: function (err) { alet("Error"); } }); Api which is in controller used to post data [HttpPost] JsonResult SaveData(POSMater collection) { if (collection.InvNo.ToString() == null) { var LocalInvNo = (from b in db.TblPOSMasters select b).FirstOrDefault(); int MaxInvNo = Convert.ToInt32(LocalInvNo) + 1; collection.InvNo = MaxInvNo; TblPOSMaster master = new TblPOSMaster(); master.InvNo = collection.InvNo; master.AddBy = 1; master.AddDate = DateTime.Now; master.CashStatus = "A"; master.CompId = 1; //master.CreditAmt = collection.CreditAmt; //master.CrCardNo = collection.CrCardNo; master.CusCash = collection.CusCash; master.CusId = 1; master.GrossSale = collection.GrossSale; db.TblPOSMasters.Add(master); db.SaveChanges(); } else { return Json(collection); } return Json(collection); } What should i do? My html button working properly but still not able to call api
I think you ought to use forward slashes (/) in your URL
Add license checks to Office and SharePoint Add-ins
Created Office Add-ins (App ID 42949681619) Implemented enter link description here. var decodedToken = getUrlVars()["et"]; var decodedBytes = encodeURIComponent(decodedToken); var Valid = false; function getUrlVars() { var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for (var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; } function EtokenWeb(sourceWord) { try { var xhr = new XMLHttpRequest(); var translateRequest = "../Verification.asmx/VerifyEntitlement?et="+ sourceWord; xhr.open("POST", translateRequest); xhr.responseType = 'document'; xhr.onload = function () { var result = parseResponse(xhr.responseXML); Valid = result; } // Send the HTTP request. xhr.send(); } catch (ex) { app.showNotification(ex.name, ex.message); } } function parseResponse(responseText) { var response = "Cannot read response.", xmlDoc; try { response = responseText.getElementsByTagName("string")[0].firstChild.nodeValue; } catch (ex) { app.showNotification(ex.name, ex.message); } return response; } using BenWeb.VerificationService; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Web; using System.Web.Services; namespace BenWeb { [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] [System.Web.Script.Services.ScriptService] public class Verification : System.Web.Services.WebService { private static VerificationServiceClient service = new VerificationServiceClient(); VerifyEntitlementTokenRequest request = new VerifyEntitlementTokenRequest(); [WebMethod] public bool VerifyEntitlement () { // Store the URL from the incoming request and declare // strings to store the query and the translation result. string currentURL = HttpContext.Current.Request.RawUrl; string queryString; bool result = false; try { // Check to make sure some query string variables exist. int indexQueryString = currentURL.IndexOf('?'); if (indexQueryString >= 0) { queryString = (indexQueryString < currentURL.Length - 1) ? currentURL.Substring(indexQueryString + 1) : String.Empty; // Parse the query string variables into a NameValueCollection. NameValueCollection queryStringCollection = HttpUtility.ParseQueryString(queryString); string Token = queryStringCollection["et"]; if (Token != null) { request.EntitlementToken = Token; VerifyEntitlementTokenResponse omexResponse = service.VerifyEntitlementToken(request); result = omexResponse.IsValid; } else result = false; } } catch (Exception ex) { //result = ex.Message; result = false; } // to the HTTP request. return result; } } } Added in code: if (Valid) { $('#highlight-button').click(SelectedRange); $('#highlight2-button').click(Recalculation); } Sent for approval. Received a comment "Your add-in does not work as described in your addin description. Nothing happens when we click the “Choose” button." Test license VerificationService worked fine (IsTest=True, IsValid=False). Where I went wrong? And how to check for this (correct) license?
Refresh model after post-request in ASP.MVC
I'm developping a webApp with MVC. I have a view with cirkles displaying a value and a slider, when you slide the cirkles need to display the new value. I send the new value with a POST from my AJAX call to the controller, which does a minor calculation with the value and give it back to the view so the cirkles can display the updated value. However my view still keeps using the startvalue. #model UGT.UI.Web.MVC.Models.BelastingViewModel <script language="JavaScript"> var config1 = liquidFillGaugeDefaultSettings(); #{ teller = 1; string naam_var = null; foreach (KeyValuePair<UGT.BL.Domain.BegrotingPackage.Categorie, double> cat in Model.Belasting) { naam = "fillgauge" + teller; naam_var = "gauge" + teller; #: var #naam_var = loadLiquidFillGauge("#naam", "#Html.DisplayFor(modelItem => cat.Value)", config1); teller++; } } function toonCirkels() { #{ teller = 1; naam = "fillgauge" + teller; string naam_var2 = null; foreach (KeyValuePair<UGT.BL.Domain.BegrotingPackage.Categorie, double> cat in Model.Belasting) { naam_var2 = "gauge" + teller; // #: gauge1.update("#Html.DisplayFor(modelItem => cat.Value)"); // #: var #naam_var = loadLiquidFillGauge("#naam", "#Html.DisplayFor(modelItem => cat.Value)", config1); // #: #naam_var2.update("#Html.DisplayFor(modelItem => cat.Value)"); teller++; } //#:gauge1.update("500"); } } public class BelastingsController : Controller { private BegrotingsManager begrotingsManager = new BegrotingsManager(); private int gemeenteId = 54; private double loon = 200; private BelastingViewModel belastingen = new BelastingViewModel(); // GET: Belastings public ActionResult Index() { var belasting = begrotingsManager.GetBelastingGebruiker(this.loon, gemeenteId); belastingen.Belasting = belasting; UpdateModel(belastingen); return View(belastingen); } [HttpPost] public ActionResult Index(String loon) { this.loon = Double.Parse(loon); var belasting = begrotingsManager.GetBelastingGebruiker(this.loon, gemeenteId); belastingen.Belasting = belasting; UpdateModel(belastingen); return new HttpStatusCodeResult(HttpStatusCode.OK); // return RedirectToAction("Index"); } namespace UGT.UI.Web.MVC.Models { public class BelastingViewModel { public IDictionary<Categorie, double> Belasting { get; set; } } } d3.selectAll('.range').on('change', function () { this.value = parseInt(this.value); if (this.value < 0) this.value = 0; else if (this.value > 5000) this.value = 5000; var loon = this.value; var loonString = "€" + loon; d3.select('.range_value').html(loonString); sendLoon(loon, loonString); }); } function sendLoon(loon, loonString) { $.ajax({ contentType: "application/json; charset=utf-8", url: "/Belastings", type: "POST", data: JSON.stringify({ "loon": loon }), success: function () { // window.location.reload(); toonCirkels(); }, error: function () { } }); }
The success of your Ajax call calls 'toonCirkels' which only contains razor generated code which is filled on page load. The content of this method never changes as it contains ONLY razor generated code and thus will always have the same logic with the same values.
angularjs post data to mvc controller in json format with multiple arrays
I am working on a project in which I have used angularjs and mvc.I am passing data from angular js controller to my mvc controller by $http.post().For now I am using single object/json array to retreive data like this -public bool UpdateIssueDetails(IssueBO issue).But I want that if I could do like this public public bool UpdateIssueDetails(IssueBO issue,List lstMembersToNotify).I want to send two json arrays from ny angular js controller to my above mvc controller method. angularjs controller code $scope.saveIssueDetails = function (issue) { var milestoneId = ""; var milestoneName = ""; if ($scope.selectedIssue.Milestone== undefined) { milestoneId = ""; milestoneName = ""; } else { milestoneId = $scope.selectedIssue.Milestone.Id; milestoneName = $scope.selectedIssue.Milestone.Name; } var arrMembersToNotify = []; var arrMembersToNotifyNew = []; var iCount = 0; $("#membersToNotify input[type=checkbox]:checked").each(function () { arrMembersToNotify = $(this).val().split("~"); arrMembersToNotifyNew.push({ "UserId": arrMembersToNotify[0], "UserDisplayName": arrMembersToNotify[1], "Email": arrMembersToNotify[2] }); }); var issueDetails = { Id: issue.Id, ProjectId: issue.ProjectId, ProjectName: issue.ProjectName, IssueStatusId: $scope.selectedIssue.Status.Id, StatusName: $scope.selectedIssue.Status.Name, IssuePriorityId: $scope.selectedIssue.Priority.Id, PriorityName: $scope.selectedIssue.Priority.Name, AssignedUserId: $scope.selectedIssue.AssignedTo.Id, AssigneeDisplayName: $scope.selectedIssue.AssignedTo.DisplayName, IssueCategoryId: $scope.selectedIssue.Category.Id, CategoryName: $scope.selectedIssue.Category.Name, DueDate: $scope.selectedIssue.DueDate, OwnerUserId: $scope.selectedIssue.OwnedBy.Id, OwnerDisplayName: $scope.selectedIssue.OwnedBy.DisplayName, IssueTypeId: $scope.selectedIssue.Type.Id, IssueTypeName: $scope.selectedIssue.Type.Name, IssueResolutionId: $scope.selectedIssue.Resolution.Id, ResolutionName: $scope.selectedIssue.Resolution.Name, MilestoneId: milestoneId, MilestoneName: milestoneName, Estimation: $scope.selectedIssue.Estimation, Progress: $scope.selectedIssue.Progress, }; var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/UpdateIssueDetails/'; $http.post(url, [issueDetails, arrMembersToNotifyNew]).success(function (data, status, headers, config) { if (data != '' || data.length >= 0 || data == true) { //$scope.selectedIssue = issue; //$scope.showIssueDetails($scope.selectedIssue); $scope.GetAssignedIssues(); } else if (data == '' || data == false) { $scope.selectedIssue = null; } else { $scope.errors.push(data.error); } }); }; mvc controller code [HttpPost] [AuthenticationRequired] public bool UpdateIssueDetails(IssueBO issue,List<IssueNotification> lstMembersToNotify) { try { //var issueDetails = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(issueAllDetails[0].ToString()); //List<Dictionary<string, string>> membersToNotifyDetails = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(issueAllDetails[1].ToString()); var membersToNotify = lstMembersToNotify.Select(membersToNotifyDetail => new IssueNotification() { UserId =membersToNotifyDetail.UserId, Email = membersToNotifyDetail.Email, UserDisplayName = membersToNotifyDetail.UserDisplayName }).ToList(); var newIssue = new IssueBO { OwnerUserId = issue.OwnerUserId, OwnerDisplayName = issue.OwnerDisplayName, LastUpdatedUserId = SessionItems.UserId, LastUpdaterDisplayName = SessionItems.DisplayName, LastUpdatedOn = DateTime.Now, ProjectId = issue.ProjectId, ProjectName = issue.ProjectName, Id = issue.Id, AssignedUserId = issue.AssignedUserId, AssigneeDisplayName = issue.AssigneeDisplayName, IssueStatusId = issue.IssueStatusId, StatusName = issue.StatusName, Progress = issue.Progress, IssuePriorityId = issue.IssuePriorityId, PriorityName = issue.PriorityName, IssueTypeId = issue.IssueTypeId, IssueTypeName = issue.IssueTypeName, IssueCategoryId = issue.IssueCategoryId, CategoryName = issue.CategoryName, IssueResolutionId = issue.IssueResolutionId, ResolutionName = issue.ResolutionName, DueDate = issue.DueDate, Estimation = issue.Estimation, MilestoneId = issue.MilestoneId, MilestoneName = issue.MilestoneName }; var result = BLL.AdminLayer.UpdateIssueDetail(newIssue, membersToNotify); return result.IsSuccessful && result.Result; } catch (Exception ex) { BLL.Base.BaseLayer.WriteApplicationLog(ex); return false; } } I am passing two json array from my angularjs controller like this-$http.post(url, [issueDetails, arrMembersToNotifyNew]).success(function (data, status, headers, config).But I am getting error trying this.Please suggest how to achieve this.Thanks
You need to pass data to the action by using JSON.stringify() $http.post(url, JSON.stringify({ issue: issueDetails, lstMembersToNotify: arrMembersToNotifyNew });
Post it as properties of an object. $http.post(url, { issue: issueDetails, lstMembersToNotify: arrMembersToNotifyNew });
Getting web response when button clicked in BlackBerry
I have loaded a web page in BB as follow //RegBrowserFieldConfig extends BrowserFieldConfig RegBrowserFieldConfig regBrowserFieldConfig = new RegBrowserFieldConfig(); //RegBrowserFieldListener extends BrowserFieldListener RegBrowserFieldListener regBrowserFieldListener = new RegBrowserFieldListener(); BrowserField registrationBrowserField = new BrowserField(regBrowserFieldConfig); registrationBrowserField.addListener(regBrowserFieldListener); add(registrationBrowserField); registrationBrowserField.requestContent("http://myurl.com/"); That web page loads fine. There is a submit button in that web page which call onsubmit in the form element in HTML. That is calling to a JavaScript function. With in that function there are some other URL that will fire according to the requirements. What I need is to get the response of those URL calls. How can I do that?
I tried this way.. BrowserFieldListener list = new BrowserFieldListener() { public void documentLoaded(BrowserField browserField, Document document) throws Exception { String url = document.getBaseURI(); //u can get the current url here... u can use ur logic to get the url after clicking the submit button Serverconnection(url);//from this methode u can get the response } }; browserField.addListener(list); Serverconnection.. public String Serverconnection(String url) { String line = ""; // if (DeviceInfo.isSimulator()) { // url = url + ";deviceSide=true"; // } else { // url = url + ";deviceSide=true"; // } url = url + getConnectionString(); try { HttpConnection s = (HttpConnection) Connector.open(url); s.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); s.setRequestProperty( "Accept", "text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); s.setRequestProperty(HttpProtocolConstants.HEADER_ACCEPT_CHARSET, "UTF-8"); s.setRequestMethod(HttpConnection.GET); InputStream input = s.openInputStream(); byte[] data = new byte[10240]; int len = 0; StringBuffer raw = new StringBuffer(); while (-1 != (len = input.read(data))) { raw.append(new String(data, 0, len)); } line = raw.toString(); input.close(); s.close(); } catch (Exception e) { System.out.println("response--- excep" + line + e.getMessage()); } return line; } EDIT.. private static String getConnectionString() { String connectionString = ""; if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) { connectionString = "?;interface=wifi"; } else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) { connectionString = "?;&deviceside=false"; } else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) { String carrierUid = getCarrierBIBSUid(); if (carrierUid == null) { connectionString = "?;deviceside=true"; } else { connectionString = "?;deviceside=false?;connectionUID=" + carrierUid + "?;ConnectionType=mds-public"; } } else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) { } return connectionString; } private static String getCarrierBIBSUid() { ServiceRecord[] records = ServiceBook.getSB().getRecords(); int currentRecord; for (currentRecord = 0; currentRecord < records.length; currentRecord++) { if (records[currentRecord].getCid().toLowerCase().equals("ippp")) { if (records[currentRecord].getName().toLowerCase() .indexOf("bibs") >= 0) { return records[currentRecord].getUid(); } } } return null; }