RouteData values are valid on one page but empty on another - c#

I have an app I'm building for automating the process of creating media kits when promoting a show or local event and I've hit something weird.
In my application, I have two web forms ~/KitInfo.aspx and ~/Photo.aspx.
In my ~\App_Start\RouteConfig.cs I have the following boiler plate code.
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
}
}
In my Global.asax.cs I have the following routes registered:
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
// Add Custom Routes
RegisterCustomRoutes(RouteTable.Routes);
}
private void RegisterCustomRoutes(RouteCollection routes)
{
routes.MapPageRoute("MediaKitInforRoute", "Kit/{show}", "~/KitInfo.aspx");
routes.MapPageRoute("PhotoRoute", "Photo/{show}/{photo}/{medium}/{size}/{download}", "~/Photo.aspx");
}
I have a utility method for accessing the route data values:
public static T GetRouteData<T>(string segmentName, T defaultValue)
{
var result = defaultValue;
try
{
var textValue = HttpContext.Current.Request.RequestContext.RouteData.Values[segmentName].ToString();
result = (T)Convert.ChangeType(textValue, typeof(T));
}
catch (Exception)
{
// Do nothing
}
return result;
}
KitInfo.aspx.cs has the following code:
protected void Page_Load(object sender, EventArgs e)
{
var show = Utility.GetRouteData("show", string.Empty);
var path = Server.MapPath("~/KitArchives/" + show);
var kitPath = Path.Combine(path, show + ".kit");
var kit = Kit.Load(kitPath);
KitName.Text = kit.ShowTitle;
}
Photo.aspx.cs has this code in the Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
var show = Utility.GetRouteData("show", string.Empty);
var photo = Utility.GetRouteData("photo", string.Empty);
var medium = Utility.GetRouteData("medium", string.Empty);
var maxSize = Utility.GetRouteData("size", -1);
var download = Utility.GetRouteData("download", 1);
if (show.Length == 0)
{
SendImageNotFound();
return;
}
Navigating to http://mediakits.server.com/kit/queen, the page will successfully load the media kit for the show value of queen. Any other value will fail with expected results as the queen show is my test kit.
Navigating to http://mediakits.server.com/Photo/queen/ShowPoster/print/900/0 fails because all of the route data is empty and Utility.GetRouteData("show", string.Empty) returns the default value of string.Empty, tripping that error check.
I'm baffled as to why it would work on one page and not the other. Do you have any thoughts?

Related

Why do you close the app when I change the page?

I have two List <>.
List<Musei> ListMusei;
List<Regioni> reg;
the object "Musei" has the property "Paese", while the object "Regioni" has the property "NomeProvincia".
The List "reg" is inserted in a ListView, and when pressed on an item, this method is invoked:
private void Listviewcitt_ItemClick(object sender, ItemClickEventArgs e)
{
var result = ((Regioni)e.ClickedItem).NomeProvincia.ToString();
var filtro = ListMusei.Where(x => x.Paese.Equals(result));
try
{
Frame.Navigate(typeof(PageAroundMe), filtro);
}
catch(Exception)
{
}
}
application where I always closes. I thought there was some problem in the "AroundMe", and then paste the code here:
In Page AroundMe I do this:
List<Musei> ListMusei;
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
ListMusei = (List<Musei>) e.Parameter;
List<Pushpin> push = new List<Pushpin>();
foreach (Musei SingoloMuseo in ListMusei)
{
Pushpin Pushpin pushpin1 = new ();
GeoPoint posizioneP;
try
{
MapLocationFinderResult result = await MapLocationFinder.FindLocationsAsync (SingoloMuseo.Indirizzo, null);
posizioneP result.Locations.FirstOrDefault = ().Point;
pushpin1.Name = SingoloMuseo.NomeMuseo;
pushpin1.Location = posizioneP;
push.Add (pushpin1);
}
catch (Exception)
{
continue;
}
}
Where is the problem? I can not even figure out where I will close
You can pass the parameter like
Frame.Navigate(typeof(PageAroundMe), filtro.ToList());
The invalid cast exception occurs because you are trying to cast IEnumerable type to List.

Stripe.Net Create and Update user

Im very new to programing and new to stripe. i am currently trying to create a basic page where i can just create the customers. Im currently using the stripe.net dll and am having a hard time getting this page to work correctly. Here is what i have. I get no errors and no records get created.
Using Stripe;
private StripeCustomer GetCustomer()
{
var mycust = new StripeCustomerCreateOptions();
mycust.Email = "thisisit#overhere.com";
mycust.Description = "One Time";
mycust.CardName = "Full Name";
var customerservice = new StripeCustomerService(System.Web.Configuration.WebConfigurationManager.AppSettings["StripeApiKey"]);
return customerservice.Create(mycust);
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
StripeCustomer current = GetCustomer();
var mycharge = new StripeChargeCreateOptions();
string key = System.Web.Configuration.WebConfigurationManager.AppSettings["StripeApiKey"];
Response.Redirect("/services/donate/thanks.aspx");
}
catch (StripeException ex)
{
//lblerror.Text = (ex.Message);
}
}
Also a little help (as i am lost an nothing i try works) as to how i would go about pulling a list of the current customs i have and display them would be great.
I'm guessing you're using this: https://github.com/jaymedavis/stripe.net#list-all-customers
In your GetCustomer method you are creating a customer, instead, you want to do something like the following:
private IEnumerable<StripeCustomer> GetCustomers()
{
var customerservice = new StripeCustomerService(System.Web.Configuration.WebConfigurationManager.AppSettings["StripeApiKey"]);
return customerservice.List();
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
StripeCustomer list = GetCustomers();
//show this list somewhere
}
catch (StripeException ex)
{
//lblerror.Text = (ex.Message);
}
}
Makre sure StripeApiKey exists in your configuration file.

How to save a page state?

In a Windows Runtime app, I load data like this:
private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
var userId = e.NavigationParameter as string;
List<User> followers = GetFollowers(userId);
this.DefaultViewModel["Followers"] = followers;
}
then user can select an item from ListView:
private void ContentListView_ItemClick(object sender, ItemClickEventArgs e)
{
var selectedItem = e.ClickedItem as User;
if (!Frame.Navigate(typeof(FollowersPage), selectedItem.UserId))
{
throw new Exception(this.resourceLoader.GetString("NavigationFailedExceptionMessage"));
}
}
So it navigates forward to the same page, but shows new followers.
The problem is that when it navigates back, it loads data again and shows from the beginning of the list rather than showing the last item selected.
So how to save a List of data in NavigationHelper_SaveState and how to load it again in NavigationHelper_LoadState with last position in the list? thanks.
Here's a basic semi-tested example you can start from. You'll need to modify it to fit your exact circumstances. Some of it is adapted from here.
void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
var isp = (ItemsStackPanel)listview.ItemsPanelRoot;
int firstVisibleItem = isp.FirstVisibleIndex;
e.PageState["FirstVisibleItemIndex"] = firstVisibleItem;
// This must be serializable according to the SuspensionManager
e.PageState["Followers"] = this.DefaultViewModel["Followers"];
}
void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
// Do we have saved state to restore?
if (e.PageState != null)
{
// Restore list view items
this.DefaultViewModel["Followers"] = (WhateverType)e.PageState["Followers"];
// Restore scroll offset
var index = (int)e.PageState["FirstVisibleItemIndex"];
var container = listview.ContainerFromIndex(index);
listview.ScrollIntoView(container);
}
else
{
// Load data for the first time
var userId = e.NavigationParameter as string;
List<User> followers = GetFollowers(userId);
this.DefaultViewModel["Followers"] = followers;
}
}

Simple Google Api example hangs on Outlook Addin

I have a Win Form that is called from within a ribbon inside an Outlook Add-In.
This WinForm calls the following code:
private void lnkReload_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Run().Wait();
}
private async Task Run()
{
// Create the service.
var service = new DiscoveryService(new BaseClientService.Initializer
{
ApplicationName = "Discovery Sample",
ApiKey = Properties.Settings.Default.ClientId
});
// Run the request.
Console.WriteLine("Executing a list request...");
var result = await service.Apis.List().ExecuteAsync();
// Display the results.
if (result.Items != null)
{
foreach (DirectoryList.ItemsData api in result.Items)
{
Console.WriteLine(api.Id + " - " + api.Title);
}
}
}
When debugging the code, at the line "car result=await"...
the code stops working. This sure can take SOME time, but reading that List should not take hours.
Any clue?
Try this:
private async void lnkReload_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
await Run();
}

Error in Content Page on initializing FacebookClient

I am getting an error "Object Reference is not set to an Instance of an object" in the ContentPage of my MasterPage Facebook Application.
Site.master.cs
public FacebookSession CurrentSession
{
get { return (new CanvasAuthorizer()).Session; }
}
protected void Page_Load(object sender, EventArgs e)
{
var auth = new CanvasAuthorizer { Perms = "email,read_stream,publish_stream,offline_access,user_about_me" };
if (auth.Authorize())
{
ShowFacebookContent();
}
}
private void ShowFacebookContent()
{
var fb = new FacebookClient(this.CurrentSession.AccessToken);
dynamic myInfo = fb.Get("me");
lblName.Text = myInfo.name;
imgProfile.ImageUrl = "https://graph.facebook.com/" + myInfo.id + "/picture";
lblBirthday.Text = myInfo.birthday;
pnlHello.Visible = true;
}
This master Page works OK & displays UserName & ProfilePic.
Default.aspx.cs
SiteMaster myMasterPage;
protected void Page_Load(object sender, EventArgs e)
{
myMasterPage = this.Page.Master as SiteMaster;
}
public void LinkButton1_Click(object sender, EventArgs e)
{
var fb = new FacebookClient(this.myMasterPage.CurrentSession.AccessToken);
dynamic feedparameters = new ExpandoObject();
feedparameters.message = (message_txt.Text == null ? " " : message_txt.Text);
feedparameters.user_message_prompt = "userPrompt";
/*Dictionary<string, object> feedparameters = new Dictionary<string, object>();
feedparameters.Add("message", "Testing Application");
feedparameters.Add("user_message_prompt", "Post To Your Wall");
feedparameters.Add("display", "iframe");*/
dynamic result = fb.Post("me/feed", feedparameters);
}
Even this Page Loads OK but Problem comes when I try to Post using LinkButton.
Following Line gives the error.
var fb = new FacebookClient(this.myMasterPage.CurrentSession.AccessToken);
On LinkButton Click Object Reference is not set to an Instance of an object...
I will really appreciate some help.
Wel finally found what was the problem. Needed to add a hidden field.
<input type="hidden" name="signed_request" value="<%: Request.Params["signed_request"]%>"/>
I think this is neither mentioned any where in the documentation nor in the Provided Samples.

Categories