All parameters in Web Service contract operations cannot be a null - wcf

When I am adding one method to my Web Service I get the error when open the WSDL in the browser:
All parameters in Web Service contract operations cannot be a null
Here is method declaration:
[<System.ServiceModel.Web.WebInvokeAttribute>]
abstract PostFile: System.IO.Stream -> bool
And here is a current method implementation:
member x.PostFile(stream : Stream) : bool =
let filepath = Path.Combine(System.Environment.CurrentDirectory, "uploadedfile.jpg")
try
let outstream : FileStream = File.Open(filepath, FileMode.Create, FileAccess.Write)
let bufferLen : int = 4096
let buffer : byte array = Array.zeroCreate bufferLen
let count : int = 0
let mutable count = stream.Read(buffer, 0, bufferLen)
if count > 0 then
outstream.Write(buffer, 0, count)
while (count > 0) do
count <- stream.Read(buffer, 0, bufferLen)
outstream.Write(buffer, 0, count)
outstream.Close()
stream.Close()
true
with
| exn ->
printfn "Exception: \n%s" exn.Message
reraise()
Here is a full stack from the browser (sorry, for russian).
If I comment this one (and only one method) all works fine. What is the reason of the error and how can I fix it?

Sorry, I have found the error. It is necessary to set variable name in the contract:
abstract PostFile: stream:System.IO.Stream -> bool

Related

ClassCastException using ByteBuffer as key for ChronicleMap

I tried a very simple example where I try to write int -> ByteBuffer and reuse the array while reading the values from the map.
try (ChronicleMap<Integer, ByteBuffer> map = ChronicleMap
.of(Integer.class, ByteBuffer.class)
.entries(1)
.averageValueSize(30)
.createPersistedTo(new File("e:/temp/test.obj"))) {
byte[] out = new byte[] { 1, 2, 3};
map.put(1, ByteBuffer.wrap(out)); // ClassCastException
ByteBuffer buff = ByteBuffer.allocate(30);
ByteBuffer in = map.getUsing(1, buff); // hoping that 'ByteBuffer in'
// is redundant
}
Unfortunately I get an unexpected ClassCastException, because Chronicle expected a byte[]
Exception in thread "main" java.lang.ClassCastException: ChronicleMap{name=null, file=E:\temp\test.obj, identityHashCode=809762318}: Value must be a [B but was a class java.nio.HeapByteBuffer
at net.openhft.chronicle.map.VanillaChronicleMap.checkValue(VanillaChronicleMap.java:190)
at net.openhft.chronicle.map.VanillaChronicleMap.put(VanillaChronicleMap.java:707)
at test.SerTest.main(SerTest.java:28)
What am I doing wrong? Trying with byte[] worked, but getUsing() did not use my input array, that remained empty.

Does netlink use 'broadcast' for passing messages?

I am following netlink example on this question and answer.
But, I don't see a sort of connection identifier in source codes. Say:
Kernel
my_nl_sock = netlink_kernel_create(&init_net, NETLINK_USERSOCK, 0,
my_nl_rcv_msg, NULL, THIS_MODULE);
User space
nls = nl_socket_alloc();
ret = nl_connect(nls, NETLINK_USERSOCK);
ret = nl_send_simple(nls, MY_MSG_TYPE, 0, msg, sizeof(msg));
where NETLINK_USERSOCK and MY_MSG_TYPE don't seem to be a connection identifier.
In such a case, how does netlink know which data comes from which user space app or kernel module and which user space app or kernel module the data should go?
In my guess, netlink receives data from user space app or kernel module and broadcasts it. And every netlink-connected app or module checks message type if data is destined to 'me'
Is what I think right?
Firstly, I recommend to read some doc, for example http://www.linuxfoundation.org/collaborate/workgroups/networking/generic_netlink_howto
To communicate you have to register a family with supported operations. It can be done with the following functions
int genl_register_family( struct genl_family *family)
int genl_register_ops( struct genl_family * family, struct genl_ops *ops)
An example of a family definition:
/*
* Attributes (variables): the index in this enum is used as a reference for the type,
* userspace application has to indicate the corresponding type
*/
enum {
CTRL_ATT_R_UNSPEC = 0,
CTRL_ATT_CNT_SESSIONS,
__CTRL_ATT_R_MAX
};
#define CTRL_ATT_R_MAX ( __CTRL_ATT_R_MAX - 1 )
#define CTRL_FAMILY "your-family"
#define CTRL_PROTO_VERSION 1
/* Family definition */
static struct genl_family ctrl_bin_gnl_family = {
.id = GENL_ID_GENERATE, // genetlink should generate an id
.hdrsize = 0,
.name = CTRL_FAMILY, // the name of this family, used by userspace application
.version = CTRL_PROTO_VERSION, // version number
.maxattr = CTRL_ATT_R_MAX, // max number of attr
};
An example of an operation definition:
struct genl_ops ctrl_info = {
.cmd = CTRL_CMD_INFO,
.flags = 0,
.policy = 0, // you can use policy if you need
.doit = 0, // set this callback if this op does some interval stuff
.dumpit = __info, // set this callback if this op dump data
};
After that you can use in your userspace app your family and operations to communicate. Make a connection:
struct nl_sock * _nl = nl_socket_alloc();
int ret = genl_connect(nl);
// test if fail
int gid = genl_ctrl_resolve( nl, CTRL_FAMILY );
// test if fail
Send info operation
struct nl_msg * msg = msg_alloc(
CTRL_CMD_INFO,
NLM_F_DUMP
);
int ret = nl_send_auto(_nl, msg );
// test if fail
// wait for the ack
// read a reply

Is this system object pointer code at all possible in Swift?

I was pointed to this objc snippet from WWDC 14, but I work on a Swift project.
CMIOObjectPropertyAddress prop = {
kCMIOHardwarePropertyAllowScreenCaptureDevices,
kCMIOObjectPropertyScopeGlobal,
kCMIOObjectPropertyElementMaster
};
UInt32 allow = 1;
CMIOObjectSetPropertyData(kCMIOObjectSystemObject, &prop, 0, NULL, sizeof(allow), &allow);
I then tried rewriting to Swift:
var prop : CMIOObjectPropertyAddress {
kCMIOHardwarePropertyAllowScreenCaptureDevices
kCMIOObjectPropertyScopeGlobal
kCMIOObjectPropertyElementMaster
}
var allow:UInt32 = 1
CMIOObjectSetPropertyData(kCMIOObjectSystemObject, &prop, 0, nil, sizeof(UInt32), &allow)
But it doesn't even validate. I don't know how to translate the CMIOObjectPropertyAddress struct. Xcode says
/Users/mortenjust/Dropbox/hack/learning/screenrec/screenrec/deleteme.swift:32:61:
Cannot assign to a get-only property 'prop'
A C struct translates as a Swift struct. Use the implicit memberwise initializer:
var prop = CMIOObjectPropertyAddress(
mSelector: UInt32(kCMIOHardwarePropertyAllowScreenCaptureDevices),
mScope: UInt32(kCMIOObjectPropertyScopeGlobal),
mElement: UInt32(kCMIOObjectPropertyElementMaster))
The cool part is when you type CMIOObjectPropertyAddress(, code completion gives you the rest.
You're right, just got it running right this second. Turns out I also had to correct for some of the types. Here's the complete translation:
var prop = CMIOObjectPropertyAddress(
mSelector: CMIOObjectPropertySelector(kCMIOHardwarePropertyAllowScreenCaptureDevices),
mScope: CMIOObjectPropertyScope(kCMIOObjectPropertyScopeGlobal),
mElement: CMIOObjectPropertyElement(kCMIOObjectPropertyElementMaster))
var allow : UInt32 = 1
var dataSize : UInt32 = 4
var zero : UInt32 = 0
CMIOObjectSetPropertyData(CMIOObjectID(kCMIOObjectSystemObject), &prop, zero, nil, dataSize, &allow)
var session = AVCaptureSession()
session.sessionPreset = AVCaptureSessionPresetHigh
var devices = AVCaptureDevice.devices()
for device in AVCaptureDevice.devices() {
println(device)
}

NSMutableData to CConstPointer conversion in Swift needed

The following Swift code (writing bytes to a stream) is rewritten from Objective-C:
var outputStream : NSOutputStream = NSOutputStream()
var pData : NSMutableData = NSMutableData()
var pType : Int = 1
let pMessage : String = "Device_Description\0\0\x01" // 16BitChar with escapeSequence
var pLength : Int = 8+pMessage.lengthOfBytesUsingEncoding(NSUTF16LittleEndianStringEncoding)
pData.appendBytes(&pLength, length: 4)
pData.appendBytes(&pType, length: 4)
pData.appendData((pMessage as NSString).dataUsingEncoding(NSUTF16LittleEndianStringEncoding))
outputStream.write(pData.bytes, maxLength: pData.length)
pData.bytes is of type COpaquePointer, but CConstPointer<Uint8>is needed by the write operation. Any hints for the correct conversion? Thanks in advance.
As Jack wu has outlined, but somewhat incompletely, the following code works just the same as using the UnsafePointer option:
var byteData = [UInt8]()
pData.getBytes(&byteData)
self.outputStream!.write(byteData, maxLength: pData.length)
From the Swift & Objc interop book section here : https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/buildingcocoaapps/InteractingWithCAPIs.html
C Constant Pointers
When a function is declared as taking a CConstPointer argument,
it can accept any of the following:
nil, which is passed as a null pointer
A CMutablePointer, CMutableVoidPointer, CConstPointer, CConstVoidPointer, or AutoreleasingUnsafePointer value, which
is converted to CConstPointer if necessary
An in-out expression whose operand is an lvalue of type Type, which is passed as the address of the lvalue
A Type[] value, which is passed as a pointer to the start of the array, and lifetime-extended for the duration of the call
I believe then it can work like this:
var p: [Uint8] = []
pData.getBytes(&p)
outputStream.write(p, maxLength: pData.length)
I found a simple solution right now, by use of UnsafePointer<T>():
var outputStream : NSOutputStream = NSOutputStream()
var pData : NSMutableData = NSMutableData()
var pType : Int = 1
let pMessage : String = "Device_Description\0\0\x01" // 16BitChar with escapeSequence
var pLength : Int = 8+pMessage.lengthOfBytesUsingEncoding(NSUTF16LittleEndianStringEncoding)
pData.appendBytes(&pLength, length: 4)
pData.appendBytes(&pType, length: 4)
pData.appendData(ptpMessage.dataUsingEncoding(NSUTF16LittleEndianStringEncoding))
outputStream.write(UnsafePointer<UInt8>(pData.bytes), maxLength: pData.length)
#holex: Thanks for your input. I know this solution is not quite Swifty, but it´s working for now.

How to dump the NTFS $Bitmap file

For a project, I want to get the list of all free/used clusters on an NTFS partition.
For this i have to dump the $Bitmap file and parse its contents.
There are few API's and examples on the web, but however they don't seem to work. Is there a simple way/ code sample to just copy the $Bitmap file somewhere.
Is using FSCTL_GET_VOLUME_BITMAP the only way? Ideally I would like to do it in C#.
NFI.EXE which is (used to be) part of the "oem support tools" can enumerate all NTFS partition items. It might also be capable to dump the content of $Bitmap.
You definitely want to go the easy route and use the IOCTL rather than trying to read $Bitmap directly. Of course, you don't have to do it yourself if somebody has done it for you. It turns out that an MSDN blogger has already written a nice little wrapper for you:
http://blogs.msdn.com/jeffrey_wall/archive/2004/09/13/229137.aspx
The whole class is over 300 lines of code, so I won't post it all, but here's the function that gets the volume bitmap:
/// <summary>
/// Get cluster usage for a device
/// </summary>
/// <param name="DeviceName">use "c:"</param>
/// <returns>a bitarray for each cluster</returns>
static public BitArray GetVolumeMap(string DeviceName)
{
IntPtr pAlloc = IntPtr.Zero;
IntPtr hDevice = IntPtr.Zero;
try
{
hDevice = OpenVolume(DeviceName);
Int64 i64 = 0;
GCHandle handle = GCHandle.Alloc(i64, GCHandleType.Pinned);
IntPtr p = handle.AddrOfPinnedObject();
// alloc off more than enough for my machine
// 64 megs == 67108864 bytes == 536870912 bits == cluster count
// NTFS 4k clusters == 2147483648 k of storage == 2097152 megs == 2048 gig disk storage
uint q = 1024 * 1024 * 64; // 1024 bytes == 1k * 1024 == 1 meg * 64 == 64 megs
uint size = 0;
pAlloc = Marshal.AllocHGlobal((int)q);
IntPtr pDest = pAlloc;
bool fResult = DeviceIoControl(
hDevice,
FSConstants.FSCTL_GET_VOLUME_BITMAP,
p,
(uint)Marshal.SizeOf(i64),
pDest,
q,
ref size,
IntPtr.Zero);
if (!fResult)
{
throw new Exception(Marshal.GetLastWin32Error().ToString());
}
handle.Free();
/*
object returned was...
typedef struct
{
LARGE_INTEGER StartingLcn;
LARGE_INTEGER BitmapSize;
BYTE Buffer[1];
} VOLUME_BITMAP_BUFFER, *PVOLUME_BITMAP_BUFFER;
*/
Int64 StartingLcn = (Int64)Marshal.PtrToStructure(pDest, typeof(Int64));
Debug.Assert(StartingLcn == 0);
pDest = (IntPtr)((Int64)pDest + 8);
Int64 BitmapSize = (Int64)Marshal.PtrToStructure(pDest, typeof(Int64));
Int32 byteSize = (int)(BitmapSize / 8);
byteSize++; // round up - even with no remainder
IntPtr BitmapBegin = (IntPtr)((Int64)pDest + 8);
byte[] byteArr = new byte[byteSize];
Marshal.Copy(BitmapBegin, byteArr, 0, (Int32)byteSize);
BitArray retVal = new BitArray(byteArr);
retVal.Length = (int)BitmapSize; // truncate to exact cluster count
return retVal;
}
finally
{
CloseHandle(hDevice);
hDevice = IntPtr.Zero;
Marshal.FreeHGlobal(pAlloc);
pAlloc = IntPtr.Zero;
}
}