ASP.NET - Why is my cookie not persisted? - asp.net-mvc

i'm trying to set a cookie to store a selected department in. The cookie is set with a small form which has a select-dropdown with departments. This is posted using AJAX.
This is how I store the cookie:
<AcceptVerbs(HttpVerbs.Post)> _
Function ChangeDepartment(ByVal FormValues As FormCollection) As ActionResult
If Response.Cookies("department") IsNot Nothing Then
Response.Cookies("department").Value = FormValues("department")
Else
Dim c As New HttpCookie("department")
c.Value = FormValues("department")
c.Expires = Now.AddDays(7)
Response.Cookies.Add(c)
End If
Return Json(New With {.newDepartment = Response.Cookies("department").Value})
End Function
The .newDepartment variable is returned correctly with the correct value.
This is how I retrieve the cookie and build the select-dropdown:
<% Ajax.BeginRouteForm("ChangeDepartment", New AjaxOptions With {.LoadingElementId = "loading", .HttpMethod = "post", .OnSuccess = "function(request) {ajaxMessage('Department change', 'Department changed to: ' + request.get_response().get_object().newDepartment);}"})%>
<select name="department">
<option>Default</option>
<option<%If Request.Cookies("department") Isnot Nothing andAlso Request.Cookies("department").Value = "Supervisor" Then Response.Write (" selected=""selected""") %>>Supervisor</option>
<option<%If Request.Cookies("department") Isnot Nothing andAlso Request.Cookies("department").Value = "Purchasing" Then Response.Write (" selected=""selected""") %>>Purchasing</option>
<option<%If Request.Cookies("department") Isnot Nothing andAlso Request.Cookies("department").Value = "Engineering" Then Response.Write (" selected=""selected""") %>>Engineering</option>
</select>
<input type="submit" value="Change department" />
<% Html.EndForm%>
The cookie isn't stored, because the select-dropdown keeps going back to Default. Am I doing something wrong?

You could try to use http debugger like Fiddler for IE and HttpFox for FireFox.
Check if the cookie is really send with the server response and if the browser sends it back with further requests.
From there you are probably going to track the problem and see what is going wrong. If you still have problems you could post the http traffic here.

Related

Truncated message tweets

Please!
I'm getting tweets from LinqToTwitter, and some tweets seem to have the text truncated, with part of the text following with an ellipsis. In some cases, the search criteria are not returned in the text, as it appears to be in the unearned part of the message. That's right? Is there a way to get this missing part of the message? I have already looked at other posts, but I could not understand which parameter allows the full text to be obtained. I'm using linqToTwitter version 4.1.0.
Thank you
Dim twitterCtx As TwitterContext = New TwitterContext(twAuth)
Dim Response As Search = Await (From search In twitterCtx.Search()
Where search.Type = SearchType.Search _
AndAlso search.SearchLanguage = "pt" _
AndAlso search.Query = "Coronavirus").SingleOrDefaultAsync()
Dim tweets As List(Of Status) = Response.Statuses()
If Response IsNot Nothing AndAlso Response.Statuses IsNot Nothing Then
For Each str As Status In tweets
Console.WriteLine(str.StatusID.ToString() + " " + str.Text)
Next
End If
When Twitter extended tweets from 140 to 280 characters, they needed to add support in the API. This is called Extended Mode and you need to add a new filter to your LINQ query, like this:
Dim Response As Search = Await (From search In twitterCtx.Search()
Where search.Type = SearchType.Search _
AndAlso search.SearchLanguage = "pt" _
AndAlso search.TweetMode = TweetMode.Extended _
AndAlso search.Query = "Coronavirus").SingleOrDefaultAsync()
Notice the search.TweetMode property. I assigned the TweetMode.Extended enum to it, which means you now get the full 280 characters.
Having done that, you might view the Text property and be surprised to see Nothing. That's because now the tweet text is in the FullText property and you can read it like this:
Dim tweets As List(Of Status) = Response.Statuses()
If Response IsNot Nothing AndAlso Response.Statuses IsNot Nothing Then
For Each str As Status In tweets
Console.WriteLine(str.StatusID.ToString() + " " + str.FullText)
Next
End If

Dynamic data from ViewBag on Partial View rendered on _Layout

Here I have a partial view in MVC 5
#modelType HOA5.MainMenuModel
<div class="navbar navbar-inverse navbar-fixed-top" id="mainNavbar">
<div class="container">
#Html.Raw(ViewBag.htmlstr)
</div>
</div>
...and the controller returns some dynamic content to ViewBag
Function Index() As ActionResult
Dim vModal As New MainMenuModel
vModal.MenuHTML = SB.ToString
Dim MenuHTML As String = ReturnMenu()
ViewBag.htmlstr = MenuHTML
Return View("MainMenuView")
End Function
... and then run just that view
http://localhost:52735/mainMenu/
It works perfectly and inserts the dynamic content. However, when I add the partial view to _Layout
#Html.Partial("~/Views/MainMenu/MainMenuView.vbhtml")
and run it
http://localhost:52735
Then the static content appears, but not the dynamic content.. Have also tried variants of #RenderAction, #RenderPartial but either that is not correct, or I have messed up the syntax!
Any pointers would be appreciated as head has been introduced to wall too many times today :-)
Thank you
As is so often we make things more complicated :-)
The easy fix was to make the function that returns the HTML string an ActionResult
Function ReturnMainMenu() As ActionResult
Try
strSQL = "SELECT * FROM Customers"
Using DS As DataSet = ReturnDataSet_Data(strSQL, 2, False)
For Each row As DataRow In DS.Tables(0).Rows
Next
End Using
Dim vModal As New MainMenuModel
Dim SB As New StringBuilder
SB.Append("<div class=""navbar navbar-inverse navbar-fixed-top"" id=""mainNavbar"">")
SB.Append("<div class=""container"">")
SB.Append("<div class=""navbar-header"">")
SB.Append("<button type=""button"" class=""navbar-toggle"" data-toggle=""collapse"" data-target="".navbar-collapse"">")
SB.Append("<span class=""icon-bar""></span>")
SB.Append("<span class=""icon-bar""></span>")
SB.Append("<span class=""icon-bar""></span>")
SB.Append("</button>")
SB.Append("<a class=""navbar-brand"" href=""/"">Add Variable Here xxx</a>") ' Add the variable here
SB.Append("</div>") ' End of navbar-header
SB.Append("<div class=""navbar-collapse collapse"">")
SB.Append("<ul class=""nav navbar-nav"">")
SB.Append("<li>Home</li></li>")
SB.Append(" <li>Upload eInvoice</li>")
SB.Append("<li>Contact</li>")
SB.Append("</ul>")
SB.Append("</div>") 'end of navbar-collapse
SB.Append("</div>")
SB.Append("</div>")
Dim checkstring As String = SB.ToString
vModal.MenuHTML = SB.ToString
Return Content(checkstring)
Catch ex As Exception
Return Nothing
End Try
End Function
Then (now I understand the syntax) add it to _Layout
#Html.Action("ReturnMainMenu", "MainMenu")
...and everything works....

Add menu item to Quickbooks

Is it possible to add a menu item to Quickbooks using the QBSDK?
I have found a couple of old examples that I can't make work.
I have created a custom application for my company and am trying to simplify it by making a menu item in Quickbooks.
Any help would be greatly appreciated.
Here is what I have tried so far, but I get an error message at the subAdd.SubscriberID.SetValue(Me.appGUID.ToString).
The error is: * Invalid GUID format. Must use zero for Custom Fields, or a GUID generated with GuidGen.exe for private data extensions.*
{
Dim subRq As ISubscriptionMsgSetRequest
subRq = MySessionManager.CreateSubscriptionMsgSetRequest(4, 0)
' Add a UIExtension subscription to our request
Dim subAdd As IUIExtensionSubscriptionAdd
subAdd = subRq.AppendUIExtensionSubscriptionAddRq
'
' set up the subscription request with the required information, we're adding to
' the file menu in this case, and just for fun, we're making it a cascading menu
subAdd.SubscriberID.SetValue(Me.appGUID.ToString) "<-----error happens here
subAdd.COMCallbackInfo.AppName.SetValue(Me.appName)
subAdd.COMCallbackInfo.ORProgCLSID.ProgID.SetValue("MenuEventContext.QBMenuListener")
subAdd.MenuExtensionSubscription.AddToMenu.SetValue("atmFile")
'
' For the cascade fun, we're just going to add items to the cascade menu...
Dim subMenu As IMenuItem
For i = 1 To 5
subMenu = subAdd.MenuExtensionSubscription.ORMenuSubmenu.Submenu.MenuItemList.Append
'
' this is the text that the user will see in QuickBooks:
subMenu.MenuText.SetValue("Sub Item " & i)
'
' this is the tag we'll get in our event handler to know which menu item was
' selected:
subMenu.EventTag.SetValue("SubMenu" & i)
Next i
'
' Send the request and get the response, since we're sending only one request there
' will be only one response in the response list
Dim subRs As ISubscriptionMsgSetResponse
subRs = MySessionManager.DoSubscriptionRequests(subRq)
Dim resp As IResponse
'
' Check the response and display an appropriate message to the user.
resp = subRs.ResponseList.GetAt(0)
If (resp.StatusCode = 0) Then
MsgBox("Successfully added to QuickBooks File menu, restart QuickBooks to see results")
Else
MsgBox("Could not add to QuickBooks menu: " & resp.StatusMessage)
End If
MySessionManager.CloseConnection()
MySessionManager = Nothing
Exit Sub
handleError:
MsgBox("Encountered error subscribing: " & Err.Description)
If Not MySessionManager Is Nothing Then
MySessionManager.CloseConnection()
End If
End Sub
The answer is yes.
The only purpose of UIExtensionSubscription is to add menu items to the top menus. Clicking the menus will then start your app, if it isn't already running, and pass it information about the current focused Quickbooks window.
Your application must be com accessible and registered.
As for your sample make sure you are passing { } around your GUID. I don't use function call unsure if you might need to cast to a string first or not.
There is a sample console app in C# in the current QBPOSSDK download from Intuit. I would thoroughly read the programmers guide and look at that sample.
One of my working requests, pretty close to the intuit sample:
Private Shared Function GetUIExtensionSubscriptionAddXML(ByVal strMenuName As String, ByVal strMainMenuName As String) As String
'strMainMenuName would be "Company" for example
'Create the qbXML request
Dim requestXMLDoc As New XmlDocument()
requestXMLDoc.AppendChild(requestXMLDoc.CreateXmlDeclaration("1.0", Nothing, Nothing))
requestXMLDoc.AppendChild(requestXMLDoc.CreateProcessingInstruction("qbxml", "version=""5.0"""))
Dim qbXML As XmlElement = requestXMLDoc.CreateElement("QBXML")
requestXMLDoc.AppendChild(qbXML)
'subscription Message request
Dim qbXMLMsgsRq As XmlElement = requestXMLDoc.CreateElement("QBXMLSubscriptionMsgsRq")
qbXML.AppendChild(qbXMLMsgsRq)
'UI Extension Subscription ADD request
Dim uiExtSubscriptionAddRq As XmlElement = requestXMLDoc.CreateElement("UIExtensionSubscriptionAddRq")
qbXMLMsgsRq.AppendChild(uiExtSubscriptionAddRq)
'UI Extension Subscription ADD
Dim uiExtEventSubscriptionAdd As XmlElement = requestXMLDoc.CreateElement("UIExtensionSubscriptionAdd")
uiExtSubscriptionAddRq.AppendChild(uiExtEventSubscriptionAdd)
'Add Subscription ID
uiExtEventSubscriptionAdd.AppendChild(requestXMLDoc.CreateElement("SubscriberID")).InnerText = MySubscriberGUID
'Add COM CallbackInfo
Dim comCallbackInfo As XmlElement = requestXMLDoc.CreateElement("COMCallbackInfo")
uiExtEventSubscriptionAdd.AppendChild(comCallbackInfo)
'Appname and CLSID
comCallbackInfo.AppendChild(requestXMLDoc.CreateElement("AppName")).InnerText = App_Name
comCallbackInfo.AppendChild(requestXMLDoc.CreateElement("CLSID")).InnerText = MyCLSID
' MenuEventSubscription
Dim menuExtensionSubscription As XmlElement = requestXMLDoc.CreateElement("MenuExtensionSubscription")
uiExtEventSubscriptionAdd.AppendChild(menuExtensionSubscription)
'Add To menu
menuExtensionSubscription.AppendChild(requestXMLDoc.CreateElement("AddToMenu")).InnerText = strMainMenuName
Dim menuItem As XmlElement = requestXMLDoc.CreateElement("MenuItem")
menuExtensionSubscription.AppendChild(menuItem)
'Add Menu Name
menuItem.AppendChild(requestXMLDoc.CreateElement("MenuText")).InnerText = strMenuName
menuItem.AppendChild(requestXMLDoc.CreateElement("EventTag")).InnerText = "menu_" & strMenuName.Replace(" ", "_")
Dim displayCondition As XmlElement = requestXMLDoc.CreateElement("DisplayCondition")
menuItem.AppendChild(displayCondition)
displayCondition.AppendChild(requestXMLDoc.CreateElement("VisibleIf")).InnerText = "InventoryEnabled"
displayCondition.AppendChild(requestXMLDoc.CreateElement("EnabledIf")).InnerText = "InventoryEnabled"
Dim strRetString As String = requestXMLDoc.OuterXml
WriteLocalLog("GetUIExtensionSubscriptionAddXML: " & strRetString)
Return strRetString
End Function

How to handle concurrency clash in ASP.Net MVC using post-redirect-get?

I use a post-redirect-get (PRG) pattern to save an entity in ASP.Net MVC 2. The controller methods are 'Save' (inserts or updates database) and 'Edit' (retrieves user input). In 'Save', I do modification check before saving by checking a 'version' column of the entity. If someone else has modified the entity, the 'version' column will not match and I will send error message to the user.
To maintain error messages, I use ModelState.Merge in 'Edit' method. The problem with this mechanism is that the user input is maintained and the user doesn't see the modification made by the other user. I avoid this problem by clearing ModelState before adding the concurrency clash message.
But I feel this solution is not optimal. How would you handle concurrency clash in ASP.Net MVC?
Here is the Edit method:
Public Function Edit() As ActionResult
Dim theevent As AEvents
If TempData("ModelState") IsNot Nothing And Not ModelState.Equals(TempData("ModelState")) Then
ModelState.Merge(CType(TempData("ModelState"), ModelStateDictionary))
End If
If RouteData.Values.ContainsKey("id") Then
theevent = NHibGet.EventWithPricingsByCode(RouteData.Values("id"))
Else
theevent = New AEvents
End If
Dim InputTemplate As New EventEdit With {.EventDate = theevent.EventDate, .EventName = theevent.EventName, .IsActive = theevent.IsActive}
If theevent.Template IsNot Nothing Then
InputTemplate.TemplateID = theevent.Template.ID
End If
Dim templates As IList(Of SeatTemplates) = NHibGet.TemplatesActive
ViewData("templates") = templates
ViewData("eventcode") = theevent.Code
ViewData("editversion") = theevent.Version
Return View(InputTemplate)
End Function
And the code for 'Save' is like this:
Public Function Save(ByVal id As Integer, ByVal UserData As EventEdit, ByVal EditVersion As Integer) As ActionResult
Dim theevent As AEvents
If id = 0 Then
theevent = New AEvents
Else
theevent = NHibGet.EventByCode(id)
End If
If theevent.Version <> EditVersion Then
ModelState.Clear()
ModelState.AddModelError("", "The event is modified by someone else")
Return RedirectToAction("Edit", New With {.id = id})
End If
If Not ModelState.IsValid Then
TempData("ModelState") = ModelState
Return RedirectToAction("Edit", New With {.id = id})
End If
theevent.EventDate = UserData.EventDate
theevent.EventName = UserData.EventName
theevent.IsActive = UserData.IsActive
theevent.Template = MvcApplication.CurrentSession.Load(Of SeatTemplates)(UserData.TemplateID)
Using trans As NHibernate.ITransaction = MvcApplication.CurrentSession.BeginTransaction
MvcApplication.CurrentSession.SaveOrUpdate(theevent)
Try
trans.Commit()
Catch ex As NHibernate.ADOException
trans.Rollback()
Throw ex
End Try
End Using
Return RedirectToAction("Edit", New With {.id = theevent.Code})
End Function
I am always in such a case instructs the user to refresh the page. It also gives him the opportunity to review fields values ​​that entered.

Good and full implementation of RSS feeds in ASP.net MVC

I've seen a few examples of RSS Feeds in ASP.NET MVC, like this, and some samples in projects (like Oxite), but none of them are complete.
Eg. None of them check for the header
If-Modified-Since
in the request, to save bandwidth.
I do not want to reinvent the wheel, so I stop here asking for some directions.
I haven't seen it implement HTTP_IF_MODIFIED_SINCE, but I would look into using the SyndicationFeed class. It makes it very simple to handle feeds without any parsing. I am currently using it for Atom feeds, but it is supposed to work for RSS as well:
function SyndicationFeed GetFeed(string url) {
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
return feed;
}
public ActionResult ShowFeed()
{
string feedUrl = "somefeedurl";
SyndicationFeed feed = GetFeed(feedUrl);
return View(feed);
}
...then in the view:
<%foreach (var item in ViewData.Model.Items) { %>
<li><%=item.Title.Text %></li>
<% } %>
If you use HttpContext.Response.Cache.SetCacheability, SetExpires and SetMaxAge then the ASP.NET caching system will take care of this for you - it understands the If-Modified-Since header. This blog entry shows how you can create an MVC Action Filter to do the necessary in MVC.
I ended up with this. Please comment or edit the post if you find any error or better way to do it.
RssController
Imports System.ServiceModel.Syndication
Imports System.Xml
Imports System.Web.HttpContext
Function MasterRSS()
Dim baseURL As String = "http://www.mysite.com"
Dim feed As New SyndicationFeed("MySite - Master RSS", "", New Uri(baseURL))
''//Add a custom attribute.
Dim xqName As New XmlQualifiedName("CustomAttribute")
feed.AttributeExtensions.Add(xqName, "Value")
Dim sp As New SyndicationPerson("jerry#mysite.com", "Jerry Seinfeld", "http://Jerry.blog.com")
feed.Authors.Add(sp)
Dim category As New SyndicationCategory("Category")
feed.Categories.Add(category)
feed.Contributors.Add(New SyndicationPerson("cosmo#mysite.com", "Cosmo Kramer", "http://kramer.blog.com"))
feed.Copyright = New TextSyndicationContent("MySite 2008")
feed.Description = New TextSyndicationContent("My description")
''//Add a custom element.
Dim doc As New XmlDocument()
Dim feedElement As XmlElement = doc.CreateElement("CustomElement")
feedElement.InnerText = "Some text"
feed.ElementExtensions.Add(feedElement)
feed.Generator = "Custom"
feed.Id = "MySiteFeedID"
feed.ImageUrl = New Uri("http://www.mysite.com/content/images/logo.png")
''//Items
Dim ModifiedSince As Date
If Not Date.TryParse(Current.Request.Headers("If-Modified-Since"), ModifiedSince) Then
ModifiedSince = Date.Today.AddDays(-30) ''//Or whatever make sense to you.
Else
ModifiedSince.AddMinutes(-5) ''//Just in case, we do not want to miss any item.
End If
''//the list of items.
Dim items As New List(Of SyndicationItem)()
Dim db As New mainDataContext
Dim textContent As TextSyndicationContent, Item As SyndicationItem
''//Then send the list of post, comments, whatever.
Dim Posts = (From p In db.Posts Where c.Date >= ModifiedSince Order By p.Date Descending)
For Each Post In Posts
Dim sb As New StringBuilder
sb.AppendFormat("<p>{0}</p>", Post.FullText)
textContent = New TextSyndicationContent(sb.ToString, TextSyndicationContentKind.Html)
Item = New SyndicationItem("Post " + Post.PostID.ToString, textContent, New Uri(baseURL + "/Post/View/" + Post.PostID.ToString), "Post" + Post.PostID.ToString, Post.Date)
items.Add(Item)
Next
If items.Count = 0 Then
''//send a 304 to the browser.
Return View("304")
End If
feed.Items = items
feed.Language = "es-ar"
feed.LastUpdatedTime = (From i In items Select i.LastUpdatedTime Order By LastUpdatedTime Descending).FirstOrDefault
''//Not needed in this sample.
''//Dim link As New SyndicationLink(New Uri("http://server/link"), "alternate", "Link Title", "text/html", 1000)
''//feed.Links.Add(link)
ViewData("feed") = feed
Return View("Rss")
End Function
Rss View (rss.aspx)
Dim htmlwriter As System.IO.Stream = Response.OutputStream
Dim rssWriter As System.Xml.XmlWriter = System.Xml.XmlWriter.Create(htmlwriter)
Dim feed As System.ServiceModel.Syndication.SyndicationFeed = ViewData("feed")
Dim rssFormatter As New System.ServiceModel.Syndication.Rss20FeedFormatter(feed)
rssFormatter.WriteTo(rssWriter)
rssWriter.Close()
This way, you can reuse the view

Resources