How to set INetFwPolicy2::ExcludedInterfaces property - windows-firewall-api

I implementing basic library to deal with Windows Firewall API.
I faced with strange result with INetFwPolicy2::ExcludedInterfaces property.
I set excluded interface via Firewall.cpl and when read property I got array of some guids. I am not sure from where this GUID come. It is not Interface GUID. I select all interfaces from Win32_NetworkAdapter and there no such GUID.
Also when I try assign this value back I got invalid argument or not found errors.
This code based on msdn example written on on VBS, but it really does not matter I have same error on C. Original example did not works either.
Const NET_FW_PROFILE2_PRIVATE = 2
Set fwPolicy2 = CreateObject("HNetCfg.FwPolicy2")
CurrentProfiles = fwPolicy2.CurrentProfileTypes
if ( CurrentProfiles AND NET_FW_PROFILE2_PRIVATE ) then
InterfaceArray = fwPolicy2.ExcludedInterfaces(NET_FW_PROFILE2_PRIVATE)
if (IsEmpty(InterfaceArray)) then
WScript.Echo( "InterfaceArray is Empty" )
else
WScript.Echo( Join(InterfaceArray) )
end if
fwPolicy2.ExcludedInterfaces(NET_FW_PROFILE2_PRIVATE) = InterfaceArray
end if

Check your csproj file xml in your executing assembly (not necessarily the assembly that uses windows-firewall-api if it is referenced). For each configuration there is a <PropertyGroup> tag, and each should have a child tag <Prefer32Bit>false</Prefer32Bit> (or at least the one that you compile with).

Related

attempt to index global 'INV' (a nil value) (line:23)

print("cl_inv wurde geladen!")
concommand.Add("inv_model", function(ply)
local wep = ply:GetActiveWeapon()
if not IsValid(wep) then return end
print(wep:GetWeaponWorldModel())
end)
net.Receive("inv_init", function()
LocalPlayer().inv = {}
end)
net.Receive("inv_give", function()
local classname = net.ReadString()
table.insert(LocalPlayer().inv, classname)
end)
function INV.Open()
local ply = LocalPlayer()
local plyinv = ply.inv
if not ply.inv then return end
local scrw, scrh = ScrW(),ScrH()
INV.Menu = vgui.Create("DFrame")
local inv = INV.Menu
inv:SetSize(scrw * .4, scrh * .6)
inv:Center()
inv:SetTitle("")
inv:MakePopup()
inv.Paint = function(me,w,h)
surface.SetDrawColor(0,0,0,200)
surface.DrawRect(0,0,w,h)
end
local scroll = inv:Add("DScrollPanel")
scroll:Dock(FILL)
scroll.panels = {}
for k,v in pairs(plyinv) do
local itemPanel = scroll:Add("DPanel")
itemPanel:Dock(TOP)
scroll.panels[itemPanel] = true
end
end
hook.Add( "OnPlayerChat", "InvOpen", function( ply, strText, bTeam, bDead )
if ( ply != LocalPlayer() ) then return end
if string.lower(strText) != "!inv" then return end
INV.Open()
end )
I already searched the whole internet for a solution, i did found something but it didnt really helped me so what im expecting is that someone may be so nice and can help me solve my problem. In line 23 is the error :attempt to index global 'INV' (a nil value) (line:23)
As I can see, you're using the Garry's Mod Lua API. Although this API adds some features to the basic Lua language (e.g. ! operator for negation, C-style comments //), you still need to use the Lua language properly.
What the error says, is that you're trying to access to a table that isn't defined in the current scope of your program.
I can bet your addon defined some global table to interoperate between files and other addons installed on your machine.
As I don't have that much information on the way you're loading your file, here are multiple guesses on possible solutions:
For a file located inside an autorun folder
If the snippet you gave is under an autorun folder, the issue may be that the INV table does not yet exist when you load your file. To correct that, you can use the GLua Timer's Library.
Here is a simple snippet:
Timer.Simple(0.2, function()
-- put your code here
end
Timer.Simple takes two parameters: first one is a delay, in seconds and the other one is a callback function, executed once the delay has ended !
If you're doing something that requires the server to have loaded some other addons before actually running your script, this might be helpfull.
Accessing Global variables of your environment
As you did not gave that many informations about your problem I have to continue to guess what you're trying to do. An other source of problem is maybe that the INV table simply doesn't exist.
How to get all defined global tables in Lua ?
In Lua, there is the _G table that contains all the data of your current environnement. For more in-depth information, please see the official Lua documentation.
To know if your table does in fact exist in your environment, you can run this snippet on your Lua server:
local function doesINVExist()
for name in pairs(_G) do
if (name == "INV") then return true end
end
return false
end
And then you can simply run it using:
print(doesINVExist())
What to do if the table doesn't exist
If INV isn't present in your environment, then it may be because your Garry's Mod server did not loaded any file that defines such a table. Then what you can do is checking the addon that should dclare that table to see if there are any errors that might make it a nil value.
I hope this can help. Of course my answer could've been much more detailed if I had more information. But as I can't write comments (my rating isn't high enough), here is all I can do for you !
Have a great day,
Pedro.

textX: How to generate object names with ObjectProcessors?

I have a simple example model where I would like to generate names for the objects of the Position rule that were not given a name with as <NAME>. This is needed so that I can find them later with the built-in FQN scope provider.
My idea would be to do this in the position_name_generator object processor but that will be only be called after the whole model is parsed. I donĀ“t really understand the reason for that, since by the time I would need a Position object in the Project, the objects are already created, still the object processor will not be called.
Another idea would be to do this in a custom scope provider for Position.location which would then first do the name generation and then use the built-in FQN to find the Location object. Although this would work, I consider this hacky and I would prefer to avoid it.
What would be the textX way of solving this issue?
(Please take into account that this is only a small example. In reality a similar functionality is required for a rather big and complex model. To change this behaviour with the generated names is not possible since it is a requirement.)
import textx
MyLanguage = """
Model
: (locations+=Location)*
(employees+=Employee)*
(positions+=Position)*
(projects+=Project)*
;
Project
: 'project' name=ID
('{'
('use' use=[Position])*
'}')?
;
Position
: 'define' 'position' employee=[Employee|FQN] '->' location=[Location|FQN] ('as' name=ID)?
;
Employee
: 'employee' name=ID
;
Location
: 'location' name=ID
( '{'
(sub_location+=Location)+
'}')?
;
FQN
: ID('.' ID)*
;
Comment:
/\/\/.*$/
;
"""
MyCode = """
location Building
{
location Entrance
location Exit
}
employee Hans
employee Juergen
// Shall be referred to with the given name: "EntranceGuy"
define position Hans->Building.Entrance as EntranceGuy
// Shall be referred to with the autogenerated name: <Employee>"At"<LastLocation>
define position Juergen->Building.Exit
project SecurityProject
{
use EntranceGuy
use JuergenAtExit
}
"""
def position_name_generator(obj):
if "" == obj.name:
obj.name = obj.employee.name + "At" + obj.location.name
def main():
meta_model = textx.metamodel_from_str(MyLanguage)
meta_model.register_scope_providers({
"Position.location": textx.scoping.providers.FQN(),
})
meta_model.register_obj_processors({
"Position": position_name_generator,
})
model = meta_model.model_from_str(MyCode)
assert model, "Could not create model..."
if "__main__" == __name__:
main()
What is the textx way to solve this...
The use case you describe is to define the name of an object based on other model elements, including a reference to other model elements. This is currently not part of any test and use cases included in our test suite and the textx docu.
Object processors are executed at defined stages during model construction (see http://textx.github.io/textX/stable/scoping/#using-the-scope-provider-to-modify-a-model). In the described setup they are executed after reference resolution. Since the name to be defined/deduced itself is required for reference resolution, object processors cannot be used here (even if we allow to control when object processors are executed, before or after scope resolution, the described setup still will not work).
Given the dynamics of model loading (see http://textx.github.io/textX/stable/scoping/#using-the-scope-provider-to-modify-a-model), the solution is located within a scope provider (as you suggested). Here, we allow to control the order of reference resolution, such that references to the object being named by a custom procedure are postponed, until references required to deduce/define the name resolved.
Possible workaround
A preliminary sketch of how your use case can be solved is discussed in a https://github.com/textX/textX/pull/194 (with an attached issue https://github.com/textX/textX/issues/193). This textx PR contains a version of scoping.py you could probably use for your project (just copy and rename the module). A full-fledged solution could be part of the textx TEP-001, where we plan to make scoping more controllable to the end-user.
Playing around with this absolutely interesting issue revealed new aspects to me for the textx framework.
names dependent on model contents (involving unresolved references). This name resolution, which can be Postponed (in the referenced PR, see below), in terms of our reference resolution logic.
Even more interesting are the consequences of that: What happens to references pointing to locations, where unresolved names are found? Here, we must postpone the reference resolution process, because we cannot know if the name might match when resolved...
Your example is included: https://github.com/textX/textX/blob/analysis/issue193/tests/functional/test_scoping/test_name_resolver/test_issue193_auto_name.py

How to fix Glass Mapper error - failed to find configuration for parent item type?

I have a Sitecore 8.1 CD instance. I also have some code that needs to create a content item in the Master database. (I am aware that is a no-no but I just need to figure this out at the moment) When my code attempts to use Glass Mapper to create a content item I get an error. Here is the code snippet and the error message. I am just trying to understand what the error means. I have a sense that this is simply a configuration problem. This code works fine on our Sitecore CM server. So I am hoping that by simply adjusting the config on our CD server I can get this to work. So far I have re-enabled the Master entry in ConnectionStrings.config and in Sitecore.config. But that hasn't fixed this.
SitecoreService service = new SitecoreService("master");
SimpleAes aes = new SimpleAes();
using (new SecurityDisabler())
{
Item parentItem = Factory.GetDatabase("master").GetItem("/sitecore/content/Non Page Content/Account Information/Shipping Addresses");
newAddress = service.Create(parentItem, newAddress); //THIS IS WHERE THE CODE FAILS
user.Addresses.Add(newAddress);
Utility.PublishItem(service.ResolveItem(newAddress));
id = aes.EncryptToString(newAddress.Id.ToString());
user.Addresses = user.Addresses;
user.Save();
}
Error Message:
Glass.Mapper.MapperException: Failed to find configuration for parent
item type Sitecore.Data.Items.Item ---> System.NullReferenceException:
Object reference not set to an instance of an object. at
System.Object.GetType() at
Glass.Mapper.Context.GetTypeConfiguration[T](Object obj, Boolean
doNotLoad, Boolean checkBase) at
Glass.Mapper.Sc.SitecoreService.Create[T,TK](TK parent, T newItem,
Boolean updateStatistics, Boolean silent) --- End of inner exception
stack trace --- at Glass.Mapper.Sc.SitecoreService.Create[T,TK](TK
parent, T newItem, Boolean updateStatistics, Boolean silent)
It is failing on this line
Item parentItem = Factory.GetDatabase("master").GetItem("/sitecore/content/Non Page Content/Account Information/Shipping Addresses");
if you put a check around it saying
if (parentItem != null) { // your code }
Then the code will work through and you will not get exception, but nothing will happen as well if parentItem is null.
Quick fix solution will be to give a 'master' DB connection string on your CD server (which is a no-no as you said). Better solution will be to expose master database through Sitecore Item API or your custom API, securing it through authentication and then calling this code from CD server via API.
I am not sure if you still are looking how to solve this issue, but when I faced today with it I found your question.
Problem is that your parentItem has type Item. It causes issue inside in Glass.
You can use any type as parent, but limitation is that it should not be inherited from Sitecore Item class.
Try this:
var parentItem = Factory.GetDatabase("master").GetItem("/sitecore/content/Non Page Content/Account Information/Shipping Addresses").GlassCast<BaseSitecoreItem>();
newAddress = service.Create(parentItem, newAddress);
where BaseSitecoreItem is some your Glass Model.
It helped me and hope will help you.

Saving JSON data to DB in Zotonic

Im trying to write a small app that retrieves a JSON file (it contains a list of items, which all have some properties), saves its contents to the DB and then displays some of it later on. I have Zotonic up and running, and generating some HTML is no problem.
ATM i'm stuck trying to figure out how to define a custom resource and how to get the data from the JSON in the DB. When the data is there I should be fine, that part seems covered ok by the documentation.
I wrote some standalone erlang scripts that fetch the data and I noticed that Zotonic has a library for decoding JSON so that part should be fine. Any tips on where to put which code or where to look further?
The z_db module allows for creating custom tables by using:
z_db:create_table(Table, Cols, Context).
The Table variable is your table name which can be either an atom or a list containing a single atom.
The Cols is a list of column definitions, which are defined by records. Currently the record definition (you can find this in include/zotonic.hrl) is:
-record(column_def, {name, type, length, is_nullable=true, default, primary_key}).
See Erlang docs on records for more info on records
Example code which I put in users/sites/[sitename]/models/m_[sitename].erl:
init(Context) ->
case z_db:table_exists(?table,Context) of
false ->
z_db:create_table(tablename,
[
#column_def{name=id, type="serial"},
#column_def{name=gid, type="integer", is_nullable=false},
#column_def{name=magnitude, type="real"},
#column_def{name=depth, type="real"},
#column_def{name=location, type="character varying"},
#column_def{name=time, type="integer"},
#column_def{name=date, type="integer"}
], Context);
true -> ok
end,
ok.
Pay attention to what options of the record you specify. Most of the errors I got were e.g. from specifying a length on the integer fields.
The models/m_sitename:init/1 does not get called on site start. The sitename:init/1 does get called so I call the init function there to ensure the table exists. Example:
init(Context) ->
m_sitename:init(Context).
It is called by Zotonic with the Context variable of the site automatically. You can get this variable manually as well with z:c(sitename).. So if you call the m_sitename:init(Context). from somewhere else you would do:
m_sitename:init(z:c(sitename)).
Next, insertion in the DB can be done with:
z_db:insert(Table, PropList, Context).
Where Table is again an atom or a list containing a single atom representing the table name. Context is the same as above.
PropList is a property list which is a list containing tuples consisting of two elements where the first is an atom and the second is its associated value/property. Example:
PropList = [
{row, Value},
{anotherrow, AnotherValue}
].
Table = tablename.
Context = z:c(sitename).
z_db:insert(Table, PropList, Context).
See Erlang docs on Property Lists for more info on property lists.
=== The dependencies have been updated so if you build from source the step directly below is no longer needed ===
The JSON part is bit more tricky. Included with Zotonic are mochijson2 and as a secondary dependency also jiffy. The latest version of jiffy contains jiffy:decode/2 which allows you to specify maps as a return type. Much more readable than the standard {struct, {struct, <<"">>}} monster. To update to the latest version edit the line in deps/twerl/rebar.config that says
{jiffy, ".*", {git, "https://github.com/davisp/jiffy.git", {tag, "0.8.3"}}},
to
{jiffy, ".*", {git, "https://github.com/davisp/jiffy.git", {tag, "0.14.3"}}},
Now run z:m(). in the Zotonic shell. (you must do this after every change in your code).
Now check in the Zotonic shell if there is a jiffy:decode/2 available by typing jiffy: <tab>, it will show a list of available functions and their arity.
To retrieve a JSON file from the internet run:
{ok, {{_, 200, _}, _, Body}} = httpc:request(get, {"url-to-JSON-here", []}, [], [])
Which will yield the variable Body with the contents. See Erlang docs on http client for more info on this call.
Next convert the contents of Body to Erlang terms with:
JsonData = jiffy:decode(Body, [return_maps]).
What you have to do next depends a lot on the structure of your JSON resource. Keep in mind that everything is now in binary UTF-8 encoded strings! If you print JsonData to screen (just enter JsonData. in your Zotonic/Erlang shell) you will see a lot of #map{<<"key"", <<"Value">>} this.
My data was nested so I had to extract the needed data like this:
[{_,ItemList}|_] = ListData.
This gave me a list of maps, and in order to deal with them as individual items I used the following function:
get_maps([]) ->
done;
get_maps([First|Rest]) ->
Map = maps:get(<<"properties">>, First),
case is_map(Map) of
true ->
map_to_proplist(Map),
get_maps(Rest);
false -> done
end,
done;
get_maps(_) ->
done.
As you might remember, the z_db:insert/3 function needs a property list to populate rows, so that what the call to map_to_proplist/1 is for. How this function looks is completely dependent on how your data looks but as an example here is what worked for me:
map_to_proplist(Map) ->
case is_map(Map) of
true ->
{Value1,_} = string:to_integer(binary_to_list(maps:get(<<"key1">>, Map))),
{Value2,_} = string:to_float(binary_to_list(maps:get(<<"key2">>, Map))),
{Value3,_} = string:to_float(binary_to_list(maps:get(<<"key3">>, Map))),
Value4 = binary_to_list(maps:get(<<"key4">>, Map)),
{Value5,_} = string:to_integer(binary_to_list(maps:get(<<"key5">>, Map))),
{Value6,_} = string:to_integer(binary_to_list(maps:get(<<"key6">>, Map))),
PropList = [{rowname1, Value1}, {rowname2, Value2}, {rowname3, Value3}, {rowname4, Value4}, {rowname5, Value5}, {rowname6, Value6}],
m_sitename:insert_items(PropList,z:c(sitename)),
ok;
false ->
ok
end.
See the documentation on string:to_list/1 as to why the tuples are needed when casting. The call to m_sitename:insert_items(PropList,z:c(sitename)) calls the z_db:insert/3 in models/m_sitename.erl but wrapped in a catch:
insert_items(PropList,Context) ->
(catch z_db:insert(?table, PropList, Context)).
Ok, quite a long post but this should get you up and running if you were looking for this answer.
The above was done with Zotonic 0.13.2 on Erlang/OTP 18.
A repost (except the JSON part) of my post in the Zotonic Developers group.

How can I assign sequences to constants in the CONSTANTS section of a TLA+ configuration file?

I've tried
CONSTANTS seq = <<5,6,7>>
but TLC gives me a syntax error:
Error: TLC found an error in the
configuration file at line 1. It was
expecting = or <- and didn't find it.
I've also tried to include the Sequences module in the configuration file, to no avail.
So... what do I have to do to assign a sequence?
I don't remember ever facing this problem and my TLC is too rusty to try and give you a first hand answer (I just restarted using the TLA+ toolbox).
From the post linked bellow, however, I figure that you can't instantiate constants with sequences through the TLC config files.
http://bbpress.tlaplus.net/topic/creating-a-sequence-from-a-set
Even though the question is old, leaving an answer may help future TLAers.
You can't directly assign to a constant in the TLA+ file. If you're using the toolbox, write CONSTANTS seq, then in the model add the tuple you want as an ordinary assignment.
So it turns out that you need a separate .tla file for that. Suppose you have "Main.tla" as you source file. You want MyConst to have value <<1,2,3>>. TLA+ toolbox generates MC.tla where it puts the constants:
---- MODULE MC ----
EXTENDS Main, TLC
const_uniq12345 = <<1,2,3>>
====
in MC.cfg, there will be the line
CONSTANT MyConst <- const_uniq12345
Note that MyConst = const_uniq12345 won't work -- if you use = instead of <-, MyConst will contain model value const_uniq12345 instead of <<1, 2, 3>>
I used https://github.com/hwayne/tlacli to be able to run TLC from command line (TLA toolbox has awful UX), and I was able to supply a tuple constant with help of extra .tla file like this. I used meaningful name instead of const_uniq12345 too, of course. Had to call java -cp /path/to/tla2tools.jar ... manually, though (got the full command using --show-script option of tlacli), because currently tlacli doesn't handle <- in the config.