(Newbie question).
I am attempting to list out the PrintQueues from the Microsoft PrintQueColletion in F#. Something like this:
let GetPrinters :List<PrintQueue> =
let localPrintServer = new PrintServer()
let printQueues = localPrintServer.GetPrintQueues [|EnumeratedPrintQueueTypes.Local; EnumeratedPrintQueueTypes.Connections|]
let printerList = printQueues |> ????
printerList
But I can't get how to turn the PrintQueueCollection into a list of PrintQueue.
Any suggestions will be most appreciated.
TIA
Hint: in C#, this is:
public static List<PrintQueue> GetPrinters()
{
PrintServer localPrintServer = new PrintServer();
PrintQueueCollection printQueues = localPrintServer.GetPrintQueues(new[] {
EnumeratedPrintQueueTypes.Local,
EnumeratedPrintQueueTypes.Connections });
var printerList = (from printer in printQueues
select printer)
.ToList();
return printerList;
}
UPDATE: See improved answer below this one.
This should do it:
let printerList =
printQueues
|> Seq.cast<PrintQueue>
|> Seq.toList
The trick here is that if you want printQueues to behave like an IEnumerable<PrintQueue>, you have to explicitly wrap it. This is what Seq.cast does.
(Side note: This is just one reason why having weakly-typed FooCollection classes instead of using built-in strongly-typed collections is a bad idea in general. Such is the legacy of old C# code.)
My first answer isn't technically correct, so I want to fix it here to make sure you see the update. It turns out that you don't need an explicit cast in this case, so the following simpler code will also work:
let printerList =
printQueues
|> Seq.toList
The rest of my explanation in the previous answer is correct for handling weakly-typed collections, but PrintQueueCollection is actually a strongly-typed IEnumerable<PrintQueue>, so it works just fine with the Seq module as it is. Sorry about that.
As it's stated in the upgrade guide, Effects is being replaced by this new Applicative Functor-like thing Cmd. I don't see any trace of a clue as to where Effects.tick might be hiding, or how it could be reimplemented.
From the looks of things, Process.sleep might be the right answer, something like
Task.perform errorHandler (\x -> x) <| Process.sleep
<| 500 * Time.millisecond
would allow the process to wait 500 milliseconds before issuing the next message / action. I'm just not sure if this is what will replace Effects.tick in the long run though.
Effect.tick functionality is replaced by AnimationFrame.
You basically subscribe to a set of msg of either times or diffs. And react accordingly.
import Html exposing (..)
import Html.App as App
import AnimationFrame
import Time exposing (Time, second)
main =
App.program
{ init = Model 0 0 ! []
, update = \msg model -> update msg model ! []
, view = view
, subscriptions = \_ -> AnimationFrame.diffs identity}
type alias Model =
{ timeSinceLastIncrement : Time
, counter : Int }
incrementTime = 1*second
update diff {timeSinceLastIncrement, counter} =
if timeSinceLastIncrement > incrementTime then
Model 0 (counter+1)
else
Model (timeSinceLastIncrement+diff) counter
view {counter} =
div [] [text (toString counter)]
I've chosen to send the Time diffs directly as messages and to unpack the structure of the model in both update and view for easier access to components. In a more complex app you will probably have something like a Tick Time message.
I have a problem to close a program in Erlang. I use wxWidgets.
-module(g).
-compile(export_all).
-define(height, 500).
-define(width, 500).
-include_lib("wx/include/wx.hrl").
-define(EXIT,?wxID_EXIT).
init() ->
start().
start() ->
Wx = wx:new(),
Frame = wxFrame:new(Wx, -1, "Line", [{size, {?height, ?width}}]),
setup(Frame),
wxFrame:show(Frame),
loop(Frame).
setup(Frame) ->
menuBar(Frame),
wxFrame:connect(Frame, close_window).
menuBar(Frame) ->
MenuBar = wxMenuBar:new(),
File = wxMenu:new(),
wxMenuBar:append(MenuBar,File,"&Fichier"),
wxFrame:setMenuBar(Frame,MenuBar),
Quit = wxMenuItem:new ([{id,400},{text, "&Quit"}]),
wxMenu:append (File, Quit).
loop(Frame) ->
receive
#wx{event=#wxCommand{type=close_window}} ->
io:format("quit icon"),
wxWindow:close(Frame,[]);
#wx{id=?EXIT, event=#wxCommand{type=command_menu_selected}} ->
io:format("quit file menu"),
wxWindow:close(Frame,[])
end.
But the program doesn't close; neither the quit icon or Quit from the menu do anything.
You're almost there, but there's a few mistakes.
First, there's never any event being generated for your quit selection on your mention, you need to use connect again, like this:
Quit = wxMenuItem:new ([{id,400},{text, "&Quit"}]),
wxFrame:connect(Frame, command_menu_selected),
Now you have an event for each of the quit methods, but neither of them is working still.
The event for your quit icon isn't matching because you have the wrong event type in your pattern match, and the event for the menu quit selection isn't matching because you're looking for an ID of ?EXIT, which is defined as ?wxID_EDIT, which is defined as.. well clearly not 400, the ID you used when you created your quit menu item. So your receive clause needs to be changed to something like this:
receive
#wx{event=#wxClose{type=close_window}} ->
io:format("quit icon"),
wxFrame:destroy(Frame);
#wx{id=400, event=#wxCommand{type=command_menu_selected}} ->
io:format("quit file menu"),
wxFrame:destroy(Frame)
end.
In addition to Michael's answer regarding using connect/3 to listen for menu commands, nearly any frame will require a few standard event connections to behave the way you expect them to on closing in addition to whatever specific things you have going on. Note that this is connecting to the close_window event and using the option {skip, true}. This is so the signal doesn't stop propagating before it hits the part of Wx that will handle it the way you expect (one click to close) instead of requiring two clicks to close the frame on some platforms.
The basic skeleton often looks like this:
init(Args) ->
Wx = wx:new(),
Frame = wxFrame:new(Wx, ?wxID_ANY, ""),
% Generate whatever state the process represents
State = some_state_initializer(Args),
% Go through the steps to create your widget layout, etc.
WidgetReferences = make_ui(Frame),
% The standardish connects nearly any frame will need.
ok = wxFrame:connect(Frame, close_window, [{skip, true}]),
ok = wxFrame:connect(Frame, command_button_clicked),
ok = wxFrame:connect(Frame, command_menu_selected),
% Add more connects here depending on what you need.
% Adjust the frame size and location, if necessary
Pos = initial_position(Args),
Size = initial_size(Args),
ok = wxFrame:move(Frame, Pos),
ok = wxFrame:setSize(Frame, Size),
wxFrame:show(Frame),
% Optional step to add this frame to a UI state manager if you're
% writing a multi-window application.
ok = gui_manager:add_live(self()),
% Required return for wx_object behavior
{Frame, State}.
Digressing a bit from the original, but strongly related...
Many wxWidgets application have something very similar to this, customized as necessary not by writing all that out again, but by defining your own callback module and passing it in as an argument:
init({Mod, Args}) ->
% ...
PartialState = blank_state([{mod, Mod}, {frame, Frame}, {wx, Wx}]),
State = Mod:finalize(PartialState, Args),
Where blank_state/1 accepts a proplist and returns whatever the actual data structure will be later (usually a record at this level, that looks something like #s{mod, frame, wx, widgets, data}), and Mod:finalize/2 takes the incomplete state and the initial args and returns a completed GUI frame plus whatever program state it is supposed to manage -- in particular the widgets data structure that carries references to any GUI elements you will need to listen for, match on, or manipulate later.
Later on you have some very basic generic handlers all frames might need to deal with, and pass any other messages through to the specific Mod:
handle_call(Message, From, State = #s{mod = Mod}) ->
Mod:handle_call(Message, From, State).
handle_cast(blit, State) ->
{ok, NewState} = do_blit(State),
{noreply, NewState};
handle_cast(show, State) ->
ok = do_show(State),
{noreply, State};
handle_cast(Message, State = #s{mod = Mod}) ->
Mod:handle_cast(Message, State).
In this case do_blit/1 winds up calling Mod:blit/1 in the callback module which rebuilds and refreshes the GUI, rebuilding it from zero by calling a function that does that within wx:batch/1 to make it appear instant to the user:
blit(State) ->
wx:batch(fun() -> freshen_ui(State) end).
If you have a lot of elements to change in the GUI at once, blitting is far smoother and faster from the user's perspective than incrementally shuffling things around or hiding/showing elements as you go -- and is much more certain to feel the same across platforms and various computer speeds and userland loads (some Wx backends give a lot of flicker or intermediate display weirdness otherwise).
The do_show/1 function usually looks something like
do_show(#s{frame = Frame}) ->
ok = wxFrame:raise(Frame),
wxFrame:requestUserAttention(Frame).
(I have been meaning to write a basic "here is one way to structure a multi-window wxErlang application" tutorial/example but just haven't gotten around to it, so a lot of details are missing here but you'll stumble on them on your own after writing a couple of programs.)
I'd like to get the keyboard input of a user in Websharper for an entire page (or whatever gets me closest), and I can't see any nice way of doing this.
I've attempted something along the lines of
JQuery.Of("document").Keyup(fun _ _ -> Window.Self.Alert("boo"))
But I keep running into a lot of NotImplementedExceptions. Are these really not implemented? Or am I hitting some weird edge case because I'm going against the grain?
Update:
I've got version 2.4.85.235 installed from nuget, if that means anything to anyone. I'm also using VS 2012.
I've also tested with a fresh sitelets templated site from VS 2010, and I see the same thing. I've installed the latest package from the WebSharper site.
Make sure that you're not calling client-side methods that are not implemented on the server. If that's the case separate client and server code, display the involved elements and invoke the JavaScript through the Web Control mechanism and use "html", "body" or Dom.Document.Current as a selector. Below is a sample for displaying an alert every time the enter key is pressed:
module Client =
open IntelliFactory.WebSharper
open IntelliFactory.WebSharper.Html
open IntelliFactory.WebSharper.JQuery
[<JavaScriptAttribute>]
let paragraph () =
P [Text "Press the Enter key to display an alert box."]
|>! OnAfterRender (fun x ->
JQuery.Of("html").Keydown(fun _ event ->
match event.Which with
| 13 -> JavaScript.Alert "Enter key was pressed."
| _ -> ()).Ignore)
type ParagraphViewer () =
inherit Web.Control()
[<JavaScript>]
override this.Body = paragraph () :> _
I want to ask a simple question how to stop this timer.
Somebody's code is like this :
let mutable timer = new DispatcherTimer()
timer.Interval - new TimeSpan(0,0,0,0,100)
timer.Start()
and I want to add a function that cause the timer to stop whenever I click button
So I put a code like this (I don't really have a clue) :
btnStop.Click
|> Event.add(fun args -> timer.Stop())
but it says that it cannot be captured by closure
any idea how to do this?
sorry. I am not an experienced functional programmer. I just want to modify a code.
Is there a reason to make the timer mutable? If you're never assigning a new value to it, then you can just drop mutable and it should work.
Otherwise, you'll need to use a reference cell instead of a normal mutable binding:
let timer = ref (new DispatcherTimer())
(!timer).Interval <- new TimeSpan(0,0,0,0,100)
(!timer).Start()
btnStop.Click
|> Event.add(fun args -> (!timer).Stop())