Script Notify for ms-appdata - c#

I want to notify my web view from button in html file and trigger the javascript:
function notify(str) {
window.external.notify(str);
}
The event captured using wv_ScriptNotify(..., ...):
void wv_ScriptNotify(object sender, NotifyEventArgs e)
{
Color c=Colors.Red;
if (e.CallingUri.Scheme =="ms-appx-web" || e.CallingUri.Scheme == "ms-appdata")
{
if (e.Value.ToLower() == "blue") c = Colors.Blue;
else if (e.Value.ToLower() == "green") c = Colors.Green;
}
appendLog(string.Format("Response from script at '{0}': '{1}'", e.CallingUri, e.Value), c);
}
I set the html file on ms-appx-web and it running well, and I realize that the html file must be store into local folder. So I change the ms-appx-web:///.../index.html to ms-appdata:///local/.../index.html.
Already search in microsoft forum and get this. On that thread there is a solution using resolver, but I'm still confusing, how can it notify from javascript like using window.external.notify? And what kind of event in C# side that will capture the "notify" from javascript other than "ScriptNotify"?
Update
There is a solution from here, example using the resolver and it said to use ms-local-stream:// rather than using ms-appdata://local so I can still use the ScriptNotify event. But unfortunately the example using the ms-appx that means using the InstalledLocation not the LocalFolder.
Trying to googling and search in msdn site for the documentation for ms-local-stream but the only documentation is just the format of ms-local-stream without any example like this ms-local-stream://appname_KEY/folder/file.
Based from that documentation, I made some sample to try it:
public sealed class StreamUriWinRTResolver : IUriToStreamResolver
{
/// <summary>
/// The entry point for resolving a Uri to a stream.
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
public IAsyncOperation<IInputStream> UriToStreamAsync(Uri uri)
{
if (uri == null)
{
throw new Exception();
}
string path = uri.AbsolutePath;
// Because of the signature of this method, it can't use await, so we
// call into a separate helper method that can use the C# await pattern.
return getContent(path).AsAsyncOperation();
}
/// <summary>
/// Helper that maps the path to package content and resolves the Uri
/// Uses the C# await pattern to coordinate async operations
/// </summary>
private async Task<IInputStream> getContent(string path)
{
// We use a package folder as the source, but the same principle should apply
// when supplying content from other locations
try
{
// My package name is "WebViewResolver"
// The KEY is "MyTag"
string scheme = "ms-local-stream:///WebViewResolver_MyTag/local/MyFolderOnLocal" + path; // Invalid path
// string scheme = "ms-local-stream:///WebViewResolver_MyTag/MyFolderOnLocal" + path; // Invalid path
Uri localUri = new Uri(scheme);
StorageFile f = await StorageFile.GetFileFromApplicationUriAsync(localUri);
IRandomAccessStream stream = await f.OpenAsync(FileAccessMode.Read);
return stream.GetInputStreamAt(0);
}
catch (Exception) { throw new Exception("Invalid path"); }
}
}
And inside my MainPage.xaml.cs:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// The 'Host' part of the URI for the ms-local-stream protocol needs to be a combination of the package name
// and an application-defined key, which identifies the specific resolver, in this case 'MyTag'.
Uri url = wv.BuildLocalStreamUri("MyTag", "index.html");
StreamUriWinRTResolver myResolver = new StreamUriWinRTResolver();
// Pass the resolver object to the navigate call.
wv.NavigateToLocalStreamUri(url, myResolver);
}
It always get the exception when it reach the StorageFile f = await StorageFile.GetFileFromApplicationUriAsync(localUri); line.
If anybody ever got this problem and already solved it, please advise.

After debugging it, I found something interesting, the BuildLocalStreamUri part is already make the ms-local-stream automatically.
I made some changes on the getContent method inside StreamUriWinRTResolver class:
public sealed class StreamUriWinRTResolver : IUriToStreamResolver
{
/// <summary>
/// The entry point for resolving a Uri to a stream.
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
public IAsyncOperation<IInputStream> UriToStreamAsync(Uri uri)
{
if (uri == null)
{
throw new Exception();
}
string path = uri.AbsolutePath;
// Because of the signature of this method, it can't use await, so we
// call into a separate helper method that can use the C# await pattern.
return getContent(path).AsAsyncOperation();
}
/// <summary>
/// Helper that maps the path to package content and resolves the Uri
/// Uses the C# await pattern to coordinate async operations
/// </summary>
private async Task<IInputStream> getContent(string path)
{
// We use a package folder as the source, but the same principle should apply
// when supplying content from other locations
try
{
// Don't use "ms-appdata:///" on the scheme string, because inside the path
// will contain "/local/MyFolderOnLocal/index.html"
string scheme = "ms-appdata://" + path;
Uri localUri = new Uri(scheme);
StorageFile f = await StorageFile.GetFileFromApplicationUriAsync(localUri);
IRandomAccessStream stream = await f.OpenAsync(FileAccessMode.Read);
return stream.GetInputStreamAt(0);
}
catch (Exception) { throw new Exception("Invalid path"); }
}
}
Change the file path on the MainPage.xaml.cs:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// The 'Host' part of the URI for the ms-local-stream protocol needs to be a combination of the package name
// and an application-defined key, which identifies the specific resolver, in this case 'MyTag'.
Uri url = wv.BuildLocalStreamUri("MyTag", "/local/MyFolderOnLocal/index.html");
StreamUriWinRTResolver myResolver = new StreamUriWinRTResolver();
// Pass the resolver object to the navigate call.
wv.NavigateToLocalStreamUri(url, myResolver);
wv.ScriptNotify += wv_ScriptNotify;
}
protected override void wv_ScriptNotify(object sender, NavigationEventArgs e)
{
if (e.CallingUri.Scheme == "ms-local-stream")
{
// Do your work here...
}
}

Related

Convert SVG to .vsdx MS Visio file

I have an application that produces SVG diagrams, we would like to create an export to Visio option that would, ideally, behind the scenes (via server-side C#) take an SVG file and convert it directly to an MS Visio .vsdx file that the user can download and then ofcourse open and edit in Visio seamlessly (as opposed to having to download the SVG file, and then importing it themselves into Visio). In effect, trying to replicate the "Open SVG" functionality that the Visio GUI supplies in backend C#.
I have seen a lot of answers on going from Visio TO SVG, but this is the opposite.
I also know that .vsdx is simply a zip file, but with that extension. Inside are a bunch of visio specific files and folders - if anyone knows what is the bare minimum required of these files/folders and their contents and where the SVG fits in, perhaps that's one way to do it.
Any guidance would be much appreciated.
Dug this up, credit/source: https://programmer.group/5c650f3227420.html
SVG can be converted to Visio's vsd format. The method is very simple. The main method is to open the SVG file and save it as a vsd file. The invocation method is as follows:
/// <summary>
/// svg turn vsd
/// </summary>
/// <param name="svgFn">svn file name</param>
/// <param name="desVsdFn">Preserved vsd file name</param>
private static void Svg2Vsd(string svgFn, string desVsdFn)
{
var app = ComObj.Create("Visio.Application");
app["Visible"] = new ComObj(false);
var docs = app["Documents"];
short visOpenHidden = 64, visOpenRO = 2;
var doc = docs.Call("OpenEx", svgFn, visOpenHidden + visOpenRO);
doc.Call("SaveAs", desVsdFn);
doc.Call("Close");
var win = app["Window"];
app.Call("Quit");
}
Here I use a ComObj class I wrote myself. Its purpose is to make it easy to invoke Com components such as Office by reflection, and to make the code concise when invoking.
Why use reflection to invoke dynamically instead of directly referencing Com components? The main purpose is to reduce the dependence and coupling of program code to COM components, so as to facilitate the compilation and distribution of code deployment. Dynamic invocation can be compiled and run without adding component references. If the Com component is not installed on the server, you can also give an intuitive prompt instead of a program error.
The code for this class is as follows:
using System;
using System.Reflection;
namespace HZ.Common
{
/// <summary>
/// For convenience Com Object attributes, method calls
/// </summary>
public class ComObj
{
public static ComObj Create(string progId)
{
var type = Type.GetTypeFromProgID(progId);
if (type == null)
{
throw new Exception("Servers need to be installed" + progId + "To use this feature");
}
return new ComObj(Activator.CreateInstance(type));
}
private object _val;
/// <summary>
/// Actual value
/// </summary>
public object Val
{
get { return _val; }
}
public ComObj(object comObject)
{
_val = comObject;
}
public ComObj Call(string mehtod, params object[] args)
{
if (_val == null)
return null;
var ret = _val.GetType().InvokeMember(mehtod, BindingFlags.InvokeMethod, null, _val, args);
return new ComObj(ret);
}
public ComObj this[string property]
{
get
{
if (_val == null)
return null;
var ret = _val.GetType().InvokeMember(property, BindingFlags.GetProperty, null, _val, null);
return new ComObj(ret);
}
set
{
if (_val != null)
_val.GetType().InvokeMember(property, BindingFlags.SetProperty, null, _val, new object[] { value.Val });
}
}
}
}

How to use Fonts in PDFsharp in my Website?

I am just using the Arial font on an Azure WebApplication web site but when I get to this line:
MainFont = new XFont("Arial", FontSize);
it throws an exception reading: Font data could not retrieved.
I would have thought Arial would have been installed on the server ... and I also tried changing it to Sans-Serif to match the default font of the Microsoft generated web-site ... but it still fails.
I have also tried adding Arial.ttf to the project, but that hasn't worked.
Thanks for the pointers #PDFSharp Team. Here is my implementation for PdfSharp 1.5 beta3b:
Add the fonts you want to your project - in my example below I put Arial in MyProject\fonts\arial\arial.ttf etc. Set each font file as an embedded resource (properties -> build action).
Apply the font resolver only once using the static call like this:
MyFontResolver.Apply(); // Ensures it's only applied once
Here's the font resolver class:
class MyFontResolver : IFontResolver
{
public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic)
{
// Ignore case of font names.
var name = familyName.ToLower().TrimEnd('#');
// Deal with the fonts we know.
switch (name)
{
case "arial":
if (isBold)
{
if (isItalic)
return new FontResolverInfo("Arial#bi");
return new FontResolverInfo("Arial#b");
}
if (isItalic)
return new FontResolverInfo("Arial#i");
return new FontResolverInfo("Arial#");
}
// We pass all other font requests to the default handler.
// When running on a web server without sufficient permission, you can return a default font at this stage.
return PlatformFontResolver.ResolveTypeface(familyName, isBold, isItalic);
}
/// <summary>
/// Return the font data for the fonts.
/// </summary>
public byte[] GetFont(string faceName)
{
switch (faceName)
{
case "Arial#":
return FontHelper.Arial;
case "Arial#b":
return FontHelper.ArialBold;
case "Arial#i":
return FontHelper.ArialItalic;
case "Arial#bi":
return FontHelper.ArialBoldItalic;
}
return null;
}
internal static MyFontResolver OurGlobalFontResolver = null;
/// <summary>
/// Ensure the font resolver is only applied once (or an exception is thrown)
/// </summary>
internal static void Apply()
{
if (OurGlobalFontResolver == null || GlobalFontSettings.FontResolver == null)
{
if (OurGlobalFontResolver == null)
OurGlobalFontResolver = new MyFontResolver();
GlobalFontSettings.FontResolver = OurGlobalFontResolver;
}
}
}
/// <summary>
/// Helper class that reads font data from embedded resources.
/// </summary>
public static class FontHelper
{
public static byte[] Arial
{
get { return LoadFontData("MyProject.fonts.arial.arial.ttf"); }
}
public static byte[] ArialBold
{
get { return LoadFontData("MyProject.fonts.arial.arialbd.ttf"); }
}
public static byte[] ArialItalic
{
get { return LoadFontData("MyProject.fonts.arial.ariali.ttf"); }
}
public static byte[] ArialBoldItalic
{
get { return LoadFontData("MyProject.fonts.arial.arialbi.ttf"); }
}
/// <summary>
/// Returns the specified font from an embedded resource.
/// </summary>
static byte[] LoadFontData(string name)
{
var assembly = Assembly.GetExecutingAssembly();
// Test code to find the names of embedded fonts
//var ourResources = assembly.GetManifestResourceNames();
using (Stream stream = assembly.GetManifestResourceStream(name))
{
if (stream == null)
throw new ArgumentException("No resource with name " + name);
int count = (int)stream.Length;
byte[] data = new byte[count];
stream.Read(data, 0, count);
return data;
}
}
}
This is a single, complete and working class based on these two almost identical posts: this blog and this forum.
Use the latest version of PDFsharp (currently 1.50 beta 3) and implement IFontResolver.
See also:
https://stackoverflow.com/a/32489271/162529
https://stackoverflow.com/a/29059207/162529
The font may be installed on the server, but PDFsharp cannot read it.

How to Save an Image from Nokia Imaging SDK

I am having issues with some sample code that I am using from one of Nokia's Imaging SDK samples they provide. Essentially I am trying to save an image to IsolatedStorage. The code that I am reusing has been used successfully elsewhere in the solution, but when I try to use it there are no errors but it does not proceed with the following statements. Essentially in the StorePhoto method, once IBuffer buffer = await App.PhotoModel.RenderFullBufferAsync(); is called no error occurs but no code below that which is actually performs the save to isolated storage operation is ran, so no image is ever saved.
SavePage.xaml.cs
private static string _photoModelPath = #"\Lockscreen\v1\PhotoModel";
private static string _photoModelBufferFilename = #"buffer.data";
public async static void StorePhoto()
{
string _photoModelPath = #"\Lockscreen\v1\LockScreen";
string _photoModelBufferFilename = #"buffer.data";
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!storage.DirectoryExists(_photoModelPath))
{
storage.CreateDirectory(_photoModelPath);
}
if (storage.FileExists(_photoModelPath + #"\" + _photoModelBufferFilename))
{
storage.DeleteFile(_photoModelPath + #"\" + _photoModelBufferFilename);
}
IBuffer buffer = await App.PhotoModel.RenderFullBufferAsync(); //code exiting method with no error
if (buffer != null)
{
IsolatedStorageFileStream originalFile = storage.CreateFile(_photoModelPath + #"\" + _photoModelBufferFilename);
Stream bufferStream = buffer.AsStream();
bufferStream.CopyTo(originalFile);
bufferStream.Flush();
bufferStream.Close();
bufferStream.Dispose();
originalFile.Flush();
originalFile.Close();
originalFile.Dispose();
}
}
}
MainPage.xaml.cs
private async void _saveItem_Click(object sender, EventArgs e)
{
Helpers.SaveHelper.StorePhoto(); //calling the StorePhoto method here
}
PhotoModel.cs (from Nokia Imaging SDK sample)
/// <summary>
/// Renders current image with applied filters to a buffer and returns it.
/// Meant to be used where the filtered image is for example going to be
/// saved to a file.
/// </summary>
/// <returns>Buffer containing the filtered image data</returns>
public async Task<IBuffer> RenderFullBufferAsync()
{
using (BufferImageSource source = new BufferImageSource(_buffer))
using (FilterEffect effect = new FilterEffect(source) { Filters = _components })
using (JpegRenderer renderer = new JpegRenderer(effect))
{
return await renderer.RenderAsync();
}
}
Turns out to solve this I had to put the code that saves the image into the same page that I was originally calling that method, and also it needs to be of type Task so that the async/await will work properly.

NullReferenceException when reading data from local storage

[edit] I want to clarify that the NullReferenceException does not occur within the posted code, but this code somehow gives back null
I'm getting a NullReferenceException when running my application for the first time, and it happens when I access a list as a property. Here is the code:
/// <summary>
/// Gets the list of workouts using Lazy Loading.
/// </summary>
/// <remarks>
/// This is the point of access for Workouts in this Page.
/// </remarks>
public List<WorkoutModel> Workouts
{
get
{
if (workouts == null || !workouts.Any())
{
workouts = JsonFileHelper.LoadWorkouts();
}
return workouts;
}
}
The JsonFileHelper code that is accessed is here:
/// <summary>
/// Retrieves all the workouts from local storage.
/// </summary>
/// <returns>The list of workouts.</returns>
public static List<WorkoutModel> LoadWorkouts()
{
bool couldLoadFile = true;
List<WorkoutModel> workouts = new List<WorkoutModel>();
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile textFile = null;
Task<List<WorkoutModel>> t = Task<List<WorkoutModel>>.Run(() => LoadWorkoutsAsync(textFile, localFolder, couldLoadFile));
t.Wait();
workouts = t.Result;
return workouts;
}
Which calls this method on a background thread:
private static async Task<List<WorkoutModel>> LoadWorkoutsAsync(StorageFile textFile, StorageFolder localFolder, bool couldLoadFile)
{
List<WorkoutModel> workouts = new List<WorkoutModel>();
if (localFolder != null)
{
try
{
textFile = await localFolder.GetFileAsync(AppResources.FileName);
}
catch (FileNotFoundException)
{
couldLoadFile = false;
}
if (couldLoadFile)
{
// Create and use a stream to the file atomically
using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
{
// Read the text stream atomically
using (DataReader textReader = new DataReader(textStream))
{
uint length = (uint)textStream.Size;
await textReader.LoadAsync(length);
string data = textReader.ReadString(length);
workouts = JsonConvert.DeserializeObject<List<WorkoutModel>>(data);
}
}
}
}
return workouts;
}
I've noticed that when debugging, the application does not crash - this leads me to believe there is some issue with synchronization going on, because it crashes when the application is run normally. This is my first foray into to asynchronous code, so there's probably something I'm missing.
What could be causing this problem?
Please read the John Saunders question. You need this knowledge, and you should have already found it before posting here.
The code needs to be restructured with variables set predictably on all paths. It's not surprising if you get errors of this kind as it is.
An exception other than FileNotFoundException will leave couldLoadFile as true and textFile as null, triggering this error. This could be your bug.
If this is not enough, then please provide the stack trace.
Instead of using Task.Wait you should try Task.Result.
///
/// Retrieves all the workouts from local storage.
///
/// The list of workouts.
public static List<WorkoutModel> LoadWorkouts()
{
bool couldLoadFile = true;
List<WorkoutModel> workouts = new List<WorkoutModel>();
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile textFile = null;
List<WorkoutModel> workouts = Task<List<WorkoutModel>>.Run(() => LoadWorkoutsAsync(textFile, localFolder, couldLoadFile)).Result;
return workouts;
}

Call mobile detection class method in ASP.NET app_code folder

Summary
I have an ASP.NET 3.5 website and a mobile detection method inside a C# class file inside my app_code folder. I want to call this method which sets a cookie, then switch my master page file if it's a mobile device.
I'm using a method i got from the comment section down in this article: http://www.codeproject.com/Articles/34422/Detecting-a-mobile-browser-in-ASP-NET
This just seemed simpler than using the 51degrees method of detection since i didn't really need a high level of detection, and i didn't want to send them to a different URL, but rather just flip to a different masterpage, and the NuGet package which makes a nice easy install doesn't work for ASP.NET 3.5.
The problem i'm at currently is with calling the method.
Here's the Code
External app_code class
public static class fooBar // test method
{
public static bool ean()
{
return true;
}
}
public static class HttpRequestExt
{
#region Private Fields
// These regular expressions retrieved from http://detectmobilebrowser.com/ "Open source mobile phone detection".
private static Regex MobileBrowsers = new Regex(#"android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|symbian|treo|up\\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);
private static Regex MobileApps = new Regex(#"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|e\\-|e\\/|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\\-|2|g)|yas\\-|your|zeto|zte\\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);
#endregion
public const string ViewMobileSiteCookieName = "ViewMobile";
/// <summary>
/// Determines if the request emanated from a mobile-device client;
/// and stores the result in a cookie on the response.
/// </summary>
/// <param name="request"></param>
/// <param name="Response"></param>
/// <returns></returns>
///
public static bool IsMobileClient(this System.Web.HttpRequest request, System.Web.HttpRequest Response)
{
bool isMobile = false;
bool isCookieSet = false;
var viewMobileCookie = request.Cookies[ViewMobileSiteCookieName];
if (viewMobileCookie != null && bool.TryParse(viewMobileCookie.Value, out isMobile))
{
isCookieSet = true;
}
else if (request.Browser.IsMobileDevice)
{
isMobile = true;
}
else if (request.ServerVariables["HTTP_X_WAP_PROFILE"].IsNotEmpty())
{
isMobile = true;
}
else if
(
request.ServerVariables["HTTP_ACCEPT"].IsNotEmpty()
&&
(
request.ServerVariables["HTTP_ACCEPT"].ToLower().Contains("wap")
|| request.ServerVariables["HTTP_ACCEPT"].ToLower().Contains("wml+xml")
)
)
{
isMobile = true;
}
else if (request.ServerVariables["HTTP_USER_AGENT"].IsNotEmpty())
{
string userAgent = request.ServerVariables["HTTP_USER_AGENT"];
isMobile = ((MobileBrowsers.IsMatch(userAgent) || MobileApps.IsMatch(userAgent.Substring(0, 4))));
}
// Store the result as a cookie.
if (!isCookieSet)
Response.Cookies.Add(new HttpCookie(ViewMobileSiteCookieName, isMobile.ToString()));
return isMobile;
}
public static bool IsNotEmpty(this string instance)
{
return instance != null && instance.Length > 0;
}
}
My call to it)
Right now im doing it on the page, but i figure i'll do this in global.asax on session start?
sectionTitle.InnerHtml = fooBar.ean().ToString(); // test works
sectionTitle.InnerHtml = HttpRequestExt.IsMobileClient.ToString(); // compile error
Compile Error:
CS0119: 'SWIC.HttpRequestExt.IsMobileClient(System.Web.HttpRequest, System.Web.HttpRequest)' is a 'method', which is not valid in the given context
Do i have to somehow cast this to the current instance? Should i just be doing this differently all together?
You're trying to call a method like a property. Methods need parentheses:
HttpRequestExt.IsMobileClient().ToString()
^^
You'll also have to call it on the current request, not just statically, as it is an extension method (which takes a parameter). E.g.:
sectionTitle.InnerHtml = Page.Request.IsMobileClient(Page.Response).ToString();

Categories

Resources