List not populating dropdown - asp.net

I am using a standard list method for my lookups I use this for winforms and works fine just trying to re use on web and its not displaying my items.
public List<SISLookupLists> GetGender()
{
List<SISLookupLists> lookups = new List<SISLookupLists>();
try
{
var q = from lookup in schoolEntities.Genders
orderby lookup.description
select new
{
Code = lookup.code,
Description = lookup.description.Trim()
};
if (q != null)
{
Array.ForEach(q.ToArray(), l =>
{
lookups.Add(new SISLookupLists(l.Code, l.Description));
});
}
}
catch (Exception ex)
{
throw new EntityContextException("GetGender failed.", ex);
}
return lookups;
}
public SISDBContext _db = new SISDBContext();
rdGender.DataSource = _db.GetGender();
rdGender.DataTextField = "Description";
rdGender.DataValueField= "Code";
rdGender.DataBind();
Any idea what I am doing wrong here guys.

Related

after successful data insert print the information to another page

After saving my data to database I want to display the information entered by the user in another page (printRegInfo.cshtml). How can I do that?
public ActionResult Create(FirmServiceRegistrationViewModel firmServiceReg)
{
try
{
ViewBag.ServiceId = new SelectList(db.ServicesModels, "ServiceId", "ServiceName");
if (ModelState.IsValid)
{
FirmsModel frm_ = new FirmsModel();
frm_.Name = firmServiceReg.Name;
frm_.PropName = firmServiceReg.PropName;
frm_.Address = firmServiceReg.Address;
db.FirmsModels.Add(frm_);
db.SaveChanges();
int frmId = frm_.FirmId;
FirmServiceRegistrationModel frmServReg = new FirmServiceRegistrationModel();
frmServReg.ServiceId_ = firmServiceReg.ServiceId;
frmServReg.FirmId_ = frmId;
db.FirmServiceRegistrationModels.Add(frmServReg);
db.SaveChanges();
}
return View();
}
catch (Exception)
{
throw;
}
}
Now on successful insert of data I want to pass the data entered by the user [Name, PropName, Address] to the view page say printRegInfo.cshtml. How can I do that?
The below code just get entered info and carried to another page using temp data. Hence you need to cast the as per model data and populate in view.
public ActionResult Create(FirmServiceRegistrationViewModel firmServiceReg)
{
try
{
ViewBag.ServiceId = new SelectList(db.ServicesModels, "ServiceId", "ServiceName");
if (ModelState.IsValid)
{
FirmsModel frm_ = new FirmsModel();
frm_.Name = firmServiceReg.Name;
frm_.PropName = firmServiceReg.PropName;
frm_.Address = firmServiceReg.Address;
db.FirmsModels.Add(frm_);
db.SaveChanges();
int frmId = frm_.FirmId;
FirmServiceRegistrationModel frmServReg = new FirmServiceRegistrationModel();
frmServReg.ServiceId_ = firmServiceReg.ServiceId;
frmServReg.FirmId_ = frmId;
db.FirmServiceRegistrationModels.Add(frmServReg);
db.SaveChanges();
TempData["FirmRegData"]=frm_;
}
return RedirectToAction("printRegInfo","ControllerName");
}
catch (Exception)
{
throw;
}
}
public ActionResult printRegInfo()
{
try
{
FirmsModel frm_ =(FirmsModel)TempData["FirmRegData"];
// Here you will get all entered info.
}
return view(frm_);
}
catch (Exception)
{
throw;
}
}

Getting Null data from google adwords api

I want to fetch location details for all the ads from google adwords but I am getting null entries.I am not able to get any data from adwords api .Help me in That as according to my knowledge there is not problem with my code and I am not able to find any solution for that.My code that I have tried is written below.
public void GetLocationAds()
{
AdWordsUser user = new AdWordsUser();
{
try
{
int offset = 0;
// Create selector.
using (CampaignCriterionService campaignCriterionService =
(CampaignCriterionService)user.GetService(AdWordsService.v201809.CampaignCriterionService))
{
Selector selector = new Selector()
{
fields = new string[]
{
CampaignCriterion.Fields.CampaignId,
CampaignCriterion.Fields.CampaignCriterionStatus,
//Location.Fields.LocationName,
//Location.Fields.CriteriaType,
//Location.Fields.ParentLocations,
//LocationCriterion.Fields.CanonicalName,
//LocationCriterion.Fields.CountryCode,
CampaignCriterion.Fields.IsNegative,
},
// predicates = new Predicate[]
//{
// Predicate.Equals( "CriteriaType","LOCATION"),
//},
paging = Paging.Default,
ordering = new OrderBy[]
{
OrderBy.Asc( CampaignCriterion.Fields.CampaignId)
}
};
CampaignCriterionPage page = new CampaignCriterionPage();
do
{
// Get the ad groups.
page = campaignCriterionService.get(selector);
// Display the results.
if (page != null && page.entries != null)
{
int j = selector.paging.startIndex;
foreach (CampaignCriterion campaignCriterion in page.entries)
{
var campaignId = campaignCriterion.campaignId;
bool IsLocation = campaignCriterion.isNegative;
var CampaignCriterionType = campaignCriterion.CampaignCriterionType;
}
}
else
{
Console.Write("No campaignCriterion were found.");
}
selector.paging.IncreaseOffset();
}
while (selector.paging.startIndex < page.totalNumEntries);
}
}
catch (Exception ex)
{
}
}
}
Kindly help me in that.

entity framework savechanges not Working MVC

i am saving data through Model. SaveChanges not saving new record in database.
and not throwing any exception. kindly help anyone to get me out this situation.
[HttpPost]
public ActionResult SaveAmbulanceLocation1(Ambulance_Position AMmodel)
{
db.Configuration.ProxyCreationEnabled = false;
// var m = db.Ambulance_Position.FirstOrDefault(x => x.A_unique_ID == AMmodel.A_unique_ID);
try
{
if (ModelState.IsValid)
{
AMmodel.Date_Time = System.DateTime.Now;
db.Ambulance_Position.Add(AMmodel);
db.SaveChanges();
}
}
catch (Exception e )
{
}
return Json("saved", JsonRequestBehavior.AllowGet);
}
I would suggest making changes to your ActionMethod as shown below; basis this accepted Stackoverflow answer.
Note that this example is not tested though; and I might be wrong...
[HttpPost]
public ActionResult SaveAmbulanceLocation1(Ambulance_Position AMmodel)
{
db.Configuration.ProxyCreationEnabled = false;
Ambulance_Position ambulance_position = new Ambulance_Position();
ambulance_position = AMmodel;
// var m = db.Ambulance_Position.FirstOrDefault(x => x.A_unique_ID == AMmodel.A_unique_ID);
try
{
if (ModelState.IsValid)
{
//AMmodel.Date_Time = System.DateTime.Now;
ambulance_position.Date_Time = System.DateTime.Now;
db.Ambulance_Position.Add(ambulance_position);
db.SaveChanges();
}
}
catch (Exception e)
{
}
return Json("saved", JsonRequestBehavior.AllowGet);
}

WebAPI call hangs when return a large amount of data

I have a web api call that I recently added to my app. I returns a complete list of all countries, states and cities in the app (currently 486 rows) I perform this call when all of the reference data for my application loads (I have a base loading page and call the function in my startup class to load all the data there). The challenge is that the call to get all my countries.... hangs and eventually I get "The operation was canceled" error. If I modify my stored procedure that selects the data from the database on the server to only return say 20 rows, it runs fine. Any suggestions?
Below is the code from the startup class:
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace GBarScene
{
class StartUpClass
{
public event GeneralDataLoad BaseDataLoadComplete;
public async Task<GBSStartUpEventArgs> ProcessStartup()
{
GBSStartUpEventArgs lobj_EventArgs;
lobj_EventArgs = new GBSStartUpEventArgs();
App.InStartUpDataLoad = true;
try
{
if (!App.IsGeolocationEnabled)
{
lobj_EventArgs.ErrorOccurred = true;
lobj_EventArgs.ShowRetry = true;
lobj_EventArgs.ShowWebSite = false;
lobj_EventArgs.ErrorMessage = resourcestrings.GetValue("NoLocationServicesMessage");
}
else if (!App.InternetIsAvailable)
{
lobj_EventArgs.ErrorOccurred = true;
lobj_EventArgs.ErrorMessage = resourcestrings.GetValue("NoInternetConnectionFound");
lobj_EventArgs.ShowRetry = true;
lobj_EventArgs.ShowWebSite = false;
}
else
{
Debug.WriteLine("Process StartUp");
await Task.Delay(500);
//Reset values
ViewModelObjects.DayOfWeek.DataLoadProcessed = false;
ViewModelObjects.Languages.DataLoadProcessed = false;
if (await ViewModelObjects.DayOfWeek.LoadData() == false)
// //try it once more
await ViewModelObjects.DayOfWeek.LoadData();
Debug.WriteLine("GBar After DayofWeek Load");
await ViewModelObjects.Languages.LoadData();
Debug.WriteLine("GBar After Languages Load");
if ((ge_AppMode)ViewModelObjects.AppSettings.AppMode == ge_AppMode.CitySelected)
{
//We need to reload the NearbyCities and set the selected one
await ViewModelObjects.NearbyCities.LoadData();
}
Debug.WriteLine("Before load of coutries");
await ViewModelObjects.CountryStateCity.LoadData();
Debug.WriteLine("After load of coutries");
Debug.WriteLine("Count: " + ViewModelObjects.CountryStateCity.CountryItems_ForList.Count.ToString());
ViewModelObjects.NumberOfResults.LoadData();
ViewModelObjects.Perspectives.LoadData();
ViewModelObjects.SearchRadiuses.LoadData();
ViewModelObjects.UseMetric.LoadData();
while (!ViewModelObjects.DayOfWeek.DataLoadProcessed && !ViewModelObjects.Languages.DataLoadProcessed && !App.IsGeolocationEnabled)
{
await Task.Delay(100);
}
if (App.BaseDataLoadError)
{
lobj_EventArgs.ErrorOccurred = true;
lobj_EventArgs.ShowRetry = true;
lobj_EventArgs.ShowWebSite = true;
lobj_EventArgs.ErrorMessage = resourcestrings.GetValue("ErrorLoadingReferenceData");
}
}
Debug.WriteLine("StartUp Process Ended");
BaseDataLoadComplete(this, lobj_EventArgs);
}
catch (Exception ex)
{
App.ProcessException(ex);
}
App.InStartUpDataLoad = false;
return lobj_EventArgs;
}
}
}
This is the helper class that makes all the WebAPI calls:
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace GBarScene
{
public class WebAPICaller: IDisposable
{
HttpClient iobj_HTTPClient = null;
public void Dispose()
{
if (iobj_HTTPClient != null)
iobj_HTTPClient.Dispose();
}
public async Task<string> HTTPGetWebServiceAsync(string ps_URI)
{
string ls_Response = "";
string ls_JSONData = "";
string ls_Prefix = "";
try
{
iobj_HTTPClient = await GetClient();
switch (Device.RuntimePlatform)
{
case Device.Android:
ls_Prefix = App.APIStandardPrefix;
break;
//case Device.Android:
// ls_Prefix = App.APISecurePrefix;
// break;
//case Device.Windows:
//case Device.WinPhone:
// ls_Prefix = App.APISecurePrefix;
// break;
default:
ls_Prefix = App.APISecurePrefix;
break;
}
Debug.WriteLine("before api call");
iobj_HTTPClient.BaseAddress = new Uri(ls_Prefix);
ls_JSONData = await iobj_HTTPClient.GetStringAsync(ps_URI);
Debug.WriteLine("after api call");
ls_Response = System.Net.WebUtility.HtmlDecode(ls_JSONData);
}
catch (Exception ex)
{
Debug.WriteLine("api call error");
App.ProcessException(ex);
}
return ls_Response;
}
public async Task<bool> HTTPPostWebService(string ps_URI, object pobj_BodyObject)
{
HttpResponseMessage lobj_HTTPResponse = null;
bool lb_Response = false;
HttpContent lobj_Content = null;
try
{
if (iobj_HTTPClient != null)
iobj_HTTPClient = await GetClient();
iobj_HTTPClient.BaseAddress = new Uri(App.APISecurePrefix);
lobj_Content = new StringContent(JsonConvert.SerializeObject(pobj_BodyObject == null ? "" : pobj_BodyObject));
lobj_Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
lobj_HTTPResponse = await iobj_HTTPClient.PostAsync(ps_URI, lobj_Content);
if (!lobj_HTTPResponse.IsSuccessStatusCode)
{
Exception lobj_Exception = new Exception(lobj_HTTPResponse.ToString());
lobj_Exception.Source = "HTTPGetWebService for: " + ps_URI;
App.ProcessException(lobj_Exception);
}
else
{
lb_Response = true;
}
}
catch (Exception ex)
{
App.ProcessException(ex);
}
finally
{
if (lobj_HTTPResponse != null)
{
lobj_HTTPResponse.Dispose();
}
//Debug.WriteLine("WebAPICaller-CallWebService-1: Done");
}
return lb_Response;
}
private async Task<HttpClient> GetClient()
{
HttpClient lobj_HTTPClient = null;
if (lobj_HTTPClient == null)
{
lobj_HTTPClient = new HttpClient();
lobj_HTTPClient.DefaultRequestHeaders.Add("Accept", "application/json");
lobj_HTTPClient.MaxResponseContentBufferSize = 2147483647;
lobj_HTTPClient.Timeout = new TimeSpan(0,0,0,0,60000);
}
return lobj_HTTPClient;
}
}
}
Sorry I forget to include the method in the CountryStateCity view model that calls the webapi helper class.
public async Task<bool> LoadData()
{
string ls_Response = "";
string ls_WorkURI = "";
WebAPICaller lobj_WebAPICaller = null;
bool lb_DataLoaded = false;
try
{
IsDataLoaded = false;
//Debug.WriteLine("City Data Load");
lobj_WebAPICaller = new WebAPICaller();
ls_WorkURI = ic_CoutryStateCityAPIUrl.Replace("{Language}", "EN");
ls_Response = await lobj_WebAPICaller.HTTPGetWebServiceAsync(ls_WorkURI);
if (ls_Response.Trim().Length == 0)
{
AddErrorEntry();
}
else
{
CountryItems_ForList = new ObservableCollection<GBSCountry_ForList>();
StateItems_ForList = new ObservableCollection<GBSState_ForList>();
CityItems_ForList = new ObservableCollection<GBSCity_ForList>();
iobj_CountryStateCity = JsonConvert.DeserializeObject<ObservableCollection<GBSCountryStateCity>>(ls_Response);
//Now load the display lists
CountryItems_ForList = new ObservableCollection<GBSCountry_ForList>(
(from lobj_Country in iobj_CountryStateCity
select new GBSCountry_ForList()
{
ID = lobj_Country.Country_Code,
Value = lobj_Country.Country_Name_Text
}).Distinct().ToList());
CountryItems_ForList.Insert(0, new GBSCountry_ForList
{
ID = "XX",
Value = "Base Value"
});
lb_DataLoaded = true;
}
}
catch (Exception ex)
{
AddErrorEntry();
App.ProcessException(ex);
}
finally
{
IsDataLoaded = true;
if (lobj_WebAPICaller != null)
lobj_WebAPICaller.Dispose();
}
return lb_DataLoaded;
}
So after much time, I believe I figured out what the problem is. The problem started to manifest itself again with smaller amounts of data and I could not figure out why. The problem appeared. The issue appears to be the IP address I was using. (I was using the IP address of the actual laptop I was hosting both the App and WebAPIs on.) It appears you have to use one of the other network adaptors for the emulator to have this work reliably.
Here are the steps I used to resolved this:
I launched my Windows 10 mobile emulator.
Click on the >> (Tools) icon in the tool bar of the emulator.
Click on the Network tab of the Additional Tools window.
Look in the list for the network adaptor labeled Desktop Adaptor #1 and copy the IP address.
Edit the Applicationhost.config file in the folder of the WebAPI project.
Find the entry in the file for site name="XXXXX" where XXXXX is the name of the Visual Studio project you are hosting your WebAPIs in.
Within the section of the entry for your WebAPI project, add a binding for the IP address you copied from in step 4. It should look something like this:
<binding protocol="http" bindingInformation="*:56952:169.254.69.220" />
Where 56952 is the port my IIS Express is hosting the WebAPIs on and 169.254.69.220 is the IP address I copied from step 4. After adding this, I was able to connect to locally hosted WebAPIs in IIS Express.
Hope this helps.

add dummy column in LINQ fetch query

How to return the List in LINQ query while adding a dummy column,
How to return qry as LIST.
public static List<MSDNMagazine.emp> FetchEmp()
{
try
{
MSDNMagazine.JsonDataContext context = new MSDNMagazine.JsonDataContext();
var qry = from p in context.emps
select new
{
emp_cod = p.emp_cod,
emp_nam = p.emp_nam,
test = "0"
};
return (List< >)qry;
}
catch (Exception ex)
{
throw ex;
}
}
select new emp //the name of the class
{
emp_cod = p.emp_cod,
emp_nam = p.emp_nam,
test = "0"
};
return qry.ToList();
Use the ToList() Extension method.
return qry.ToList();

Resources