Why is ExecuteResult not called? - asp.net

I'm trying to implement a JSONP response in my ASP.NET MVC 5 web application. I've followed this tutorial:
http://www.ingeniumweb.com/blog/post/using-jsonp-calls-in-asp.net-mvc/1216/
The problem is that the ExecuteResult method is never called:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace subscribe.ActionResults
{
public class JsonpResult : JsonResult
{
object Data = null;
public JsonpResult()
{
}
public JsonpResult(object Data)
{
this.Data = Data;
}
public override void ExecuteResult(ControllerContext ControllerContext)
{
if (ControllerContext != null)
{
HttpResponseBase Response = ControllerContext.HttpContext.Response;
HttpRequestBase Request = ControllerContext.HttpContext.Request;
string callbackfunction = Request["callback"];
if (string.IsNullOrEmpty(callbackfunction))
{
throw new Exception("Callback function name must be provided in the request!");
}
Response.ContentType = "application/x-javascript";
if (Data != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
Response.Write(string.Format("{0}({1});", callbackfunction, serializer.Serialize(Data)));
}
}
}
}
}
In my controller I have:
public JsonpResult Get(string emailaddress, string callback, string jsonp)
{
var slist = from u in db.subscriptions
select u;
if (!String.IsNullOrEmpty(emailaddress))
slist = slist.Where(s => (s.emailaddress == emailaddress));
if (slist.Count() > 0)
{
JsonpResult result = new JsonpResult(slist.ToList());
return result; //json list of matches
}
else
{
JsonpResult result = new JsonpResult(new List<Subscription>());
return result; //empty json list
}
}

Related

Using SQLite-net-pcl and can't update the data

So i have this really annoying problem where i Can't seem to get it to update any of the databases i have created, whats worse the i can see the instance is showing the updated information but isn't applying it. I'm really new to this and is my first course project.
This is the code that is being used to update the data:
'''
using Project.Database;
using Project.DataClasses;
using Project.Pages.SuperPages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Project.Pages.UpdateDeleteListItem
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class UpdateDeleteList : ContentPage
{
private new readonly Label Title;
private Style LabelStyle;
private StoreDetails UpdateStoreDetails;
private Entry SNum;
private Entry SName;
private Entry SMName;
private Entry Addy;
public UpdateDeleteList(string pageType, object Item)
{
InitializeComponent();
BindingContext = Item;
UpdateStoreDetails = (StoreDetails)Item;
SetLabelStyle();
string titleMsg = "Update or Delete Selected " + pageType;
Frame frame = new Frame();
Label title = new Label() {Text = titleMsg };
Title = title;
StackLayout titleStack = new StackLayout() { Children = { Title } };
frame.Content = titleStack;
if (pageType == "Store")
{
StoreUDLItem(frame);
}
if (pageType == "Ticket")
{
TicketUDLItem(frame);
}
StylePage();
}
private void SaveButton_Clicked(object sender, EventArgs args)
{
if (StoreCheckValues() == true)
{
var store = SName;
var storeManager = SMName;
var storeNumber = SNum;
var address = Addy;
var storeDataAccess = new StoreDataAccess();
UpdateStoreDetails.StoreName = store.Text;
UpdateStoreDetails.StoreManger = storeManager.Text;
UpdateStoreDetails.StoreNumber = storeNumber.Text;
UpdateStoreDetails.Address = address.Text;
//MerchandiserKey = GetMerchId()
storeDataAccess.SaveStoreDetails(UpdateStoreDetails);
storeDataAccess.SaveAllStoreDetails();
}
'''
here is the data access methods:
'''
using Project.DataClasses;
using SQLite;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using Xamarin.Forms;
namespace Project.Database
{
class StoreDataAccess
{
private SQLiteConnection database;
private static object collisionLock = new object();
public ObservableCollection<StoreDetails> StoreDetails { get; set; }
public StoreDataAccess()
{
database = DependencyService.Get<IDatabaseConnection>().DbConnectionStore();
database.CreateTable<StoreDetails>();
this.StoreDetails = new ObservableCollection<StoreDetails>(database.Table<StoreDetails>());
//AddNewTicket(new Ticket ticket);
}
//add ticket method
public void AddNewStore(StoreDetails item)
{
this.StoreDetails.Add(item);
}
//retrieve ticket method
public StoreDetails GetStoreDetails(int id)
{
lock (collisionLock)
{
return database.Table<StoreDetails>().FirstOrDefault(StoreDetails => StoreDetails.StoreId == id);
}
}
//save ticket
public int SaveStoreDetails(StoreDetails storeDetailsInstance)
{
lock (collisionLock)
{
if (storeDetailsInstance.StoreId != 0)
{
database.Update(storeDetailsInstance);
return storeDetailsInstance.StoreId;
}
else
{
database.Insert(storeDetailsInstance);
return storeDetailsInstance.StoreId;
}
//database.Commit();
}
}
public void SaveAllStoreDetails()
{
lock (collisionLock)
{
foreach (var storeDetailsInstance in this.StoreDetails)
{
if (storeDetailsInstance.StoreId != 0)
{
database.Update(storeDetailsInstance);
}
else
{
database.Insert(storeDetailsInstance);
}
}
}
}
'''
This is the page that is sending the information to the first code block to bind the data too
'''
using Project.Database;
using Project.DataClasses;
using Project.Pages.UpdateDeleteListItem;
using SQLite;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Project.Pages.ListPages
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class StoreList : ContentPage
{
private ObservableCollection<StoreDetails> Items { get; set; }
private readonly StoreDataAccess storeDataAccess;
private readonly SQLiteConnection database;
public StoreList()
{
InitializeComponent();
storeDataAccess = new StoreDataAccess();
this.BindingContext = this.storeDataAccess;
Items = storeDataAccess.StoreDetails;
StoreView.ItemsSource = Items;
}
async void Handle_ItemTapped(object sender, ItemTappedEventArgs e)
{
if (e.Item == null) { return; }
else
{
//var id = Items[e.ItemIndex].StoreId;
await Navigation.PushAsync(new UpdateDeleteList("Store", e.Item));
//Deselect Item
((ListView)sender).SelectedItem = null;
}
}
//page reload handle
protected override void OnAppearing()
{
base.OnAppearing();
var dbName = "StoreListDatabase.db3";
var path = Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.Personal), dbName);
if (database == null)
{
new StoreDataAccess();
}
using (SQLiteConnection conn = new SQLiteConnection(path))
{
Items = storeDataAccess.StoreDetails;
StoreView.ItemsSource = Items;
}
}
}
}
'''
and lastly here is my databbase model for it:
'''
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
using SQLite;
using System.ComponentModel;
namespace Project.DataClasses
{
class StoreDetails : INotifyPropertyChanged
{
private int _storeId;
[PrimaryKey, AutoIncrement, NotNull]
public int StoreId
{
get { return _storeId; }
set { _storeId = value; OnPropertyChanged(nameof(StoreId)); }
}
private string _storeName;
[NotNull, DefaultValue("Enter Store Name")]
public string StoreName
{
get { return _storeName; }
set { _storeName = value; OnPropertyChanged(nameof(_storeName)); }
}
private string _storeManger;
[NotNull, DefaultValue("Enter Store Managers Name")]
public string StoreManger
{
get { return _storeManger; }
set { _storeManger = value; OnPropertyChanged(nameof(StoreManger)); }
}
private string _storeNumber;
[NotNull, DefaultValue("Enter Store Number")]
public string StoreNumber
{
get { return _storeNumber; }
set { _storeNumber = value; OnPropertyChanged(nameof(StoreNumber)); }
}
private string _address;
[NotNull, DefaultValue("Enter Address")]
public string Address
{
get { return _address; }
set { _address = value; OnPropertyChanged(nameof(Address)); }
}
private int _merchandiserKey;
[NotNull]
public int MerchandiserKey
{
get { return _merchandiserKey; }
set { _merchandiserKey = value; OnPropertyChanged(nameof(MerchandiserKey)); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
'''
any help would be greatly appreciated
'''
public int SaveStoreDetails(StoreDetails storeDetailsInstance)
{
lock (collisionLock)
{
if (storeDetailsInstance.StoreId != 0)
{
database.Update(storeDetailsInstance);
return storeDetailsInstance.StoreId;
}
else
{
database.Insert(storeDetailsInstance);
return storeDetailsInstance.StoreId;
}
//database.Commit();
}
}
'''
this is the area where it all seems to be going wrong i just don't know why
Thank You Jason, you were correct in that the error was in calling both the savefunctions and overwriting it!!

Project doesn`t have access to referenced project in the c# solution

I'm trying to access a method from a class which is in another project but in the same solution. The problem i face is that it keeps saying that i'm missing a reference even when i'm using the using namespace of the project.
This code is in project 2 and it is a controller. which is referenced to project 1
namespace WebSvc1.Controllers
{
public class RemunerationController : ApiController
{
[HttpPost]
public void BonusRecipient(BonusRecipients bonusRecipients)
{
XmlSerializer writer = new XmlSerializer(typeof(BonusRecipients));
var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
"//BonusReipients.xml";
FileStream file = File.Create(path);
writer.Serialize(file, bonusRecipients);
file.Dispose();
file.Close();
}
}
}
And this code is in project 1 which should call the method from the controller in project 2
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Mvc;
using Newtonsoft.Json;
using WebApp1.DataContracts;
using WebApp1.Models;
namespace WebApp1.Controllers
{
public class BonusController : Controller
{
// GET: Bonus
public ActionResult Index()
{
return View("View");
}
// POST: Bonus/Allocate
[HttpPost]
public async Task<ActionResult> Allocate(BonusViewModel bonusAllocation)
{
try
{
var employees = await GetEmployees();
List<Employee> recipients = new List<Employee>();
for (int i = 0; i < employees.Count; i++)
{
if (i % bonusAllocation.OneInXEmployees == 0)
{
var recipient = employees[i];
recipients.Add(recipient);
employees.Remove(recipient);
}
}
//BonusRecipient(recipients);
return RedirectToAction("Index", "Home");
}
catch
{
return View("View");
}
}
private async Task<List<Employee>> GetEmployees()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:57652/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await
client.GetAsync($"api/employee");
if (response.IsSuccessStatusCode)
{
string employeeData = await
response.Content.ReadAsStringAsync();
List<Employee> employees =
JsonConvert.DeserializeObject<List<Employee>>(employeeData);
return employees;
}
return new List<Employee>();
}
}
}

ServiceStack RSS serialisation issue

I'm trying to create an RSS feed for a ServiceStack Service. I've followed various examples as closely as I can. My problem is that I get no output and I am not sure how to troubleshoot the issue. I suspect I have done something wrong on the serialisation. Here is (a simplified version of) what I have
My DTO's are
using System.Collections.Generic;
using ServiceStack;
using Library;
[Route("/MyCollection/Tomorrow/{ID}", "GET, POST")]
[Api("MyCollections Delivery")]
public class MyCollectionTomorrow
: IReturn<MyCollectionTomorrowResponse>
{
public long ID { get; set; }
}
public class MyCollectionTomorrowResponse : IHasResponseStatus
{
public long ID { get; set; }
public List<MyCollection> Result { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
public class MyCollection
{
public string Description { get; set; }
public string MyCollectionDayOfWeek { get; set; }
public DateTime MyCollectionDate { get; set; }
public bool Assisted { get; set; }
public string RoundType { get; set; }
public string Description { get; set; }
}
My service is
using System;
using Library;
using ServiceStack;
using ServiceStack.Configuration;
using System;
using Library;
using ServiceStack;
using ServiceStack.Configuration;
using MyCollection.Tomorrow;
using MyCollections.Tomorrow;
public class MyCollectionTomorrowService : Service
{
public object Any(WasteCollectionTomorrow request)
{
int id;
var param = new CollectionTomorrow();
param.ID = ID;
var response = client.Get<CollectionTomorrowResponse>(param);
return response;
}
catch (Exception ex)
{
var response = new CollectionTomorrowResponse();
response.Result = null
var status = new ResponseStatus { Message = ex.Message, StackTrace = ex.StackTrace };
response.ResponseStatus = status;
return response;
}
}
}
and my media type is
namespace DataFeedServices
{
using System;
using System.IO;
using System.ServiceModel.Syndication;
using System.Text;
using System.Xml;
using ServiceStack;
using ServiceStack.Data;
using ServiceStack.Web;
using MyCollections.Tomorrow;
public class RssFormat
{
private const string RssContentType = "application/rss+xml";
public static void Register(IAppHost appHost)
{
appHost.ContentTypes.Register(RssContentType, SerializeToStream, DeserializeFromStream);
}
public static void SerializeToStream(IRequest req, object response, Stream stream)
{
StreamWriter sw = null;
try
{
var syndicationFeedResponse = response as MyCollectionResponse;
sw = new StreamWriter(stream);
if (response != null)
{
WriteRssCollectionFeed(sw, syndicationFeedResponse);
}
}
finally
{
if (sw != null)
{
sw.Dispose();
}
}
}
public static void WriteRssCollectionFeed(StreamWriter sw, MyCollectionResponse Mycollections)
{
const string Baseuri = "example.com";
try
{
var uri = new Uri(Baseuri);
var syndicationFeed = new SyndicationFeed(
"MyCollection Service",
"Mycollections " ,
uri);
syndicationFeed.Authors.Add(new SyndicationPerson("email#mysite.com"));
if (Mycollections.Result != null)
{
foreach (var cats in Mycollections.Result)
{
syndicationFeed.Categories.Add(new SyndicationCategory(cats.RoundID));
}
}
syndicationFeed.Generator = "MyApp";
syndicationFeed.Copyright = new TextSyndicationContent("Copyright 2015");
syndicationFeed.LastUpdatedTime = DateTime.Now;
if (Mycollections.Result != null)
{
// set items
foreach (var coll in Mycollections.Result)
{
var item = new SyndicationItem { Title = new TextSyndicationContent(coll.CollectionDate) };
item.Links.Add(new SyndicationLink(uri));
item.Authors.Add(new SyndicationPerson("email#mysite.com"));
var itemContent = new StringBuilder();
itemContent.Append("My Item content");
item.Content = new TextSyndicationContent(
itemContent.ToString(),
TextSyndicationContentKind.Plaintext);
}
}
Rss20FeedFormatter rssFeed = syndicationFeed.GetRss20Formatter();
var xwriter = XmlWriter.Create(sw);
rssFeed.WriteTo(xwriter);
}
catch (Exception)
{
throw new Exception("Something bad happened");
}
}
public static object DeserializeFromStream(Type type, Stream stream)
{
throw new NotImplementedException();
}
}
}
Since your ContentType is not reusable and coupled to a specific MyCollectionResponse, it's easier to just return a raw string with the RSS XML:
[AddHeader(ContentType = "application/rss+xml")]
public object Any(WasteCollectionTomorrow request)
{
//..
return rssXml;
}
You can also write it directly to the Response Output Stream with something like:
public object Any(WasteCollectionTomorrow request)
{
//..
base.Response.ContentType = "application/rss+xml";
RssFormat.SerializeToStream(response, Response.OutputStream);
base.Response.EndRequest();
return null;
}

How to map routes dynamically?

With a website, I am using the built-in routing tools available within the newer version of ASP.NET, but they aren't currently dynamic, they're hard coded into the codebase in the global.asax file.
Not sure if this is possible but, is there a way that those routes can be generated dynamically?
You could subclass RouteBase in order to make your routes based on a dynamic data set.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Routing;
using System.Web;
using System.Web.Mvc;
public class ProductRoute : RouteBase
{
public override RouteData GetRouteData(HttpContextBase httpContext)
{
RouteData result = null;
string virutalPath = httpContext.Request.Url.AbsolutePath.Substring(1).ToLowerInvariant();
// Call the database here to retrieve the productId based off of the virtualPath
var productId = Product.GetProductIdFromVirtualPath(virutalPath);
if (productId != Guid.Empty)
{
result = new RouteData(this, new MvcRouteHandler());
result.Values["controller"] = "Product";
result.Values["action"] = "Details";
result.Values["id"] = productId;
}
return result;
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
VirtualPathData result = null;
string controller = Convert.ToString(values["controller"]);
string action = Convert.ToString(values["action"]);
if (controller == "Product")
{
string path = string.Empty;
if (action == "Details")
{
Guid productId = (Guid)values["id"];
// Call the database here to get the Virtual Path
var virtualPath = Product.GetVirtualPathFromProductId(productId);
}
if (!String.IsNullOrEmpty(virtualPath))
{
result = new VirtualPathData(this, virtualPath);
}
}
return result;
}
}

Convert a image handler from ASPX to asynchronus ASHX

Im struggling with bad performance on one of my websites. It is handling a lot of images, and I serve images through an image handler. When I created it I did a mistake and created a ASPX file to handle the images, I should have used an generic handler (ASHX).
I found this good site, which looks promising. It is about creating an asynchronus image handler. But I have very little knowledge about this, and need some help.
Help site:
http://msdn.microsoft.com/en-us/magazine/cc163463.aspx
This is how my ShowImage.aspx file looks now:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Configuration;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.Caching;
using System.Collections;
public partial class ShowImage : System.Web.UI.Page
{
Gallery gal = new Gallery();
private void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Start with empty Response object.
Response.Clear();
// Get the image path from the URL.
string imagePath = Request.QueryString["image"];
// Set the size of the image
int maxHeight = 1000;
if (Request.QueryString["maxHeight"] != null)
{
string mh = Request.QueryString["maxHeight"];
maxHeight = int.Parse(mh);
}
int maxWidth = 1000;
if (Request.QueryString["maxWidth"] != null)
{
string mw = Request.QueryString["maxWidth"];
maxWidth = int.Parse(mw);
}
string thumbPath = gal.ThumbnailPath(Server.MapPath(imagePath), maxHeight, maxWidth);
byte[] buffer = null;
System.Drawing.Image img = System.Drawing.Image.FromFile(thumbPath);
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, img.RawFormat);
buffer = ms.ToArray();
}
Response.ContentType = "image/" + Path.GetExtension(thumbPath).Remove(0, 1);
Response.OutputStream.Write(buffer, 0, buffer.Length);
img.Dispose();
Response.End();
}
}
}
I have started with the handler ShowImage.ashx, but im a bit stuck. Any help is appreciated. Im not sure where I should merge my code with this.
using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Threading;
using System.IO;
public class ShowImage : IHttpAsyncHandler
{
//private ShowImageService _ts;
private ShowImageServiceAsyncResult _ar;
private HttpContext _context;
private Exception _ex;
public void ProcessRequest (HttpContext context)
{
// Never used
}
public bool IsReusable { get { return false; } }
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object state)
{
_context = context;
_ar = new ShowImageServiceAsyncResult(cb, state);
// SHOULD I PLACE CODE HERE?
return _ar;
}
public void EndProcessRequest(IAsyncResult ar)
{
if (_ex != null)
{
// If an exception was thrown, rethrow it
throw _ex;
}
else
{
// Otherwise return the generated image
}
}
}
class ShowImageServiceAsyncResult : IAsyncResult
{
private AsyncCallback _cb;
private object _state;
private ManualResetEvent _event;
private bool _completed = false;
private object _lock = new object();
public ShowImageServiceAsyncResult(AsyncCallback cb, object state)
{
_cb = cb;
_state = state;
}
public Object AsyncState { get { return _state; } }
public bool CompletedSynchronously { get { return false; } }
public bool IsCompleted { get { return _completed; } }
public WaitHandle AsyncWaitHandle
{
get
{
lock (_lock)
{
if (_event == null)
_event = new ManualResetEvent(IsCompleted);
return _event;
}
}
}
public void CompleteCall()
{
lock (_lock)
{
_completed = true;
if (_event != null) _event.Set();
}
if (_cb != null) _cb(this);
}
}
You're not making any asynchronous calls to retrieve your Image, so you don't need an asynchronous handler.
Derive from IHttpHandler and just put your code in ProcessRequest.

Resources