is there a reason to serialize and then deserialize an object? - serialization

I have a SOAP web service that someone developed at my work place and i try to learn it and i came across a move in the code that i can't get my head around. can someone explain to me the logic behind it? why would someone want to serialize an object and a line after to deserialize it?
**this is the whole code: if someone has a way to improve the code it will be appreciated: **
using IRail.BLL.SAP;
using IRail.Entities.SAP.Report;
using IRail.WebAPI.Heplers;
using Logger;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web.Script.Serialization;
using System.Web.Services;
namespace IRail.WebAPI
{
public class EventInfo
{
public string QMNUM { get; set; }
public string QMART { get; set; }
public string STATUS { get; set; }
public string MAHUT_CODE { get; set; }
public string MAHUT_TXT { get; set; }
public string START_DATE { get; set; }
public string START_TIME { get; set; }
public string END_DATE { get; set; }
public string END_TIME { get; set; }
public string ZQMNUM { get; set; }
public string QMTXT { get; set; }
public string IKUN { get; set; }
public string ZLONG { get; set; }
public string LAT { get; set; }
public string TPLNR { get; set; }
public string ZZKM_NUM { get; set; }
public string ZZTOKM_NUM { get; set; }
}
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class Events : System.Web.Services.WebService
{
public static readonly ILogger _logger = LogManager.GetLogger();
[WebMethod]
public string UpdateEvent(EventInfo eventInfo)
{
// create an instance of SapClient object an fill it with the input parameters,
// that passes by the url to the function using the eventInfo class.
SapClient SapArgs = new SapClient()
{
params_input = "",
QNUM = eventInfo.QMNUM,
QMART = eventInfo.QMART,
STATUS = eventInfo.STATUS,
MAHUT_CODE = eventInfo.MAHUT_CODE,
MAHUT_TXT = eventInfo.MAHUT_TXT,
START_DATE = eventInfo.START_DATE,
START_TIME = eventInfo.START_TIME,
END_DATE = eventInfo.END_DATE,
END_TIME = eventInfo.END_TIME,
ZQMNUM = eventInfo.ZQMNUM,
QMTXT = eventInfo.QMTXT,
IKUN = eventInfo.IKUN,
ZLONG = eventInfo.ZLONG,
LAT = eventInfo.LAT,
TPLNR = eventInfo.TPLNR,
ZZKM_NUM = eventInfo.ZZKM_NUM,
ZZTOKM_NUM = eventInfo.ZZTOKM_NUM,
ikunx = "",
ikuny = "",
operation_type = "",
returnZ = "",
returnM = "",
returnTrueCurves = "",
f = ""
};
string errorMsg = String.Empty;
string outputJson = String.Empty;
ApiHelper apiHelper = new ApiHelper();
try
{
// create an instance of JS Serializer.
var jss = new JavaScriptSerializer();
// serialize the object to convert it to json format.
JObject sapArgs = JObject.Parse(jss.Serialize(SapArgs));
// decerialize the object back from json format to pass the JSON string representation
// of the sapArgs object as the input to the callGPAsync method.
var dict = jss.Deserialize<Dictionary<string, string>>(sapArgs.ToString());
// create an instance of EventsEngine.
EventsEngine eventsEngine = new EventsEngine();
// assign the type of the event to the events object:
// check the event type.
SapArgs.operation_type = eventsEngine.CheckEventType(dict, ref errorMsg);
// assign the event type that has returned to the sapArgs object's operation_type parameter.
sapArgs["operation_type"] = SapArgs.operation_type; // "1";// set operation_type for test;
// if encountered an error return the content of it.
if (errorMsg != "") return "UpdateEvent ERROR: " + errorMsg;
_logger.Info($"Username: {Utils.GetUserName()}, UpdateEvent : {sapArgs.ToString()}, eventType :{SapArgs.operation_type}");
if (!string.IsNullOrWhiteSpace(apiHelper.getValueFromDict(dict, "IKUN")) && dict["IKUN"].ToString() == "Y")
{
var res = apiHelper.convertCoordiateWGSToITM(sapArgs).GetAwaiter().GetResult();
}
outputJson = apiHelper.callGPAsync(sapArgs).GetAwaiter().GetResult();
try
{
// if there is result from submitted job add operation_type
outputJson = outputJson.Replace("}", ", \"operation_type\" = \"" + SapArgs.operation_type + "\" }");
}
catch (Exception outputEx)
{
return "outputJson ERROR: " + outputEx;
}
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent(outputJson, System.Text.Encoding.UTF8, "application/json");
return outputJson;
}
catch (Exception ex)
{
_logger.Error(" UpdateEvent ERROR : " + SapArgs.ToString() + ", eventType :" + SapArgs.operation_type + ", errorMsg :" + errorMsg);
_logger.Error(ex);
return "UpdateEvent ERROR: update failed on exception. please check logs.";
}
//0. check with documentation - what are the parameters - in sap document
//0. log -> input call
//1. properties input validation -
// A. all inputs are correct //2.4 in documents ---> function in BLL that does the validation
//2. if all ok - -- delete prev event
//3. call GP service to update new event
//4. return success + log reult
}
}
}
I did not try anything i just want to understand the logic.

Related

Problems with converting FixedLength format to to csv using same class definition

I defined both FixedLength and Delimited attributes on a single class. It reads the fixed length file fine but fails when i try to write out a csv.
[FixedLengthRecord]
[DelimitedRecord(",")]
public class PCFFileHeader
{
[FieldFixedLength(2)] public string RecordType { get; set; }
[FieldFixedLength(25)] public string FileDescription { get; set; }
}
var engine = new MultiRecordEngine(typeof(PCFFileHeader), typeof(SecondHeader));
engine.RecordSelector = RecordSelector;
var output = engine.ReadFile(filePath);
// code to extract PCFHeader from output and create a list
var headerEngine = new DelimitedFileEngine<PCFFileHeader>();
headerEngine.WriteFile("header_" + DateTime.Now.ToString("yyyyMMddhhmmss"), pcfFileHeaderList);
You can't add both [FixedLengthRecord] and [DelimitedRecord] to the same class. FileHelpers will just treat it as [FixedLengthRecord]. With your current class, it will error if you do:
// This causes an exception because the class is not a delimited record definition
var delimitedHeaderEngine = new DelimitedFileEngine<PCFFileHeader>();
Instead, you should have two PCFFileHeader definitions, FixedPCFFileHeader and DelimitedPCFFileHeader.
[FixedLengthRecord]
public class FixedPCFFileHeader
{
[FieldFixedLength(2)] public string RecordType { get; set; }
[FieldFixedLength(25)] public string FileDescription { get; set; }
}
[DelimitedRecord(",")]
public class DelimitedPCFFileHeader
{
public string RecordType { get; set; }
public string FileDescription { get; set; }
}
class Program
{
static void Main(string[] args)
{
var fixedHeaderEngine = new FileHelperEngine<FixedPCFFileHeader>();
var recordsFixed = fixedHeaderEngine.ReadString("AADescription ");
Debug.Assert(recordsFixed.Count() == 1);
Debug.Assert(recordsFixed[0].RecordType == "AA");
Debug.Assert(recordsFixed[0].FileDescription == "Description ");
var delimitedHeaderEngine = new FileHelperEngine<DelimitedPCFFileHeader>();
var recordsDelimited = delimitedHeaderEngine.ReadString("AA,Description");
Debug.Assert(recordsDelimited.Count() == 1);
Debug.Assert(recordsDelimited[0].RecordType == "AA");
Debug.Assert(recordsDelimited[0].FileDescription == "Description");
var pcfFileHeaderList = new FixedPCFFileHeader[] { new FixedPCFFileHeader() { RecordType = "AA", FileDescription = "Description" } };
// If you want to output a header when exporting uncomment the following
//headerEngine.HeaderText = "header_" + DateTime.Now.ToString("yyyyMMddhhmmss");
var output = fixedHeaderEngine.WriteString(pcfFileHeaderList);
Debug.Assert(output == "AADescription \r\n");
Console.WriteLine("All OK");
Console.ReadLine();
}
}
If you want to automatically detect the correct format during import, you can use the FileHelpers Smart Format Detector.

C# - How to Upload large size video ( in GB ) to Amazon S3 bucket

I need to upload a large size video to Amazon S3 bucket.
I have a large size video and it
here is my class that i am using
public class CustomAmazon
{
public string tourName { get; set; }
public string driveName { get; set; }
public string tourID { get; set; }
public string driveID { get; set; }
public string key { get; set; }
public string bucketName { get; set; }
public string cloudFrontVideoUrl { get; set; }
public string amazonS3VideoUrl { get; set; }
public string filePath { get; set; }
}
and here is the Amazon Code for writing an object
static string WritingAnObject(CustomAmazon customAmazon)
{
try
{
var videoStream = new FileStream(customAmazon.filePath, FileMode.Open, FileAccess.Read);
// put a more complex object with some metadata and http headers.
string fileName = customAmazon.tourID + "/" + customAmazon.driveID + "/" + Guid.NewGuid() + "__" + Path.GetFileName(customAmazon.filePath);
PutObjectRequest titledRequest = new PutObjectRequest()
{
BucketName = customAmazon.bucketName,
Key = fileName,
InputStream = videoStream,
Timeout = new TimeSpan(4, 30, 30),
ContentType = "video/mov",
CannedACL = S3CannedACL.PublicRead
};
titledRequest.Metadata.Add("title", fileName);
titledRequest.Metadata.Add("drive", customAmazon.driveName);
client.PutObject(titledRequest);
Thread.Sleep(4000);
// Retrieve ACL for object
customAmazon.cloudFrontVideoUrl = customAmazon.cloudFrontVideoUrl + fileName;
customAmazon.key = fileName;
customAmazon.amazonS3VideoUrl = ReadConfig.AWSStorageUrl + fileName;
}
catch (AmazonS3Exception amazonS3Exception)
{
Logger.Write(amazonS3Exception.Message);
if (amazonS3Exception.ErrorCode != null &&
(amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") ||
amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
{
Console.WriteLine("Please check the provided AWS Credentials.");
Console.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
}
else
{
Logger.Write(string.Format("An error occurred with the message '{0}' when writing an object", amazonS3Exception.Message));
}
}
return customAmazon.amazonS3VideoUrl;
}
I am getting error while uploading large size video, while in small size videos it is working fine.
Yes, I got the answer, I tried it using multicast and it is working fine, here is my solution
Here is my class
public class CustomAmazon
{
public string tourName { get; set; }
public string driveName { get; set; }
public string tourID { get; set; }
public string driveID { get; set; }
public string key { get; set; }
public string bucketName { get; set; }
public string cloudFrontVideoUrl { get; set; }
public string amazonS3VideoUrl { get; set; }
public string filePath { get; set; }
}
and here is my solution
I just call below method to upload large video file after connecting credentials
/// <summary>
/// Method used for DFI (website or API) users to upload a file on Amazon S3 storage
/// </summary>
/// <param name="customAmazon"></param>
/// <returns>CustomAmazon class object </returns>
public CustomAmazon UploadFiletoAmazonS3Storage(CustomAmazon customAmazon)
{
using (client = new AmazonS3Client(ReadConfig.AWSAccessKeyId, ReadConfig.AWSSecretKey, RegionEndpoint.USEast1))
{
Console.WriteLine("Writing an object");
WritingAnLargeObject(customAmazon);
}
return customAmazon;
}
public static string WritingAnLargeObject(CustomAmazon customAmazon)
{
// List to store upload part responses.
List<UploadPartResponse> uploadResponses = new List<UploadPartResponse>();
string fileName = string.Empty;
// Giving custom filename to original file
if (!string.IsNullOrEmpty(customAmazon.tourID) && (!string.IsNullOrEmpty(customAmazon.driveID)))
{
fileName = customAmazon.tourID + "/" + customAmazon.driveID + "/" + Guid.NewGuid() + "___" + Regex.Replace(Path.GetFileName(customAmazon.filePath), #"\s", "");
}
else
{
fileName = Guid.NewGuid() + "___" + Regex.Replace(Path.GetFileName(customAmazon.filePath), #"\s", "");
}
// 1. Initialize MultipartUploadRequest.
InitiateMultipartUploadRequest initiateRequest = new InitiateMultipartUploadRequest
{
BucketName = customAmazon.bucketName,
Key = fileName,
ContentType = "video/mov",
CannedACL = S3CannedACL.PublicRead
};
InitiateMultipartUploadResponse initResponse =
client.InitiateMultipartUpload(initiateRequest);
// 2. Upload video in small Parts of 5 MB.
long contentLength = new FileInfo(customAmazon.filePath).Length;
long partSize = 5 * (long)Math.Pow(2, 20); // 5 MB
try
{
long filePosition = 0;
for (int index = 1; filePosition < contentLength; index++)
{
UploadPartRequest uploadRequest = new UploadPartRequest
{
BucketName = customAmazon.bucketName,
Key = fileName,
UploadId = initResponse.UploadId,
PartNumber = index,
PartSize = partSize,
FilePosition = filePosition,
FilePath = customAmazon.filePath
};
// Upload part and add response to our list.
uploadResponses.Add(client.UploadPart(uploadRequest));
filePosition += partSize;
}
// Step 3: complete.
CompleteMultipartUploadRequest completeRequest = new CompleteMultipartUploadRequest
{
BucketName = customAmazon.bucketName,
Key = fileName,
UploadId = initResponse.UploadId,
//PartETags = new List<PartETag>(uploadResponses)
};
completeRequest.AddPartETags(uploadResponses);
customAmazon.key = fileName;
CompleteMultipartUploadResponse completeUploadResponse = client.CompleteMultipartUpload(completeRequest);
customAmazon.cloudFrontVideoUrl = customAmazon.cloudFrontVideoUrl + fileName;
customAmazon.amazonS3VideoUrl = ReadConfig.AWSStorageUrl + fileName;
}
catch (Exception exception)
{
Logger.Write(exception.Message);
Console.WriteLine("Exception occurred: {0}", exception.Message);
AbortMultipartUploadRequest abortMPURequest = new AbortMultipartUploadRequest
{
BucketName = customAmazon.bucketName,
Key = fileName,
UploadId = initResponse.UploadId
};
client.AbortMultipartUpload(abortMPURequest);
}
return fileName;
}
and Finally I uploaded the video into S3 bucket

Retrieve values from SQL database - EF

I'm trying to figure out how to pull values from a SQL database and display this in a razor view.
I have the following class using Entity Framework (I believe)
public class EventLog
{
[Key]
public int Id { get; set; }
public int EventId { get; set; }
public int MaxDelegates { get; set; }
public string Code { get; set; }
public DateTime End { get; set; }
public string Title { get; set; }
}
And I want to map title to DBTitle in the following model:
public class CourseDetailVM : CourseDetailSummaryVM
{
public EventLog DBTitle { get; set; }
}
I then want to see this in the following view:
#using TSW.Web.Helpers
#model TSW.Web.ViewModels.CourseDetailVM
#{
Layout = "~/Views/_Master.cshtml";
}
#Model.DBTitle.Title;
I have the following controller already in place (sorry for the length I plan to reduce this down):
public class CourseDetailController : BaseRenderController<CourseDetailPageDT>
{
private readonly ISitePageFactory _pageFactory = null;
private readonly IEventService _eventService = null;
public CourseDetailController(IEventService eventService, ISitePageFactory pageFactory)
{
_pageFactory = pageFactory;
_eventService = eventService;
}
public async Task<ActionResult> CourseDetail()
{
var homepage = _pageFactory.GetCurrentHomepage();
var model = Mapper.Map<CourseDetailVM>(CurrentContent);
model.Email = homepage.ContactEmail;
model.PhoneNumber = homepage.HeaderPhoneNumber;
model.InnerPageHeader.ShowHeading = true;
model.InnerPageHeader.Title = model.PageTitle;
if (model.Categories.Count == 1)
{
var categoryTagId = model.Categories.First().Id;
var contentTypeAlias = DocumentTypeHelper.GetDocumentTypeAlias<CourseListingPageDT>();
var courseCategoryPage = Umbraco.TypedContentAtXPath($"//{contentTypeAlias}")
.FirstOrDefault(x => x.GetPropertyValue<int>(Constants.DocumentTypes.CourseListingPage.Category) == categoryTagId);
if (courseCategoryPage != null)
{
model.InnerPageHeader.BackLink = Mapper.Map<LinkItem>(courseCategoryPage.Id);
}
}
try
{
model.Events = await _eventService.GetEventsForCourse(CurrentContent.AdministrateId);
}
catch (Exception ex)
{
model.Events = new StaticPagedList<Event>(Enumerable.Empty<Event>(), 1, 1, 0);
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
if (CurrentContent.Graphic != 0)
{
model.InnerPageHeader.Graphic = Mapper.Map<CtaItem>(CurrentContent.Graphic);
}
return View(model);
}
}
I've tried every suggestion I can google to add the mapping in the controlling but can't get my head around this simple function of pulling the value from a SQL database into the razor view.
Could anyone help me out?

How to resolve an error with WCF data contract -Message = "There was an error while trying to serialize parameter

I have two data contracts of same contents in two different namespaces. i have copied one datacontract to another and
passed to a particular method. but it is giving the below error and throwing exception. it is not going into that method.
Please let me know any ideas /suggestions on how to resolve this.Appreciate your help:
Exception errror:
{"Type 'System.Collections.Generic.List`1[[GlobalWcfServiceLib.TopicDetailsInfo, GlobalWcfContracts, Version=1.2.2.0, Culture=neutral,
PublicKeyToken=17c64733a9775004]]' with data contract name 'ArrayOfTopicDetailsInfo:http://CName.GlobalService/11.1/2010/11'
is not expected. Consider using a DataContractResolver or add any types not known statically to the list of
known types - for example, by using the KnownTypeAttribute attribute or by
adding them to the list of known types passed to DataContractSerializer."}
Message = "There was an error while trying to serialize parameter
http://CName.SharedServices.DBServiceLib:subscriptionDataContract.
The InnerException message was 'Type 'System.Collections.Generic.List`1
[[GlobalWcfServiceLib.TopicDetailsInfo,
GlobalWcfContra...
//////
Here is my scenario : i am copying the data from dc to new data contract as below. after copying , when i am executing the createsubscriptions method i am getting the above mentioned error. i have given the details of data contract and error attached to this question. please refer to that as well.
Method1(SubscriptionDataContracts dc)
{
SubscriptionDataContract subscriptionDataContract = new SubscriptionDataContract();
List<SubscriptionTopicInfo> topicsInfo = dc.TopicList;
List<SubscriptionTopic> newTopicsList = new List<SubscriptionTopic>();
subscriptionDataContract.ExtensionData = dc.ExtensionData;
subscriptionDataContract.UserID = dc.UserID;
for (int i = 0; i < topicsInfo.Count; i++)
{
SubscriptionTopic topic = new SubscriptionTopic();
topic.DBHandle = topicsInfo[i].DBHandle;
topic.Topic = topicsInfo[i].Topic;
topic.Target = topicsInfo[i].Target;
newTopicsList.Add(topic);
}
subscriptionDataContract.TopicList = newTopicsList;
CreateSubscriptions(subscriptionDataContract); //getting the above mentioned error in another dll after going into this method
}
////////////////////////////////
//My data contract
[DataContract(Name = "TopicDetailsInfo", Namespace = "http://CName.GlobalService")]
[Serializable]
public class TopicDetailsInfo
{
protected object topic;
protected object baseObjectType;
[DataMember]
public object BaseObjectType
{
get
{
return baseObjectType;
}
set
{
baseObjectType = value;
}
}
[DataMember]
public object TopicID
{
get
{
return topic;
}
set
{
topic = value;
}
}
static public TopicDetailsInfo CreateTopic<T, mT>(IComparable<T> objectType, IComparable<mT> objectID)
{
var topicDetails = new TopicDetailsInfo();
topicDetails.BaseObjectType = objectType;
topicDetails.TopicID = objectID;
return topicDetails;
}
}
[DataContract(Name = "SubscriptionTopicInfo", Namespace = "http://CName.GlobalService")]
[KnownType(typeof(List<TopicDetailsInfo>))]
[Serializable]
public class SubscriptionTopicInfo
{
private object topic;
private object target;
private object creator;
[DataMember]
public object Topic
{
get
{
return topic;
}
set
{
topic = value;
}
}
[DataMember]
public object Target
{
get
{
return target;
}
set
{
target = value;
}
}
[DataMember]
public object DBHandle
{
get
{
return creator;
}
set
{
creator = value;
}
}
static public SubscriptionTopicInfo CreateSubscriptions<T, mT, nT>(IList<TopicDetailsInfo> topic, IComparable<mT> target, IComparable<nT> handle)
{
var subscriptionTopic = new SubscriptionTopicInfo();
subscriptionTopic.Target = target;
subscriptionTopic.Topic = topic;
subscriptionTopic.DBHandle = handle;
return subscriptionTopic;
}
}
[DataContract(Name = "SubscriptionData", Namespace = "http://CName.GlobalService")]
[KnownType(typeof(List<SubscriptionTopicInfo>))]
[Serializable]
public class SubscriptionDataContracts : IExtensibleDataObject
{
private ExtensionDataObject extensionDataObjectValue;
[DataMember]
public string UserID
{
get;
set;
}
[DataMember]
public string ProjectID
{
get;
set;
}
[DataMember]
public string FromDiscipline
{
get;
set;
}
[DataMember]
public string ModuleID
{
get;
set;
}
[DataMember]
public string SessionID
{
get;
set;
}
[DataMember]
public List<SubscriptionTopicInfo> TopicList
{
get;
set;
}
public ExtensionDataObject ExtensionData
{
get
{
return extensionDataObjectValue;
}
set
{
extensionDataObjectValue = value;
}
}
}

Google Cell Tower Location API: Changed?

For the last few months I've been finding the locations of cell towers as we use their cellid and areaid, based on the following code:
public class GoogleService
{
public GoogleCell GetCellInfo(string lac, string mnc, string mcc, string cellID)
{
try
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("https://www.google.com/loc/json");
myReq.Method = "POST";
myReq.ContentType = "application/jsonrequest";
string postData = "{\"cell_towers\": [{\"location_area_code\": \"" + lac + "\", \"mobile_network_code\": \"" + mnc + "\", \"cell_id\": \"" + cellID + "\", \"mobile_country_code\": \"" + mcc + "\"}], \"version\": \"1.1.0\", \"request_address\": \"true\"}";
myReq.ContentLength = postData.Length;
StreamWriter stOut = new StreamWriter(myReq.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(postData);
stOut.Close();
HttpWebResponse webresponse;
webresponse = (HttpWebResponse)myReq.GetResponse();
Encoding enc = System.Text.Encoding.UTF8;
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);
string Response = loResponseStream.ReadToEnd();
loResponseStream.Close();
webresponse.Close();
GoogleCell Mycell = JsonConvert.DeserializeObject<GoogleCell>(Response);
return Mycell;
}
catch (Exception ex)
{
string strErr = ex.Message;
if (ex.InnerException != null)
{
strErr += ": " + ex.InnerException.Message;
}
MessageBox.Show(strErr);
return new GoogleCell();
}
}
}
public class GoogleCell
{
public GoogleCell() { }
public GoogleCell(string mnc, string mcc, string lac)
{
this.Mnc = mnc;
this.Mcc = mcc;
this.Lac = lac;
}
public string Mnc { get; set; }
public string Mcc { get; set; }
public string Lac { get; set; }
public string CellID { get; set; }
public Location location { get; set; }
public class Location
{
public Location() { }
public Location(string latitude, string longitude)
{
this.latitude = latitude;
this.longitude = longitude;
}
public string latitude { get; set; }
public string longitude { get; set; }
public Address address { get; set; }
public class Address
{
public Address() { }
public string country { get; set; }
public string country_code { get; set; }
public string city { get; set; }
public string region { get; set; }
public string street { get; set; }
public string street_number { get; set; }
public string postal_code { get; set; }
}
}
The code worked flawlessly until sometime between one and two weeks ago, when it started returning error 400: Bad Request when it does the GetRequestStream().
My code hasn't changed.
I can't find any record of the API's parameters changing.
What else could be going on? This uses Google Gears, which has been deprecated for a while now, but I can't find any doco on a replacement that finds cell towers.
any ideas?
I ended up kicking Google to the curb and using OpenCellID:
public CellTowerPOCO GetCellInfo_OpenCellID(string lac, string mnc, string mcc, string cellID)
{
try
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(string.Format("http://www.opencellid.org/cell/get?mcc={0}&mnc={1}&cellid={2}&lac={3}",mcc,mnc,cellID,lac));
HttpWebResponse webresponse;
webresponse = (HttpWebResponse)myReq.GetResponse();
//Encoding enc = System.Text.Encoding.UTF8;
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream());
string Response = loResponseStream.ReadToEnd();
loResponseStream.Close();
webresponse.Close();
CellTowerPOCO Mycell = new CellTowerPOCO();
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(Response);
Mycell.location.latitude = xdoc.ChildNodes[1].FirstChild.Attributes["lat"].Value;
Mycell.location.longitude = xdoc.ChildNodes[1].FirstChild.Attributes["lon"].Value;
Mycell.Mcc = mcc;
Mycell.CellID = cellID;
Mycell.Mnc = mnc;
//MessageBox.Show(xdoc.ChildNodes[0].InnerText);
return Mycell;
}
catch (Exception ex)
{
string strErr = ex.Message;
if (ex.InnerException != null)
{
strErr += ": " + ex.InnerException.Message;
}
MessageBox.Show(strErr);
return new CellTowerPOCO();
}
}