I have a custom action filter that will log user actions automatically using a [Log] attribute in my controllers. I've used this same setup in multiple applications so I know it works, but this time it's failing and I can't figure out why.
public override void OnResultExecuted(ResultExecutedContext thisContext)
{
LogTrace(thisContext.RouteData);
}
public void LogTrace(RouteData routeData)
{
MyContext db = new MyContext();
TimeSpan Duration = (DateTime.Now - StartTime);
string Controller = ReadableController((string)routeData.Values["controller"]);
string Action = (string)routeData.Values["action"];
long? ID = (long?)routeData.Values["id"];
LogFile log = new LogFile();
log.UserID = User.ID;
log.Controller = Controller;
log.Action = Action;
log.ItemID = ID;
log.Timestamp = DateTime.Now;
log.Duration = Duration;
db.LogFiles.Add(log);
db.SaveChanges();
}
I'm getting 'specified cast is invalid' on LogFile log = new LogFile().
It's not that, the error is one line up, here:
long? ID = (long?)routeData.Values["id"];
Check your route data. id is not a long. It must be a string or even something else.
If it is a numeric type which you store as a string then you have other options to convert it, such as Convert.ToInt64.
Related
Sorry If i confuse anyone with the question, I am trying hard to make the scenario clear.
Am writing Test Cases for a method that invoke HttpClient Methods.So, I ended up writing following Test Method.
[TestMethod]
public async Task CallComplexRefTypeParamAPI_Get_GetResponseWithParamatersNameValueAppended()
{
#region Arrange
//var resourceURL = #"http://localhost:32662/api/user/ComplexReferenceTypeParamStringResponse";
var resourceURL = #"/api/user/ComplexReferenceTypeParamStringResponse";
var restHelper = new RestHelper(_BaseAddress);
string ParameterKey1 = "VariableStr";
string ParameterValueStr = "Jia";
string ParameterKey2 = "VariableInt";
int ParameterValueInt = 1;
string ParameterKey3 = "VariableBool";
bool ParameterValueBool = true;
string ParameterKey4 = "VariableDateTime";
DateTime ParameterValueDateTime = DateTime.Now;
ComplexRefType ParameterComplexRefType = new ComplexRefType()
{
VariableBool = ParameterValueBool,
VariableDateTime = ParameterValueDateTime,
VariableInt = ParameterValueInt,
VariableStr = ParameterValueStr
};
string result;
#endregion
#region Act
using (WebApp.Start<WebApiStartup>(_BaseAddress))
{
restHelper.AddURLParameters("VariableComplexRef", ParameterComplexRefType);
restHelper.AddURLParameters("DummyStr", "DummyStr");
result = await restHelper.ExecuteAsync<string>(HttpMethod.Get, resourceURL);
}
#endregion
#region Assert
Assert.AreEqual<string>(string.Format("{0}={1}&{2}={3}&{4}={5}&{6}={7}",
ParameterKey1, ParameterValueStr,
ParameterKey2, ParameterValueInt,
ParameterKey3, ParameterValueBool,
ParameterKey4, ParameterValueDateTime), result);
#endregion
}
On other side, I have my Test Controller with following 2 methods.
public string GetMultipleTypeParamStringResponse(string VariableStr, int VariableInt, DateTime VariableDateTime)
{
return string.Format("VariableStr={0}&VariableInt={1}&VariableDateTime={2}", VariableStr, VariableInt, VariableDateTime);
}
public string GetComplexReferenceTypeParamStringResponse([FromUri]ComplexRefType VariableComplexRef, string DummyStr)
{
return string.Format("VariableStr={0}&VariableInt={1}&VariableBool={2}&VariableDateTime={3}",
VariableComplexRef.VariableStr,
VariableComplexRef.VariableInt,
VariableComplexRef.VariableBool,
VariableComplexRef.VariableDateTime);
}
I have the same Controller replicated in an Web API application. If run the test method, pointing to the Self-Hosted API, the application hits "GetMultipleTypeParamStringResponse" instead of "GetComplexReferenceTypeParamStringResponse". However, if I run it against the Web API, it hits the rightful "GetComplexReferenceTypeParamStringResponse" method.
Could someone please help me understand why this behavior ? On both cases, the Query String generated looks to be similar.
Self Hosted
http://localhost:8888/api/user/ComplexReferenceTypeParamStringResponse?VariableStr=Jia&VariableInt=1&VariableBool=True&VariableDateTime=1%2F5%2F2017 3:49:10 PM&DummyStr=DummyStr
Web API
http://localhost:32662/api/user/ComplexReferenceTypeParamStringResponse?VariableStr=Jia&VariableInt=1&VariableBool=True&VariableDateTime=1%2F5%2F2017 3:50:58 PM&DummyStr=DummyStr
Change the routetemplate in your route configuration to
routeTemplate: "api/{controller}/{action}/{id}"
Mark the methods with explicit Route attribute and HttpGet verb like below
[HttpGet]
[Route("api/user/ComplexReferenceTypeParamStringResponse")]
I am new to entity framework and right now struggling with an issue. I am using MVC api and EF6.
I was saving member details in a PUT method. That worked fine.
Now, I modified the code to save a comment (Added new method PublishComment()) as well but this breaks the code without any error message!! The debug session just hungs on the db.SaveChanges().
public void Put(Guid id, MemberListItem item)
{
using (Context db = new Context())
{
Person updPerson = db.People.Find(item.PersonID);
if (updPerson.PrincipleContact != item.PrincipalMember)
{
updPerson.PrincipleContact = item.PrincipalMember;
}
string memberName = updPerson.GivenName1;
Guid memberID = updPerson.MemberID;
db.Entry(updPerson).State = System.Data.Entity.EntityState.Modified;
PublishComment(db, memberID, "User Modified. " + memberName + " modified from user profile.");
db.SaveChanges();
}
public void PublishComment(Context db, Guid memberID, string comment)
{
MemberComment newComment = new MemberComment();
newComment.CommentID = new Guid();
newComment.MemberID = memberID;
newComment.DateAdded = DateTime.Now;
newComment.Comment = DateTime.Now.ToShortDateString() +": " + comment;
db.MemberComments.Add(newComment);
}
I think your issue is here:
newComment.CommentID = new Guid(); // eg {00000000-0000-0000-0000-000000000000}
But I'm not too sure why you are not seeing a duplicate key exception (which is what this looks like it would generate)
see Guid is all 0's (zeros)?
Currently, I'm sending some data to Parse.com. All works well, however, I would like to add a row if it's a new user or update the current table if it's an old user.
So what I need to do is check if the current Facebook ID (the key I'm using) shows up anywhere in the fbid column, then update it if case may be.
How can I check if the key exists in the column?
Also, I'm using C#/Unity.
static void sendToParse()
{
ParseObject currentUser = new ParseObject("Game");
currentUser["name"] = fbname;
currentUser["email"] = fbemail;
currentUser["fbid"] = FB.UserId;
Task saveTask = currentUser.SaveAsync();
Debug.LogError("Sent to Parse");
}
Okay, I figured it out.
First, I check which if there is any Facebook ID in the table that matches the current ID, then get the number of matches.
public static void getObjectID()
{
var query = ParseObject.GetQuery("IdealStunts")
.WhereEqualTo("fbid", FB.UserId);
query.FirstAsync().ContinueWith(t =>
{
ParseObject obj = t.Result;
objectID = obj.ObjectId;
Debug.LogError(objectID);
});
}
If there is any key matching the current Facebook ID, don't do anything. If there aren't, just add a new user.
public static void sendToParse()
{
if (count != 0)
{
Debug.LogError("Already exists");
}
else
{
ParseObject currentUser = new ParseObject("IdealStunts");
currentUser["name"] = fbname;
currentUser["email"] = fbemail;
currentUser["fbid"] = FB.UserId;
Task saveTask = currentUser.SaveAsync();
Debug.LogError("New User");
}
}
You will have to do a StartCoroutine for sendToParse, so getObjectID has time to look through the table.
It may be a crappy implementation, but it works.
What you need to do is create a query for the fbid. If the query returns an object, you update it. If not, you create a new.
I'm not proficient with C#, but here is an example in Objective-C:
PFQuery *query = [PFQuery queryWithClassName:#"Yourclass]; // Name of your class in Parse
query.cachePolicy = kPFCachePolicyNetworkOnly;
[query whereKey:#"fbid" equalTo:theFBid]; // Variable containing the fb id
NSArray *users = [query findObjects];
self.currentFacebookUser = [users lastObject]; // Array should contain only 1 object
if (self.currentFacebookUser) { // Might have to test for NULL, but probably not
// Update the object and save it
} else {
// Create a new object
}
I am trying to get records from an AS400 system into Dynamics CRM programatically. To achieve this i have pushed the AS400 records into a SQL table and am able to push those records to CRM by referencing the CRM 4 web service endpoints in a SSIS 2008 C# script.
The problem is one of the fields is in Y2K date string format. In order to get it into a date field (D.O.B) in CRM i believe i will need to convert it to a date format then reference resulting value in a variable.
I do not know how to do this.
This question/answer (http://stackoverflow.com/a/4880021/1326443) may help with part of the question but i do not know how to use this into my script to get a value (haven't done any scripting for a number of years and new to C#)
Script snippet:
public class ScriptMain : UserComponent
{
private CrmService service = null;
public override void PreExecute()
{
base.PreExecute();
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = "DevOrg";
service = new CrmService();
service.Url = "http://crm/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
}
public override void PostExecute()
{
base.PostExecute();
}
public override void LeadInput_ProcessInputRow(LeadInputBuffer Row)
{
lead cont = new lead();
if (!Row.TITL20_IsNull)
{
cont.salutation = Row.TITL20;
}
if (!Row.DOBI20_IsNull)
{
cont.new_birthdate = Row.DOBI20;
}
....
....
service.Create(cont);
}
}
}
{ cont.new_birthdate = Row.DOBI20; } throws:
cannot implicitly convert type 'string' to .....CrmSdk.CRMDateTime
Just had a look at the documentation for CRMDateTime (http://msdn.microsoft.com/en-us/library/bb928935.aspx)
This states that you can set this using the Value property (http://msdn.microsoft.com/en-us/library/bb928944.aspx)
So you might like to try:
cont.new_birthdate.Value = Row.DOBI20
Edit
In response to your comments, try the following
string ConvertDate(string dateToConvert)
{
dateToConvert= dateToConvert.PadLeft(7, '0');
int c;
int.TryParse(dateToConvert.Substring(0,1), out c);
c = (c * 100) + 1900;
int y;
int.TryParse(dateToConvert.Substring(1,2), out y);
return (c+y).ToString() + dateToConvert.Substring(3,4);
}
I have a project that inserts personal information to a table and details into another table. But sometimes personal information cannot be recorded, however details are recorded. As below code part, firstly personal information are inserted, then details. But sometimes personal information doesn't get saved and userId returns 0, So details are saved. I don't know why it doesn't work. Any idea?
public int ConferenceIdyeGoreKisiBilgileriniKaydet(string orderId)
{
KisiselBilgilerBal kisiBilgileri = (KisiselBilgilerBal)Session["kisiselBilgilerSession"];
registrationCode = GenerateGeristrationCode();
string toplamMaliyet = Session["toplamOdeme"].ToString();
PersonalInformation.SavePersonalInformations(kisiBilgileri, registrationCode,conferenceName);
int userId = AuthorPaperDetaylari.AdVeSoyadaGoreIdGetir(kisiBilgileri.f_name, kisiBilgileri.l_name);
AuthorPaperDetaylari.SaveAuthorPaperDetails(authorPaperDetay, userId); // save details via userId.
return userId;
}
This method saves personal information.
public static void SavePersonalInformations(KisiselBilgilerBal kisiBilgileri,string registrationCode,string conferenceName)
{
try
{
string cs = ConfigurationManager.AppSettings["SiteSqlServer"];
DBDataContext db = new DBDataContext(cs);
DBpersonalInformation personalInfo = new DBpersonalInformation();
personalInfo.f_name = kisiBilgileri.f_name;
personalInfo.l_name = kisiBilgileri.l_name;
personalInfo.university_affiliation = kisiBilgileri.university_affiliation;
personalInfo.department_name = kisiBilgileri.department_name;
personalInfo.address1 = kisiBilgileri.address1;
personalInfo.address2 = kisiBilgileri.address2;
personalInfo.city = kisiBilgileri.city;
personalInfo.state = kisiBilgileri.state;
personalInfo.zipCode = kisiBilgileri.zipCode;
personalInfo.country = kisiBilgileri.country;
personalInfo.phone = kisiBilgileri.phone;
personalInfo.email = kisiBilgileri.email;
personalInfo.orderId = kisiBilgileri.orderId;
personalInfo.registrationCode = registrationCode;
personalInfo.date = DateTime.Now;
personalInfo.conferenceName = conferenceName;
db.DBpersonalInformations.InsertOnSubmit(personalInfo);
db.SubmitChanges();
}
catch (Exception)
{
}
}
This method saves details
public static void SaveAuthorPaperDetails(AuthorPaperDetailsBal authorPaperDetay, int userId)
{
try
{
string cs = ConfigurationManager.AppSettings["SiteSqlServer"];
DBWebDataContext db = new DBWebDataContext(cs);
DBAuthorPaperDetail authorPaperDetail = new DBAuthorPaperDetail();
authorPaperDetail.paper_title = authorPaperDetay.paperTitleDetails;
authorPaperDetail.conference_maker_id = authorPaperDetay.confMakerId;
authorPaperDetail.additional_paper_title = authorPaperDetay.additionalPprTtle;
authorPaperDetail.areYouMainAuthor = authorPaperDetay.mainAuthor;
authorPaperDetail.feeForFirstAuthorPaper = authorPaperDetay.registerFeeForFirstAuthor;
authorPaperDetail.feeForAdditionalPaper = authorPaperDetay.regFeeForAdditionalPape;
authorPaperDetail.feeForParticipCoAuthors = authorPaperDetay.regFeeForCoAuthors;
authorPaperDetail.userId = userId;
authorPaperDetail.firstCoAuthorName = authorPaperDetay.firstCoAuthor;
authorPaperDetail.secondCoAuthorName = authorPaperDetay.secondCoAutho;
authorPaperDetail.thirdCoAuthorName = authorPaperDetay.thirdCoAuthor;
authorPaperDetail.toplamOdeme = authorPaperDetay.toplamMaliyet;
db.DBAuthorPaperDetails.InsertOnSubmit(authorPaperDetail);
db.SubmitChanges();
}
catch (Exception)
{
}
}
I don't know why it doesnt work. Any idea?
...
catch (Exception)
{
}
Well, that explains pretty much everything... don't do this. Ever. The database layer is trying to tell you what the problem is, and you are sticking your fingers in your ears, hoping that'll make it go away. If I had to guess: maybe an occasional timeout due to being blocked by another SPID.
If you can't do anything useful or appropriate with an exception, just let it bubble to the caller. If it gets to the UI, tell the user about it (or just log the issue internally and tell the user "There was a problem").
Also, a LINQ-to-SQL data-context is IDisposable; you should have using statement around db.
In addition to Marc's answer... You are calling SubmitChanges twice. If you want atomic data storage, you should call it once. You can use relational properties to create an object graph, and submit the whole graph at once.
public void SaveParentAndChildren()
{
using (CustomDataContext myDC = new CustomDataContext())
{
Parent p = new Parent();
Child c = new Child();
p.Children.Add(c);
myDC.Parents.InsertOnSubmit(p); //whole graph is now tracked by this data context
myDC.SubmitChanges(); // whole graph is now saved to database
// or nothing saved if an exception occurred.
} //myDC.Dispose is called for you here whether exception occurred or not
}