i am trying to impersonate another user before running a connecting to an API. my code has worked fine on windows xp, but 1 user received a windows 7 machine and the code no longer works. there is no error, imperonsation seems to be working, but no matter what I try the service is called using the current user's context. I have tried turning down UAC, still nothing. if I Run AS I can get the entire application to run as the other user, but this is not what I want to do. Anyone know what could cause impersonation to stop working on a machine?
CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Security.Permissions;
//This class is based on the code from here: http://msdn.microsoft.com/en- us/library/chf6fbt4.aspx
//And here: http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.aspx
public class Impersonator
{
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
private static WindowsImpersonationContext impersonationContext;
//For reference, not used yet.
//Ex: (int)Logontype.Interactive
enum LogonType
{
Interactive = 2,
Network = 3,
Batch = 4,
Service = 5,
Unlock = 7,
NetworkClearText = 8,
NewCredentials = 9
}
//For reference, not used yet
enum LogonProvider
{
Default = 0,
WinNT35 = 1,
WinNT40 = 2,
}
// If you incorporate this code into a DLL, be sure to demand FullTrust.
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public static void Impersonate(string user, string domain, string password)
{
try
{
//Impersonate a Windows User
SafeTokenHandle safeTokenHandle = default(SafeTokenHandle);
const int LOGON32_PROVIDER_DEFAULT = 0;
//This parameter causes LogonUser to create a primary token.
//const int LOGON32_LOGON_INTERACTIVE = 2; //Orig
const int LOGON32_LOGON_INTERACTIVE = 2; //2,9,7
// Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser(user, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);
WindowsIdentity windowsIdentity = new WindowsIdentity (safeTokenHandle.DangerousGetHandle());
impersonationContext = windowsIdentity.Impersonate();
//WindowsIdentity.Impersonate(safeTokenHandle.DangerousGetHandle());
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public static void StopImpersonating()
{
try
{
// Stop impersonating the user.
impersonationContext.Undo();
// Check the identity name.
Console.Write("Name of the identity after performing an Undo on the");
Console.WriteLine(" impersonation: " + WindowsIdentity.GetCurrent().Name);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Security;
using System.Runtime.ConstrainedExecution;
public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeTokenHandle()
: base(true)
{
}
[DllImport("kernel32.dll")]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr handle);
protected override bool ReleaseHandle()
{
return CloseHandle(handle);
}
}
Related
I am using LogonUser to get primary user token and then CreateProcessAsUser APIs to create process. But I am getting error code 6. Not sure what the problem is. Below is the code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LogOnUserTestWindows
{
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;
class Program
{
// Define the Windows LogonUser and CloseHandle functions.
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool LogonUser(String username, String domain, IntPtr password,
int logonType, int logonProvider, ref IntPtr token);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
private enum SW
{
SW_HIDE = 0,
SW_SHOWNORMAL = 1,
SW_NORMAL = 1,
SW_SHOWMINIMIZED = 2,
SW_SHOWMAXIMIZED = 3,
SW_MAXIMIZE = 3,
SW_SHOWNOACTIVATE = 4,
SW_SHOW = 5,
SW_MINIMIZE = 6,
SW_SHOWMINNOACTIVE = 7,
SW_SHOWNA = 8,
SW_RESTORE = 9,
SW_SHOWDEFAULT = 10,
SW_MAX = 10
}
[StructLayout(LayoutKind.Sequential)]
private struct STARTUPINFO
{
public int cb;
public String lpReserved;
public String lpDesktop;
public String lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
private struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
private static extern bool CreateProcessAsUser(
IntPtr hToken,
String lpApplicationName,
String lpCommandLine,
IntPtr lpProcessAttributes,
IntPtr lpThreadAttributes,
bool bInheritHandle,
uint dwCreationFlags,
IntPtr lpEnvironment,
String lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
// Define the required LogonUser enumerations.
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
private const int CREATE_UNICODE_ENVIRONMENT = 0x00000400;
private const int CREATE_NO_WINDOW = 0x08000000;
private const int CREATE_NEW_CONSOLE = 0x00000010;
static void Main()
{
// Display the current user before impersonation.
Console.WriteLine("Before impersonation: {0}",
WindowsIdentity.GetCurrent().Name);
// Ask the user for a network domain.
Console.Write("Please enter your domain: ");
string domain = Console.ReadLine();
// Ask the user for a user name.
Console.Write("Please enter your user name: ");
string username = Console.ReadLine();
// Ask the user for a password.
Console.Write("Please enter your password: ");
SecureString passWord = GetPassword();
// Impersonate the account provided by the user.
try
{
//WindowsImpersonationContext userContext = ImpersonateUser(passWord, username, domain);
IntPtr token = ImpersonateUser(passWord, username, domain);
// Display the current user after impersonation.
Console.WriteLine("After impersonation: {0}",
WindowsIdentity.GetCurrent().Name);
}
catch (ArgumentException e)
{
Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message);
}
catch (Win32Exception e)
{
Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message);
}
finally
{
passWord.Dispose();
}
}
public static SecureString GetPassword()
{
SecureString password = new SecureString();
// get the first character of the password
ConsoleKeyInfo nextKey = Console.ReadKey(true);
while (nextKey.Key != ConsoleKey.Enter)
{
if (nextKey.Key == ConsoleKey.Backspace)
{
if (password.Length > 0)
{
password.RemoveAt(password.Length - 1);
// erase the last * as well
Console.Write(nextKey.KeyChar);
Console.Write(" ");
Console.Write(nextKey.KeyChar);
}
}
else
{
password.AppendChar(nextKey.KeyChar);
Console.Write("*");
}
nextKey = Console.ReadKey(true);
}
Console.WriteLine();
// lock the password down
password.MakeReadOnly();
return password;
}
public static IntPtr ImpersonateUser(SecureString password, string userName, string domainName)
{
IntPtr tokenHandle = IntPtr.Zero;
IntPtr passwordPtr = IntPtr.Zero;
bool returnValue = false;
int error = 0;
// Marshal the SecureString to unmanaged memory.
passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(password);
// Pass LogonUser the unmanaged (and decrypted) copy of the password.
returnValue = LogonUser(userName, domainName, passwordPtr,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
ref tokenHandle);
if (!returnValue && tokenHandle == IntPtr.Zero)
error = Marshal.GetLastWin32Error();
// Perform cleanup whether or not the call succeeded.
// Zero-out and free the unmanaged string reference.
Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr);
// Close the token handle.
CloseHandle(tokenHandle);
// Throw an exception if an error occurred.
if (error != 0)
{
throw new System.ComponentModel.Win32Exception(error);
}
// The token that is passed to the following constructor must
// be a primary token in order to use it for impersonation.
//WindowsIdentity newId = new WindowsIdentity(tokenHandle);
//String workgroup;
string cmdLine = null;
string workDir = null;
bool visible = true;
var pEnv = IntPtr.Zero;
var startInfo = new STARTUPINFO();
var procInfo = new PROCESS_INFORMATION();
int iResultOfCreateProcessAsUser;
uint dwCreationFlags = CREATE_UNICODE_ENVIRONMENT | (uint)(visible ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW);
startInfo.wShowWindow = (short)(visible ? SW.SW_SHOW : SW.SW_HIDE);
startInfo.lpDesktop = "winsta0\\default";
if (!CreateProcessAsUser(
tokenHandle,
"C:/Windows/System32/notepad.exe", // Application Name
cmdLine, // Command Line
IntPtr.Zero,
IntPtr.Zero,
false,
dwCreationFlags,
pEnv,
workDir, // Working directory
ref startInfo,
out procInfo))
{
iResultOfCreateProcessAsUser = Marshal.GetLastWin32Error();
throw new Exception("StartProcessAsCurrentUser: CreateProcessAsUser failed. Error Code -" + iResultOfCreateProcessAsUser);
}
return tokenHandle;
}
}
}
Below is the error
System.Exception
HResult=0x80131500
Message=StartProcessAsCurrentUser: CreateProcessAsUser failed. Error Code -6
Source=LogOnUserTestWindows
StackTrace:
at LogOnUserTestWindows.Program.ImpersonateUser(SecureString password, String userName, String domainName) in C:\Users\santosh\source\repos\LogOnUserTestWindows\LogOnUserTestWindows\Program.cs:line 242
at LogOnUserTestWindows.Program.Main() in C:\Users\santosh\source\repos\LogOnUserTestWindows\LogOnUserTestWindows\Program.cs:line 122
I am not able to find any proper documentation for both logonUser and CreateProcessAsUser APIs. I am trying to run this code on my machine which has multiple usets. I am logged in from one user and trying to create process from another user. It would be really great if someone can point me to proper documentation or examples. Please help. Thanks in Advance.
You closed tokenHandle before you passed it to CreateProcessAsUser.
Result: ERROR_INVALID_HANDLE (= 6).
Please try CreateProcessWithToken instead, although I don't know why the function returned error code -6, but a few days ago I tried to start up an application with specified user token, but CreateProcessAsUser didn't work, but CreateProcessWithToken did. Maybe it will also work for you, good luck.
SQLite-net-pcl seem's to work on all platforms except Android 7.0.
So far on Android 7.0 from a fresh install the application will crash due to an SQLException with the issue that it can't create a PK. If I uninstall the applications storage I.e. wipe the app from application settings, the app then works perfectly.
All other platforms seem to install instantly. See for youself https://play.google.com/store/apps/details?id=com.purewowstudio.fivestartips
I cannot seem to fix this. Worst of all, my iOS which shares a DB PCL doesn't load at all.
Does anyone know how to fix this?
Code example:-
Object
using System;
namespace App.LocalObjects
{
[Preserve(AllMembers = true)]
public class LocalArticle
{
[SQLite.PrimaryKey, SQLite.Column("articleObjectId")]
public string objectId { get; set; }
public DateTime createdAt { get; set; }
public DateTime updatedAt { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Url { get; set; }
public int Status { get; set; }
public LocalArticle()
{
this.objectId = " ";
this.Title = " ";
this.Description = " ";
this.Url = " ";
}
}
}
Database
using System;
using System.Linq;
using System.Collections.Generic;
using SQLite;
using App.LocalObjects;
namespace App.DataLayer
{
public class Database
{
static object locker = new object();
public SQLiteConnection database;
public string path;
public Database(SQLiteConnection conn)
{
database = conn;
database.CreateTable<LocalArticle>();
}
public int SaveLocalArticleItem(LocalArticle item)
{
lock (locker)
{
LocalArticle article = database.Table<LocalArticle>().FirstOrDefault(x => x.objectId == item.objectId);
if (article != null && article.objectId.Equals(item.objectId) && !article.updatedAt.Equals(item.updatedAt))
{
database.Update(item);
return item.ID;
} else {
return database.Insert(item);
}
}
}
Code to initialize DB:
using System;
using System.IO;
using Android.App;
using App.BusinessLayer.Managers;
using App.BusinessLayer.ParseObjects;
using App.Utils;
using Android.Content;
using Com.Nostra13.Universalimageloader.Core;
using Com.Nostra13.Universalimageloader.Core.Assist;
using Android.Graphics;
using Com.Nostra13.Universalimageloader.Cache.Memory.Impl;
using Com.OneSignal;
using Parse;
using SQLite;
namespace App.Droid
{
[Application(LargeHeap = true)]
public class App : Application
{
public static App Current { get; private set; }
public ModelManager modelManager { get; set; }
private SQLiteConnection conn;
private ImageLoader imageLoader;
public App(IntPtr handle, global::Android.Runtime.JniHandleOwnership transfer)
: base(handle, transfer)
{
Current = this;
}
public override void OnCreate()
{
base.OnCreate();
SetupParse();
SetupDB();
}
private void SetupParse()
{
ParseObject.RegisterSubclass<ParseArticle>();
ParseClient.Initialize(new ParseClient.Configuration
{
ApplicationId = Constants.ParseApplicationID,
Server = Constants.ParseServer
});
}
private void SetupDB()
{
var sqliteFilename = Constants.DBName;
string libraryPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var path = System.IO.Path.Combine(libraryPath, sqliteFilename);
conn = new SQLiteConnection(path);
modelManager = new ModelManager(conn);
}
Here's what my project is currently referencing:-
Android N began actually enforcing rules around accessing the SQLite libraries that come with Android. Therefore any app (or app library) that was previously directly accessing SQLite without going through the special Java wrapper was already breaking the rules technically, the reason it was not a problem was because Android never really enforced those rules. Read more about that here
Now that Android N does enforce those rules, it causes the crash to occur. I am guessing that you are using the SQLite.Net-PCL library for accessing your SQLite DB. If you look here there is an open issue for that exact problem that the library creators never fixed.
We ran into the same issue and have since switched to the SQLite-Net-PCL library (notice the dash instead of the period) which works the exact same way and has an almost identical API. A link for that library can be found here.
i have same issue. i install this package for sqlite and set targeted version to android 8(oreo) my application works again
Im trying to get this thing to work all day.
Im trying to paste an input text to a textbox in another windows application, (lets say Chrome's URL bar)
I managed to get the main window hwnd, but when I used SendMessage, it just changed the title of the window
SO I am trying to figure out how exactly do I find out, dynamically, the hwnd of my textbox.
I also tried Spy++ but it gave me the same hwnd for all child windows for some reason, must did something wrong.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);
private static IntPtr WinGetHandle(string wName)
{
IntPtr hWnd = IntPtr.Zero;
foreach (Process pList in Process.GetProcesses())
{
if (pList.MainWindowTitle.Contains(wName))
{
hWnd = pList.MainWindowHandle;
}
}
return hWnd;
}
static void Main(string[] args)
{
List<IntPtr> myList = GetChildWindows(WinGetHandle("chrome"));
foreach(IntPtr ptr in myList)
{
//No idea which one of those IntPtr is actually my textbox
//SendMessage((IntPtr)788018, 0x000C, 0, "text here");
}
Console.ReadLine();
}
[DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr i);
public static List<IntPtr> GetChildWindows(IntPtr parent)
{
List<IntPtr> result = new List<IntPtr>();
GCHandle listHandle = GCHandle.Alloc(result);
try
{
EnumWindowProc childProc = new EnumWindowProc(EnumWindow);
EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle));
}
finally
{
if (listHandle.IsAllocated)
listHandle.Free();
}
return result;
}
private static bool EnumWindow(IntPtr handle, IntPtr pointer)
{
GCHandle gch = GCHandle.FromIntPtr(pointer);
List<IntPtr> list = gch.Target as List<IntPtr>;
if (list == null)
{
throw new InvalidCastException("GCHandle Target could not be cast as List<IntPtr>");
}
list.Add(handle);
// You can modify this to check to see if you want to cancel the operation, then return a null here
return true;
}
public delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter);
}
}
I also tried Spy++ but it gave me the same hwnd for all child windows
for some reason, must did something wrong.
Not all applications use old-school "heavy" controls backed by a windows handle. For example, .Net WPF applications will exhibit the same behavior of just one handle for the main window itself. Everything is else drawn directly to the screen as needed via DirectX. Web browsers are "light" as well and don't use controls backed by a handles. Basically if Spy++ doesn't show child windows inside the main window then you won't be able to use the traditional window manipulation APIs or SendMessage().
Sadly I couldnt find a way to make it the way I wanted, but I found a workaround that works pretty well:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
static void Main(string[] args)
{
IntPtr hWnd = FindWindow(null, "Origin");
if (!hWnd.Equals(IntPtr.Zero))
{
// activate Notepad window
if (SetForegroundWindow(hWnd))
{
// send "Hello World!"
SendKeys.SendWait("Hello World!");
// send key "Tab"
SendKeys.SendWait("{TAB}");
// send key "Enter"
SendKeys.SendWait("{ENTER}");
}
}
}
}
}
I would like to use NAudio for a record program, but I'm hitting an unexpected limitation. NAudio.Wave.WaveIn.GetCapabilities(deviceNumber) returns a WaveInCapabilities structure, but only a few fields of that structure are public.
In particular I need to know which formats are supported by the device. That information is in:
private SupportedWaveFormat supportedFormats;
I can change that to public and build NAaudio.dll, but I'm wondering if there is some reason that field is marked private? Or is there another place I can find that information?
there was an example on the web, i edited it, and this works for me to get all the capabilites from different devices (it's quite ugly, but it works...):
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Collections;
namespace _4ch_stream
{
class clsRecDevices
{
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct WaveInCaps
{
public short wMid;
public short wPid;
public int vDriverVersion;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public char[] szPname;
public uint dwFormats;
public short wChannels;
public short wReserved1;
}
[DllImport("winmm.dll")]
public static extern int waveInGetNumDevs();
[DllImport("winmm.dll", EntryPoint = "waveInGetDevCaps")]
public static extern int waveInGetDevCapsA(int uDeviceID,
ref WaveInCaps lpCaps, int uSize);
public ArrayList arrLst = new ArrayList();
//using to store all sound recording devices strings
static int devcount = waveInGetNumDevs();
public static short[] Mid = new short[devcount];
public static short[] Pid = new short[devcount];
public static int[] DriverVersion = new int[devcount];
public static uint[] Formats = new uint[devcount];
public static short[] Channels = new short[devcount];
public static short[] Reserved1 = new short[devcount];
public int Count
//to return total sound recording devices found
{
get { return arrLst.Count; }
}
public string this[int indexer]
//return spesipic sound recording device name
{
get { return (string)arrLst[indexer]; }
}
public clsRecDevices() //fill sound recording devices array
{
int waveInDevicesCount = waveInGetNumDevs(); //get total
if (waveInDevicesCount > 0)
{
for (int uDeviceID = 0; uDeviceID < waveInDevicesCount; uDeviceID++)
{
WaveInCaps waveInCaps = new WaveInCaps();
waveInGetDevCapsA(uDeviceID, ref waveInCaps,
Marshal.SizeOf(typeof(WaveInCaps)));
arrLst.Add(new string(waveInCaps.szPname).Remove(
new string(waveInCaps.szPname).IndexOf('\0')).Trim());
Mid[uDeviceID] = waveInCaps.wMid;
Pid[uDeviceID] = waveInCaps.wPid;
Formats[uDeviceID] = waveInCaps.dwFormats;
Channels[uDeviceID] = waveInCaps.wChannels;
Reserved1[uDeviceID] = waveInCaps.wReserved1;
//clean garbage
}
}
}
}
}
Hope it helped.
i am stuck on how to take a screenshot of my windows phone 7.5 and sending it over TCP. i have no experience in doing socket program and I/O and am doing what i can through tutorials over the internet. This is what i have done.
From the codes below i am stuck in how i can send the writeableBitMap over TCP encoded as a Jpeg periodically running in the WP7.5 background, whereby a program on a desktop will receive it as a jpeg image so it can be displayed creating a windows phone to desktop streaming effect.
my mainPage of my windows phone 7.5 application using a library i have created from a tutorial for taking care of the sockets connection.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone;
using System.Windows.Media;
using System.IO;
namespace helloworld
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
SocketLibrary.socketLib sl = new SocketLibrary.socketLib();
private string hostIP = "127.0.0.1";
public MainPage()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, RoutedEventArgs e)
{
bool retVal;
retVal = sl.EstablishTCPConnection(hostIP);
WriteableBitmap bmpCurrentScreenImage = new WriteableBitmap((int)this.ActualWidth, (int)this.ActualHeight);
var ms = new MemoryStream();
// Send the picture.
bmpCurrentScreenImage.SaveJpeg(ms, bmpCurrentScreenImage.PixelWidth, bmpCurrentScreenImage.PixelHeight, 0, 90);
ms.Seek(0, SeekOrigin.Begin);
retVal = sl.Send(ms);
sl.CloseSocket();
}
}
}
the socket library
namespace SocketLibrary
{
public class socketLib
{
Socket s = null;
static ManualResetEvent done = new ManualResetEvent(false);
private Int16 portNo = 3334;
public socketLib()
{
}
public bool EstablishTCPConnection(string host)
{
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = new DnsEndPoint(host, portNo);
socketEventArg.Completed += new
EventHandler<SocketAsyncEventArgs>(delegate(object o, SocketAsyncEventArgs e)
{
done.Set();
});
done.Reset();
s.ConnectAsync(socketEventArg);
return done.WaitOne(10000);
}
public bool Send(MemoryStream data)
{
byte[] msData = data.ToArray();
if (s != null)
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = s.RemoteEndPoint;
socketEventArg.UserToken = null;
socketEventArg.Completed += new
EventHandler<SocketAsyncEventArgs>(delegate(object o, SocketAsyncEventArgs e)
{
done.Set();
});
socketEventArg.SetBuffer(msData, 0, msData.Length);
done.Reset();
s.SendAsync(socketEventArg);
return done.WaitOne(10000);
}
return false;
}
public void CloseSocket()
{
if (s != null)
{
s.Close();
}
}
}
}
check this
http://www.charlespetzold.com/blog/2011/05/Windows-Phone-Screen-Shots.html
http://blog.galasoft.ch/archive/2010/12/28/taking-a-screenshot-from-within-a-silverlight-wp7-application.aspx