using System.Windows;
using System.Windows.Input;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using WindowsPhoneApp; // For the Setting class
namespace Tally
{
public partial class MainPage : PhoneApplicationPage
{
int count = 0;
// Remember what the user typed, for future app activations or launches
Setting<int> savedCount = new Setting<int>(“SavedCount”, 0);
public MainPage()
{
InitializeComponent();
}
// Handle a tap anywhere on the page (other than the Button)
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
this.count++;
this.CountTextBlock.Text = this.count.ToString(“N0”);
}
// Handle a tap on the button
void ResetButton_Click(object sender, RoutedEventArgs e)
{
this.count = 0;
this.CountTextBlock.Text = this.count.ToString(“N0”);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
// Persist state when leaving for any reason (Deactivated or Closing)
this.savedCount.Value = this.count;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
// Restore persisted state
this.count = this.savedCount.Value;
this.CountTextBlock.Text = this.count.ToString(“N0”);
}
}
}
I am not a C# coder..i use VB.net...anyway i tried converting it using an online conversion tool...but the vb code is full of errors.Can anyone help me with this??I have just started learning Windows Phone 7.
What namespace should be imported in VB for using WindowsPhoneApp;??
http://forums.create.msdn.com/forums/p/82711/514488.aspx
The chapter 1 app (like almost every app in the book) uses a Settings class to interact with isolated storage. This way, it can remember values the next time the app runs. In the code download for the book, the project includes the necessary Settings.cs class which makes this error go away. The code for this class is also included in the book in Chapter 20, when the topic of isolated storage is discussed.
So you've got two options:
1.Copy Settings.cs from the Chapter 1 code download and include it in your project.
2.Create a new Settings.cs file in your project and type in the Settings.cs code from Chapter 20.
There is a bullet point in Chapter 1 that attempts to explain the situation, but I realize that it is too confusing.
Try this online converter
I have tried the converter and this is the converted result:
Imports System.Windows
Imports System.Windows.Input
Imports System.Windows.Navigation
Imports Microsoft.Phone.Controls
Imports WindowsPhoneApp
' For the Setting class
Namespace Tally
Public Partial Class MainPage
Inherits PhoneApplicationPage
Private count As Integer = 0
' Remember what the user typed, for future app activations or launches
Private savedCount As New Setting(Of Integer)(SavedCount, 0)
Public Sub New()
InitializeComponent()
End Sub
' Handle a tap anywhere on the page (other than the Button)
Protected Overrides Sub OnMouseLeftButtonDown(e As MouseButtonEventArgs)
MyBase.OnMouseLeftButtonDown(e)
Me.count += 1
Me.CountTextBlock.Text = Me.count.ToString(N0)
End Sub
' Handle a tap on the button
Private Sub ResetButton_Click(sender As Object, e As RoutedEventArgs)
Me.count = 0
Me.CountTextBlock.Text = Me.count.ToString(N0)
End Sub
Protected Overrides Sub OnNavigatedFrom(e As NavigationEventArgs)
MyBase.OnNavigatedFrom(e)
' Persist state when leaving for any reason (Deactivated or Closing)
Me.savedCount.Value = Me.count
End Sub
Protected Overrides Sub OnNavigatedTo(e As NavigationEventArgs)
MyBase.OnNavigatedTo(e)
' Restore persisted state
Me.count = Me.savedCount.Value
Me.CountTextBlock.Text = Me.count.ToString(N0)
End Sub
End Class
End Namespace
Related
I need to dynamically creates controllers in a ASP.NET Core 6 MVC application.
I found some way to somewhat achieve this but not quite.
I'm able to dynamically add my controller but somehow it reflects only on the second request.
So here is what I do: first I initialize my console app as follows:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc.Infrastructure;
namespace DynamicControllerServer
{
internal class Program
{
static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
ApplicationPartManager partManager = builder.Services.AddMvc().PartManager;
// Store thePartManager in my Middleware to be able to add controlelr after initialization is done
MyMiddleware._partManager = partManager;
// Register controller change event
builder.Services.AddSingleton<IActionDescriptorChangeProvider>(MyActionDescriptorChangeProvider.Instance);
builder.Services.AddSingleton(MyActionDescriptorChangeProvider.Instance);
var app = builder.Build();
app.UseAuthorization();
app.MapControllers();
// Add Middleware which is responsible to cactn the request and dynamically add the missing controller
app.UseMiddleware<MyMiddleware>();
app.RunAsync();
Console.WriteLine("Server has been started successfully ...");
Console.ReadLine();
}
}
}
Then my middleware looks like this: it basically detects that there is the "dynamic" keyword in the url. If so, it will load the assembly containing the DynamicController:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using System;
using System.Reflection;
namespace DynamicControllerServer
{
public class MyMiddleware
{
public RequestDelegate _next { get; }
private string dllName = "DynamicController1.dll";
static public ApplicationPartManager _partManager = null;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
if (httpContext.Request.Path.HasValue)
{
var queryParams = httpContext.Request.Path.Value;
if(httpContext.Request.Path.Value.Contains("api/dynamic"))
{
// Dynamically load assembly
Assembly assembly = assembly = Assembly.LoadFrom(#"C:\Temp\" + dllName);
// Add controller to the application
AssemblyPart _part = new AssemblyPart(assembly);
_partManager.ApplicationParts.Add(_part);
// Notify change
MyActionDescriptorChangeProvider.Instance.HasChanged = true;
MyActionDescriptorChangeProvider.Instance.TokenSource.Cancel();
}
}
await _next(httpContext); // calling next middleware
}
}
}
The ActionDescriptorChange provider looks like this:
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Primitives;
namespace DynamicControllerServer
{
public class MyActionDescriptorChangeProvider : IActionDescriptorChangeProvider
{
public static MyActionDescriptorChangeProvider Instance { get; } = new MyActionDescriptorChangeProvider();
public CancellationTokenSource TokenSource { get; private set; }
public bool HasChanged { get; set; }
public IChangeToken GetChangeToken()
{
TokenSource = new CancellationTokenSource();
return new CancellationChangeToken(TokenSource.Token);
}
}
}
Dynamic controller is in separate dll and is very simple:
using Microsoft.AspNetCore.Mvc;
namespace DotNotSelfHostedOwin
{
[Route("api/[controller]")]
[ApiController]
public class DynamicController : ControllerBase
{
public string[] Get()
{
return new string[] { "dynamic1", "dynamic1", DateTime.Now.ToString() };
}
}
}
Here are the packages used in that project:
<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
This works "almost" fine ... when first request is made to:
https://localhost:5001/api/dynamic
then it goes in the middleware and load the assembly, but returns a 404 error.
Then second request will actually work as expected:
Second request returns the expected result:
I must doing it wrong and probably my middleware is executed too late in the flow to reflect the dynamic controller right away.
Question is: what should be the proper way to achieve this?
Second question I have is say now the external dll holding our dynamic controller is updated.
How can I reload that controller to get the new definition?
Any help would be appreciated
Thanks in advance
Nick
Here is the answer to my own question in case it can help somebody out there.
It seems building and loading the controller from the middleware will always end up with failure on the first call.
This makes sense since we are already in the http pipeline.
I end up doing same thing from outside the middleware.
Basically my application detect a change in the controller assembly, unload the original assembly and load the new one.
You cannot use the Default context since it will not allow reloading different dll for same assembly:
var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath); // Produce an exception on updates
To be able to reload new dll for same assembly, I’m loading each controller in its own assembly context. To do that you need to create your own class deriving from AssemblyLoadContext and managing assembly load:
public class MyOwnContext: AssemblyLoadContext
{
// You can find lots of example in the net
}
When you want to unload the assembly, you just unload the context:
MyOwnContextObj.Unload();
Now to add or remove the controller on the fly, you need to keep reference of the PartManager and the ApplicationPart.
To add controller
ApplicationPart part = new AssemblyPart(assembly);
_PartManager.ApplicationParts.Add(part);
To remove:
_PartManager.ApplicationParts.Remove(part);
On course once done, still use following piece of code to acknowledge the change:
MyActionDescriptorChangeProvider.Instance.HasChanged = true;
MyActionDescriptorChangeProvider.Instance.TokenSource.Cancel();
That allow updating controller on the fly with no interruption of service.
Hope this helps people out there.
I have done a similar solution (used for managing a web app plugins) with some differences that may help you:
List all the external assemblies in a config file or appsettings.json so all the dll names and/or addresses are known at startup
Instead of registering controllers when they are called, register them at program.cs/start up :
//Foreah dllName from settings file
var assembly = Assembly.LoadFrom(#"Base address" + dllNameLoadedFromSettings);
var part = new AssemblyPart(assembly);
services.AddControllersWithViews()
.ConfigureApplicationPartManager(apm => apm.ApplicationParts.Add(part));
// Any other configuration based on the usage you want
Second: I usually keep plugin dlls in the bin folder so when using IIS as soon as a dll file in bin is changed the upper-level app is automatically reset. So your second question would be solved too.
I am trying to write my own "Application_Error" for my site.
I need to catch 404's (to see what mistakes users are making) & 500's to catch my programming errors. I did this succesfully in my site before I started using Umbraco in the global.asax.
I have tried the following method.
1: I created a class MyGlobal (file MyGlobal.vb in the App_Code directory:
Public Class MyGlobal
Inherits umbraco.Web.UmbracoApplication
Protected Overloads Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Dim ctx As HttpContext = HttpContext.Current
ctx.Response.Redirect("http://wwww.google.com")
End Sub
End Class
Obivously, this is only to test.
In addition, I editeted my Global.asax file and now it looks like this:
<%# Application Language="VB" Inherits="MyGlobal" %>
<script runat="server">
</script>
I already have:
<customErrors mode="Off" />
&
<httpErrors existingResponse="PassThrough"/>
in my web.config.
1: When I try to enter a non-existent page, i get the Umbraco 404 error page.
2: When I purposely create a 500 error, the system shows me the error page and does not redirect to Google.
Please help as I can not go live without this.
Thanks.
Yoni
Edit:
As I am working in VB, I have used this:
Imports Microsoft.VisualBasic
Imports Umbraco.Core
Public Class MyCustomEvent1
Inherits ApplicationEventHandler
Protected Overrides Sub ApplicationStarted(umbracoApplication As UmbracoApplicationBase, applicationContext As ApplicationContext)
AddHandler umbracoApplication.[Error], AddressOf umbracoApplication_Error
End Sub
Private Sub umbracoApplication_Error(sender As Object, e As EventArgs)
Dim x As HttpContext = HttpContext.Current
x.Response.Redirect("http://www.espn.com")
' Do your stuff
End Sub
End Class
It is not firing when I try either a 404 or a 500 error.
(If I put a redirect in the upper section, i get an error that "System.Web.HttpException: Response is not available in this context.")
Can you help?
Thanks
Concerning 404's, you should look at the package 301 URL Tracker. This is an amazing free package tracking all 404's. While doing that it also tracks all renames of nodes, when a node has been renamed, it also creates a redirect to the new url. Of cource you can also create your own redirects using urls from a previous site or using regex.
Writing your own global asax is not best practice when you use Umbraco, because umbraco uses a lot of things at startup itself. Instead you can hook into the ApplicationEventHandler events to register your custom code at startup. The only thing to activate the handlers is implementing the ApplicationEventHandler class. All classes derived from this class will be called at the umbraco boot-up.
The UmbracoApplicationBase class is derived from the HttpApplication. You can hook into the Error event of this class to implement your own error handler logic.
public class MyCustomEvent1 : ApplicationEventHandler
{
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
umbracoApplication.Error += umbracoApplication_Error;
// very bad example
// Response.Redirect("http://google.com")
}
void umbracoApplication_Error(object sender, EventArgs e)
{
// Do your stuff
}
}
EDIT
If you need to create your own "404 not found" pipeline you should create an IContentFinder (see documentation). The example below comes from this PDF: http://www.zpqrtbnk.net/CoreInternalsForWebsiteDevelopment.pdf and this session from Stéphane Gay presented at Codegarden.
public class My404ContentFinder : IContentFinder
{
public bool TryFindContent(PublishedContentRequest contentRequest)
{
if (!contentRequest.HasDomain)
return false;
var contentCache = contentRequest.RoutingContext.UmbracoContext.ContentCache;
var domainRoot = contentCache.GetById(contentRequest.Domain.RootNodeId);
var firstSegment = contentRequest.Uri.AbsolutePath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).First();
var root = domainRoot.Children.FirstOrDefault(x => x.UrlName == firstSegment);
root = root ?? domainRoot.Children.First();
var page = root.Descendants().FirstOrDefault(x => x.Name == "404");
if (page == null) return false;
contentRequest.PublishedContent = page;
var wcd = Domain.GetDomainsById(root.Id, true).SingleOrDefault(x => x.IsWildcard);
if (wcd != null) contentRequest.Culture = new CultureInfo(wcd.Language.CultureAlias);
return true;
}
}
I have been following lot of posts & threads based on which have integrated
the logic to skip scenarios. Still not able to get it working successfully.
When i put the
"configuredEmbedder().useMetaFilters(Arrays.asList("-skip"));"
OR
"configuredEmbedder().useMetaFilters(Arrays.asList("+skip"));"
in the storyrunner,java file, none of the scenarios are executed.
And when I remove the line, all the scenarios are executed.
My .story file has "Meta skip" in 2 of the 4 scenarios.
Can someone please look into this & let me know what I may have missed.
Below is the class where all the configs reside
public class SampleStory extends JUnitStory {
public SampleStory() {
configuredEmbedder().embedderControls()
.doGenerateViewAfterStories(true)
.doIgnoreFailureInStories(false).doIgnoreFailureInView(true)
.useStoryTimeoutInSecs(60);
configuredEmbedder().useMetaFilters(Arrays.asList("+skip"));
/* removeStartIgnoreCase */
// StringUtils.removeStartIgnoreCase("","");
}
#Override
public Configuration configuration() {
Configuration configuration = new MostUsefulConfiguration();
Properties viewResources = new Properties();
viewResources.put("decorateNonHtml", "true");
viewResources.put("reports", "ftl/jbehave-reports-with-totals.ftl");
// Where to find the stories
StoryLoader storyLoader;
storyLoader = new LoadFromRelativeFile(
CodeLocations.codeLocationFromClass(this.getClass()));
configuration.useStoryLoader(storyLoader);
StoryReporterBuilder storyReporterBuilder;
storyReporterBuilder = new StoryReporterBuilder();
// storyReporterBuilder.withDefaultFormats();
storyReporterBuilder.withDefaultFormats();
// storyReporterBuilder.withViewResources(viewResources).withFormats(CONSOLE,
// TXT, HTML, XML);
// storyReporterBuilder.withFormats();
// CONSOLE reporting
configuration.useStoryReporterBuilder(storyReporterBuilder);
return configuration;
}
/*
* #Override public Embedder configuredEmbedder() {
* super.configuredEmbedder().useMetaFilters(Arrays.asList("-skip"));
*
*
* return super.configuredEmbedder(); }
*/
#Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration(), new SampleSteps());
}
Snenairo.story
Scenario: This is scenario 1
Given I say hello
When I say bye
Then whatever
Scenario: This is scenario 2
Meta : #skip
Given I say ello
When I say ye
Then whatever
There is another class where all the binding menthods for g/w/t exists.
Got an reply from the group of the devs of jbehave - there was a syntax error
i did
meta: #skip
but it should have been
meta : #skip
I used #ignore like this in my jbehave scenario and it worked.
Scenario: Employee1 - Delete Employees
Meta:
#ignore
I have developed an application. I want to display a message before the user starts implementing my application. Like when it is used first time i want to show "Count = 1". And when app is visited second time, "Count = 2".
How can i achieve it? I had done such thing in android using sharedperferences. But how can i do it in blackberry. I had tried something with PersistentStore. But cant achieve that, for i dont know anything about the Persistance in BB.
Also i would wish to restrict the use for 100. Is it possible?
sample codes for this will be appreciable, since i am new to this environment..
You can achieve it with Persistent Storage.
Check this nice tutorial about storing persistent data.
Also you can use SQLite. Link to a development guide which describes how to use SQLite databases in Java® applications: Storing data in SQLite databases.
You can restrict user for trying your application at most 100 times using your own logic with the help of persistent data. But I think there may be some convention, so try Google for that.
got it...
I created a new class which implements Persistable. In that class i had created an integer variable and set an getter and setter function for that integer...
import net.rim.device.api.util.Persistable;
public class Persist implements Persistable
{
private int first;
public int getCount()
{
return first;
}
public void setCount()
{
this.first += 1;
}
}
Then in the class which initializes my screen, i had declared persistence variables and 3 functions to use my Persist.java, initStore(), savePersist(), and getPersist()
public final class MyScreen extends MainScreen implements FieldChangeListener
{
/*
* Declaring my variables...
*/
private static PersistentObject store;
public Persist p;
public MyScreen()
{
//my application codes
//here uses persistence
initStore();
p = getPersist();
if(p.getCount()<100)
{
savePersist();
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert(p.getCount.toString());
}
});
}
else
{
close();
System.exit(0);
}
}
//three function....
public static void initStore()
{
store = PersistentStore.getPersistentObject(0x4612d496ef1ecce8L);
}
public void savePersist()
{
synchronized (store)
{
p.setCount();
store.setContents(p);
store.commit();
}
}
public Persist getPersist()
{
Persist p = new Persist();
synchronized(store)
{
p = (Persist)store.getContents();
if(p==null)
{
p = new Persist();
}
}
return p;
}
}
I hope u all will get it right now....
If there are another simple way, plz let me know...
Thanks
I am writing an Excel 2007 Addin. using VS2008 and .net 3.5, C#.
I catched Microsoft.Office.Interop.Excel.Application's WindowActivate and WindowDeActivate events.
It was surprised to know that WindowActivate and Deactivate only triggers when i switch between two Excel Windows. if i switch to notepad, i expect Deactivate to be triggered, but its not happening. same way from notepad if i switch to excel window, i expect Activate to be triggered but its not happening. It looks like the behaviour indicates windows are MDI-Child windows.
Now what i want to do is get HWnd of Excel's Mainwindow and hook Window Activate and Deactivates using dllimport features.
Can anyone guide to me on this.
Regards
I solved similar problem when writing Excel addin. No dll import is needed. I solved this issue using System.Windows.Forms.NativeWindow class.
At first, I made my own class inherited from NativeWindow class and declared two events Activated and Deactivate in it and finaly overrided WndProc() method to rise these events when message WM_ACTIVATE is passed to the WndProc method. According to "Message" parameter WParm is Excel window activated or deactivated.
public class ExcelWindow: NativeWindow
{
public const int WM_ACTIVATED = 0x0006;
public ExcelWindow():base(){}
//events
public event EventHandler Activated;
public event EventHandler Deactivate;
//catching windows messages
protected override void WndProc(ref Message m)
{
if (m.Msg== WM_ACTIVATED)
{
if (m.WParam.ToInt32() == 1)
{
//raise activated event
if (Activated!=null)
{
Activated(this, new EventArgs());
}
}
else if (m.WParam.ToInt32() == 0)
{
//raise deactivated event
if (Deactivate!=null)
{
Deactivate(this, new EventArgs());
}
}
}
base.WndProc(ref m);
}
}
Then I made in my addin class field "ExcelWindow myExcelWindow" and added following code to OnConnection method of my addin:
ExcelWindow myExcelWindow;
void Extensibility.IDTExtensibility2.OnConnection(object application, Extensibility.ext_ConnectMode ConnectMode, object AddInInst, ref Array custom)
{
excel = application as Excel.Application;
myExcelWindow = new ExcelWindow();
myExcelWindow.AssignHandle(new IntPtr(excel.Hwnd));
myExcelWindow.Activated += new EventHandler(myExcelWindow_Activated);
myExcelWindow.Deactivate += new EventHandler(myExcelWindow_Deactivate);
//addin code here
}
void myExcelWindow_Activated(object sender, EventArgs e)
{
//do some stuff here
}
void myExcelWindow_Deactivate(object sender, EventArgs e)
{
//do some stuff here
}
I hope this will help you.
Finally I found one solution..that works only Activate/Deactivate.
This is not the perfect way to do it. But I did not find any good alternative.
This method uses polling. I have to call following function in each 10 ms interval to check focus in/out.
public static bool ApplicationIsActivated()
{
var activatedHandle = GetForegroundWindow();
if (activatedHandle == IntPtr.Zero)
{
return false; // No window is currently activated
}
var procId = Process.GetCurrentProcess().Id;
int activeProcId;
GetWindowThreadProcessId(activatedHandle, out activeProcId);
return activeProcId == procId;
}