By sending the following APNS-Payload:
{"aps":{"alert":"test Push","badge":1,"sound":"default"},
"objid":"SomeID","vid":"4229", "title":"aTitle","type":"queryform",
"idArray":["-100", "SomeID"]}`
The following method converts the NSDictionary to a class(notificationInfo is the userInfo from "receivedNotification".
Following problem: if the ObjectForKey:"idArray" to get the "idArray" is equal the key in the payload, the variable objid is null. But objid exists in the notificationInfo. If I rename "idArray" e.g. to Idarray, objid would be set.
ApnsNotificationInfo GetApnsNotificationInfo(NSDictionary notificationInfo)
{
var apnsInfo = new ApnsNotificationInfo();
if (notificationInfo == null || notificationInfo.Count == 0)
return apnsInfo;
var idArray = notificationInfo.ObjectForKey(new NSString("idArray")) as NSArray;
if (idArray != null && idArray.Count > 0)
{
var articleId = (idArray.Count == 2) ?
idArray.GetItem<NSNumber>(1) :
idArray.GetItem<NSNumber>(0);
if (articleId == null)
return apnsInfo;
apnsInfo.ArticleId = articleId.Int32Value;
if (idArray.Count == 2)
{
var categoryId = idArray.GetItem<NSNumber>(0);
if (categoryId != null)
apnsInfo.CategoryId = categoryId.Int32Value;
}
}
NSString message = null;
var aps = notificationInfo.ObjectForKey(new NSString("aps")) as NSDictionary;
if (aps != null)
message = aps.ObjectForKey(new NSString("alert")) as NSString;
if (message != null)
apnsInfo.Message = message.ToString();
var title = notificationInfo.ObjectForKey (new NSString ("title")) as NSString;
var type = notificationInfo.ObjectForKey (new NSString ("type")) as NSString;
var objid = notificationInfo.ObjectForKey (new NSString ("objid")) as NSString;
var vid = notificationInfo.ValueForKey (new NSString ("vid")) as NSString;
if(!string.IsNullOrEmpty (title)){
apnsInfo.Title = title;
}
if (!string.IsNullOrEmpty (type)) {
apnsInfo.Type = type;
if(objid != null){
apnsInfo.requestID = objid.ToString ();
}
if(vid != null){
apnsInfo.vid = Convert.ToInt32 (vid);
}
}
return apnsInfo;
}
Another explanation for my problem: if i send this payload:
{"aps":{"alert":"test Push","badge":1,"sound":"default"}, "objid":"SomeID","vid":"4229", "title":"aTitle","type":"queryform", "Idarray":["-100", "SomeID"]}
var objid = notificationInfo.ObjectForKey (new NSString ("objid")) as NSString;
objid would be set. If the array in the payload is called: idArray, objid = null
This is really weird. I hope someone can help.
So although I don't entirely understand your question, as you said yourself you can solve the problem by pulling out 'objid' directly, there are a few things that need to be amended in your payload and your code to adhere to best practices.
The payload I believe should be as follows: (You miss some defining brackets after objid, and at the end of the idArray).
{"aps":{"alert":"test Push","badge":1,"sound":"default"},
"objid":{"SomeID","vid":"4229", "title":"aTitle","type":"queryform",
"idArray":["-100", "SomeID"]}}
Also your code is not using null propagation correctly, and will cause you issues in the future. if your checking for null, you must also propogate the Count otherwise it will likely cause an exception to be thrown.
if (idArray != null && idArray?.Count > 0)
{
}
It's also worth noting that often JSON deserialises property names in lower case. This can differ between deserialisers however.
Related
I am trying to design a credential retrieval process. I tried using HttpRequestBase. However, I am unable to move further. HttpRequestBase only takes string but, I have to pass int. The database has 'EmailID as string' and 'TaxID as int' Following are the two scenarios I am having trouble with.
Scenario 1:
string EmailID = Request["EmailID"];
int TaxID = Request[TaxID];
//Tax ID is having following errors
//Error CS1503: Argument 1: cannot convert from 'int' to 'string'
//Error CS0165: Use of unassigned local variable 'TaxID'
SUPRTestingDBEntities2 dbcontrol = new SUPRTestingDBEntities2();
var userAuth = (from data in dbcontrol.SUPRTesting where data.EmailID == EmailID
&& data.TaxID == TaxID
select data).FirstOrDefault();
if (userAuth != null)
{
Session["EmailID"] = userAuth.EmailID;
Session["LoginID"] = userAuth.LoginID;
return RedirectToAction("LIDAuthentication", "Corporation");
}
else if (userAuth == null)
{
return View();
}
Scenario 2, here I changed TaxID type to string (line 2), which throws the error in line 5:
string EmailID = Request["EmailID"];
string TaxID = Request[TaxID];
SUPRTestingDBEntities2 dbcontrol = new SUPRTestingDBEntities2();
var userAuth = (from data in dbcontrol.SUPRTesting where data.EmailID == EmailID
&& data.TaxID == TaxID
/*Error CS0019: Operator '==' cannot be applied to operands of type 'int' and 'string'*/
select data).FirstOrDefault();
if (userAuth != null)
{
Session["EmailID"] = userAuth.EmailID;
Session["LoginID"] = userAuth.LoginID;
return RedirectToAction("LIDAuthentication", "Corporation");
}
else if (userAuth == null)
{
return View();
}
Can someone help me with this.
What you need is converting your TaxId request to int and then your Scenario 1 should works fine, something like this:
int TaxID = Convert.ToInt32(Request[TaxID]);
However I would do this to better handle all of the possible errors:
string taxID = Request["TaxID"];
if (!String.IsNullOrEmpty(taxID) && int.TryParse(taxID, out int TaxID))
{
//Your code here, use TaxID in your query
}
Unless I've misunderstood what you're trying to do, you shouldn't need to use Request at all. You can obtain this information by adding parameters to the controller method:
public ActionResult MyMethod(string EmailID, int TaxID) // query string parameters moved to method parameters
{
SUPRTestingDBEntities2 dbcontrol = new SUPRTestingDBEntities2();
var userAuth = (from data in dbcontrol.SUPRTesting
where data.EmailID == EmailID
&& data.TaxID == TaxID
select data).FirstOrDefault();
if (userAuth != null)
{
Session["EmailID"] = userAuth.EmailID;
Session["LoginID"] = userAuth.LoginID;
return RedirectToAction("LIDAuthentication", "Corporation");
}
else if (userAuth == null)
{
return View();
}
}
I am basically trying to handle unique constraint validation in my .Net API. I have two unique key cosntraints on two fields in my table.
If you see my code below , I am trying to check if the record exists. I am looking at returning a boolean value if the record exist. is that possible. For the time being, I am returning null.
Is this the best way to do it.
[HttpPost]
[SkipTokenAuthorization]
[Route("api/classificationoverrides/create")]
public IHttpActionResult Create(ClassificationItemViewModelCreate model)
{
var mgrClassificationService = GetService<MGR_STRT_CLASSIFICATION>();
var isExists = mgrClassificationService.Where(x =>
x.MANAGERSTRATEGYID == model.ManagerStrategyId && x.PRODUCT_ID == model.ProductId).FirstOrDefault();
if (isExists == null)
{
var mgrClassficationOverride = new MGR_STRT_CLASSIFICATION();
if (model != null)
{
mgrClassficationOverride.PRODUCT_ID = model.ProductId;
mgrClassficationOverride.LEGACY_STRATEGY_ID = model.LegacyStrategyId;
mgrClassficationOverride.STRATEGY_ID = model.StrategyId;
mgrClassficationOverride.MANAGERSTRATEGY_TYPE_ID = model.ManagerStrategyTypeId;
mgrClassficationOverride.MANAGERSTRATEGYID = model.ManagerStrategyId;
mgrClassficationOverride = mgrClassificationService.Create(mgrClassficationOverride);
}
return Ok(mgrClassficationOverride);
}
else
{
return null;
}
}
What is the Query results window's global service (interface)? Code below:
var dteService = Package.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
if (dteService == null)
{
Debug.WriteLine("");
return;
}
var something=Package.GetGlobalService(typeof(???)) as ???;
EDIT: The goal is, when I press the context menu button, I want the function callback to be able to access the service where the work item is selected (or the results list
Please check this case in MSDN forum for the details how to get it work: https://social.msdn.microsoft.com/Forums/vstudio/en-US/2d158b9c-dec1-4c59-82aa-f1f2312d770b/sdk-packageget-selected-item-from-query-results-list
The following code is quoted from above link for your quick reference:
Document activeDocument = _applicationObject.ActiveDocument;
if (activeDocument != null)
{
DocumentService globalService = (DocumentService)Package.GetGlobalService(typeof(DocumentService));
if (globalService != null)
{
string fullName = activeDocument.FullName;
IWorkItemTrackingDocument document2 = globalService.FindDocument(fullName, null);
if ((document2 != null) && (document2 is IResultsDocument))
{
int[] selectedItemIds = ((IResultsDocument)document2).SelectedItemIds;
}
}
}
var dteService = Package.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
if (dteService == null)
{
Debug.WriteLine("");
return;
}
DocumentService documentService = Package.GetGlobalService(typeof(DocumentService)) as DocumentService;
if (documentService == null)
return;
string fullName = dteService.ActiveDocument.FullName;
IWorkItemTrackingDocument activeDocument = documentService.FindDocument(fullName, null);
if (activeDocument == null || !(activeDocument is IResultsDocument))
return;
In the below code I have Session variable in which I want to check whether it is null or not. Please help me to do this.
(SearchDoc) is class.
var SearchDoc = (SearchDoc)Session["Documentname"];
var oDocumentID = SearchDoc.ClientID;
var Documentid = SearchDoc.DocumentID;
if (SearchDoc == null)
{
}
This is the safest approach :
if ((HttpContext.Current.Session !=null && Session["Documentname"] as SearchDoc!= null))
{
//do what you want with
((SearchDoc)Session["Documentname"])
}
2 things to notice :
Yes , sometime the session object is null. ( probably occurs with AShX's without appropriate interface)
use the AS operator. - once it's ok , you can safely cast to SearchDOC
Try this
if(Session["Documentname"] != null)
{
var SearchDoc = (SearchDoc)Session["Documentname"];
var oDocumentID = SearchDoc.ClientID;
var Documentid = SearchDoc.DocumentID;
if (SearchDoc == null)
{
}
}
You can simply try this:
string oDocumentID = string.Empty;
string Documentid = string.Empty;
if(Session["Documentname"] != null){
var SearchDoc = (YourSearchDocType)Session["Documentname"];
oDocumentID = SearchDoc.ClientID;
Documentid = SearchDoc.DocumentID;
// some code
}
dont try to access some property of object which can be null
Reshaper said the left hand side of ?? was never null even though its type is int?
_savedMediaFileId = mediaFile.MediaFileId ?? _savedMediaFileId;
The auto refactor "remove unreachable code" turned it into this:
_savedMediaFileId = (int) mediaFile.MediaFileId;
Is that right or is Resharper making a mistake here?
My idea was that since int? is nullable, then then I could use ?? to keep the existing value in the case it is null.
Here's my unit test (in progress)
[TestClass]
public class MediaRepositoryTest
{
private const string SiteId = "3";
private const string ConnectionString =
#"Data Source=dvmind\mssqlsites;Database=***********;User Name=sa;Password=**************";
private string _mediaSourceName = "TestMediaSourceName";
private string _mediaTypeName = "TestMediaTypeName";
private string _mediaSourceAddress = "TestMediaSourceAddress";
private string _mediaFileAddress = "TestMediaFileAddress";
private int _savedMediaFileId = 0;
private string GetGuidString()
{
return Convert.ToBase64String(Guid.NewGuid().ToByteArray());
}
[TestInitialize]
public void TestInitialize()
{
_mediaSourceName = _mediaSourceName + GetGuidString();
_mediaTypeName = _mediaTypeName + GetGuidString();
_mediaSourceAddress = _mediaSourceAddress + GetGuidString();
_mediaFileAddress = _mediaFileAddress + GetGuidString();
}
[TestCleanup]
public void TestCleanup()
{
using (var db = new SiteContext(ConnectionString))
{
if (_savedMediaFileId != 0)
{
(from c in db.MediaFiles where c.MediaFileId == _savedMediaFileId select c).ToList()
.ForEach(c => db.MediaFiles.Remove(c));
}
(from c in db.MediaSources where c.MediaSourceName == _mediaSourceName select c).ToList()
.ForEach(c => db.MediaSources.Remove(c));
(from c in db.MediaTypes where c.MediaTypeName == _mediaTypeName select c).ToList()
.ForEach(c => db.MediaTypes.Remove(c));
}
}
[TestMethod]
public void SaveMediaTest()
{
var mediaSource = new MediaSource
{
MediaSourceName = _mediaSourceName,
MediaSourceAddress = _mediaSourceAddress
};
var mediaType = new MediaType
{
MediaTypeName = _mediaTypeName
};
var mediaFile = new MediaFile
{
SiteId = SiteId,
MediaFileAddress = _mediaFileAddress,
MediaSource = mediaSource,
MediaType = mediaType
};
var connectionStringProvider =
Mock.Of<IConnectionStringProvider>(c => c.GetConnectionString() == ConnectionString);
var repository = new MediaRepository(connectionStringProvider);
Assert.IsTrue(mediaFile.MediaFileId == 0);
repository.SaveMedia(mediaFile);
Assert.IsTrue(mediaFile.MediaFileId != 0);
_savedMediaFileId = mediaFile.MediaFileId ?? _savedMediaFileId;
//using (var db = new SiteContext(ConnectionString))
//{
//}
}
Now that you've posted a complete example, I think the reason you are getting unreachable code, is due to the Assert conditions that precede this line;
Assert.IsTrue(mediaFile.MediaFileId == 0);
If mediaFile.MediaFileId is null, the program exits on this line, if its not, then the warning is correct; mediaFile.MediaFileId cannot be null on the line you highlight;
_savedMediaFileId = mediaFile.MediaFileId ?? _savedMediaFileId;
Also, if the definition of SaveMedia took a ref MediaFile that would also impact the warning, because it is then possible (as far as ReSharper is concerned) that the value is changed again to Null by;
repository.SaveMedia(mediaFile);
Either of these changes will impact the presence of the warning.
ReSharper is likely inferring here that mediaFile.MediaFileId can never have the value null even though the type is int?. Hence it's suggesting that you skip the null check entirely and go straight for the value
A clearer example is the following
string s = "hello world";
if (s != null) {
...
}
In this case s can be null practically because it is of type string and null is a valid value. However in this specific context s can never be null hence ReSharper would flag this check as unnecessary
This is a bit of a guess, but I think what's happening here (based on MSDN
When you declare someting int?, it doesn't create a reference type that can be null. Instead, it creates Nullable<T> which is a struct meaning it cannot be Null b/c it is a value type. That struct besides the value contains a boolean flag that tells it if it is null of if value is valid.
Hence, doing int? ?? is essentially testing a struct for null value which it can never be. It does not test Nullable<T>.HasValue which is a way to test if is "null" or not.
Hence the ReSharper complaint.