I want to get my network interface's Name, Speed, and MAC Address.
var searcher = new ManagementObjectSearcher { Scope = GetConnectedScope(target, "cimv2") };
try
{
searcher.Query = new ObjectQuery("SELECT MACAddress, Speed, Name FROM Win32_NetworkAdapter");
var nicList = new List<NetworkInterfaceModel>();
foreach (var item in searcher.Get())
{
nicList.Add(new NetworkInterfaceModel
{
NetworkInterfaceName = (string)item["Name"],
NetworkInterfaceSpeed = (double)(item["Speed"] != null ? (ulong) item["Speed"] : 0)/1000/1000,
MacAddress = (string)item["MACAddress"]
});
}
For Windows 7 and Vista it work just fine, but for XP and Windows Server 2003 it didn't collect the speed. How can I get the speed for XP and Server 2003?
You can get networks name using windows cmd:
Process p = new Process();
p.StartInfo.FileName = "netsh.exe";
p.StartInfo.Arguments = "wlan show interfaces";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string s = p.StandardOutput.ReadToEnd();
string s1 = s.Substring(s.IndexOf("SSID"));
s1 = s1.Substring(s1.IndexOf(":"));
s1 = s1.Substring(2, s1.IndexOf("\n")).Trim();
p.WaitForExit();
namelabel.Text = s1;
for MAC Address:
IPAddress IP = IPAddress.Parse("192.168.1.1");
byte[] macAddr = new byte[6];
uint macAddrLen = (uint)macAddr.Length;
UInt32 nRet = 0;
uint nAddress = BitConverter.ToUInt32(IP.GetAddressBytes(), 0);
nRet = SendARP(nAddress, 0, macAddr, ref macAddrLen);
if (nRet == 0)
{
string[] sMacAddress = new string[(int)macAddrLen];
for (int i = 0; i < macAddrLen; i++)
{
sMacAddress[i] = macAddr[i].ToString("x2");
string macAddress += sMacAddress[i] + (i < macAddrLen - 1 ? ":" : "");
}
}
and about speed you can use the following code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.NetworkInformation;
Start with adding a timerInteval(How fast you want to change to the new value) a NetworkInteface and a timer:
private const double timerUpdate = 1000;
private NetworkInterface[] nicArr;
private Timer timer;
Then Continue using the folowing componets on start up:
public Form1()
{
InitializeComponent();
InitializeNetworkInterface();
InitializeTimer();
}
Componets:
private void InitializeNetworkInterface()
{
// Grab all local interfaces to this computer
nicArr = NetworkInterface.GetAllNetworkInterfaces();
// Add each interface name to the combo box
for (int i = 0; i < nicArr.Length; i++)
comboBox1.Items.Add(nicArr[i].Name); //you add here the interface types in a combobox and select from here WiFi, ethernet etc...
// Change the initial selection to the first interface
comboBox1.SelectedIndex = 0;
}
private void InitializeTimer()
{
timer = new Timer();
timer.Interval = (int)timerUpdate;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
Timer's tick
void timer_Tick(object sender, EventArgs e)
{
UpdateNetworkInterface();
}
With this void you update the ping:
public void UpdatePing()
{
try
{
Ping myPing = new Ping();
PingReply reply = myPing.Send(textBox1.Text, 1000);
if (reply != null)
{
label17.Text = reply.Status.ToString();
label18.Text = reply.RoundtripTime.ToString();
}
}
catch
{
label17.Text = "ERROR: You have Some TIMEOUT issue";
label18.Text = "ERROR: You have Some TIMEOUT issue";
}
}
and finally use this to show the speed in network form:
private void UpdateNetworkInterface()
{
// Grab NetworkInterface object that describes the current interface
NetworkInterface nic = nicArr[comboBox1.SelectedIndex];
// Grab the stats for that interface
IPv4InterfaceStatistics interfaceStats = nic.GetIPv4Statistics();
// Calculate the speed of bytes going in and out
// NOTE: we could use something faster and more reliable than Windows Forms Tiemr
// such as HighPerformanceTimer http://www.m0interactive.com/archives/2006/12/21/high_resolution_timer_in_net_2_0.html
// Update the labels
speedlbl.Text = nic.Speed.ToString();
interfaceTypelbl.Text = nic.NetworkInterfaceType.ToString();
bytesReceivedlbl.Text = interfaceStats.BytesReceived.ToString();
bytesSentlbl.Text = interfaceStats.BytesSent.ToString();
int bytesSentSpeed = (int)(interfaceStats.BytesSent - double.Parse(label10.Text)) / 1024;
int bytesReceivedSpeed = (int)(interfaceStats.BytesReceived - double.Parse(label11.Text)) / 1024;
bytescomelbl.Text = bytesSentSpeed.ToString() + " KB/s";
bytessentlbl.Text = bytesReceivedSpeed.ToString() + " KB/s";
}
Win32_NetworkAdapter doesn't support the speed property under XP, As per http://msdn.microsoft.com/en-us/library/windows/desktop/aa394216(v=vs.85).aspx :
Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: This property has not been implemented yet. It returns a NULL value by default.
Instead, use the CIM_NetworkAdapter class with the same property.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa387931(v=vs.85).aspx
using System.Net;
foreach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces()) {
Debug.WriteLine(netInterface.Name); // Name
Debug.WriteLine(netInterface.Speed); // Speed
Debug.WriteLine(netInterface.GetPhysicalAddress().ToString()); // MAC
}
Related
There was such a problem: I ran the program many times and now it throws the following error FloodException: Flood prevention. Telegram now requires your program to do requests again only after 73611 seconds have passed (TimeToWait property). If you think the culprit of this problem may lie in TLSharp's implementation, open a Github issue please.
I attach the code below:
using System;
using System.Text;
using System.Windows.Forms;
using TeleSharp.TL;
using TeleSharp.TL.Messages;
using TLSharp.Core;
namespace tgBM
{
public partial class Form1: Form
{
string phone;
string code;
int n = 1;
StringBuilder sb = new StringBuilder ();
TelegramClient client = new TelegramClient (2646156, "08ec188e0bdee432e568120348f5f13a"); // create a client with parameters
public Form1 ()
{
InitializeComponent();
}
string str = "";
public async void authAsync()
{
var dialogs = (TLDialogs) await client.GetUserDialogsAsync();
foreach (var element in dialogs.Chats)
{
TLChat chat = element as TLChat;
if (element is TLChannel)
{
var offset = 0;
TLChannel channel = element as TLChannel;
if (channel.Title == "TOPLES")
{
TLChannel ch = element as TLChannel;
TLInputPeerChannel inputPeer = new TLInputPeerChannel() {ChannelId = ch.Id, AccessHash = (long) ch.AccessHash};
while (n! = 11)
{
try
{
TLChannelMessages res = await client.SendRequestAsync <TLChannelMessages>
(new TLRequestGetHistory() {Peer = inputPeer, Limit = 20, AddOffset = offset, OffsetId = 0});
var msgs = res.Messages;
if (res.Count> offset)
{
offset + = msgs.Count;
foreach (TLAbsMessage msg in msgs)
{
if (msg is TLMessage)
{
TLMessage message = msg as TLMessage;
str + = n.ToString () + "\ t" + message.Id + "\ t" + message.FromId + "\ t" + message.Message + Environment.NewLine;
}
if (msg is TLMessageService)
continue;
n ++;
}
}
else
break;
}
catch (Exception ex)
{
MessageBox.Show (ex.Message);
break;
}
}
}
}
textBox3.Text = str;
}
}
private async void button1_Click (object sender, EventArgs e)
{
phone = textBox1.Text;
await client.ConnectAsync (); // make a connection
var hash = await client.SendCodeRequestAsync(phone);
}
private async void button2_Click (object sender, EventArgs e)
{
code = textBox2.Text;
var user = await client.MakeAuthAsync(phone, await client.SendCodeRequestAsync(phone), code);
authAsync();
}
}
}
In a comment, you said are in a testing phase.
In this case, you should read https://core.telegram.org/api/auth#test-accounts
According to this page, there are 3 ways to perform tests while limiting the risk for FLOOD_WAIT errors:
Connect to the Test servers instead of the Production servers (seems not possible with TLSharp)
Use Test accounts with phone numbers 99966XYYYY (only available on Test servers)
Connect as a user with the phone number you use to create the API ID/Hash
I can do all that with WTelegramClient (TLSharp is no longer maintained and cannot connect to Telegram servers anymore)
I wrote 2 winforms as follows
Check the connection of the Ardruino to PC 1 and write the received information to log.txt file
Read selected information in log files and send them to PC 2 (SQL installed)
Note: PC 1 has 2 network cards (network card 1 receives the signals of the Arduino over the range: 192.168.1.2; Network card 2 connects to PC 2 via the range: 110.110.1.2)
How do I get the information I need from PC 1 and transfer them to PC 2 (with SQL installed) with only 1 program
My code Winform received form Arduino:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Data.SqlClient;
namespace TCPIPSeverMutilClient
{
public partial class Form1 : Form
{
const int MAX_CONNECTION = 30;
const int PORT_NUMBER =1989;
int currentconnect = 0;
delegate void SetTextCallback(string text);
static TcpListener listener;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
IPAddress address = IPAddress.Parse(IPText.Text);
listener = new TcpListener(address, PORT_NUMBER);
AddMsg("Creat Sever with IP :"+ IPText.Text);
AddMsg("Waiting for connection...");
button1.Hide();
listener.Start();
for (int i = 0; i < MAX_CONNECTION; i++)
{
// new Thread(DoWork).Start();
Thread aThread = new Thread(DoWork);
aThread.IsBackground = true; //<-- Set the thread to work in background
aThread.Start();
}
}
private void DoWork()
{
while (true)
{
Socket soc = listener.AcceptSocket();
currentconnect = currentconnect + 1;
SetText("Numbers Connection " + currentconnect.ToString());
Console.WriteLine("Connection received from: {0}", soc.RemoteEndPoint);
try
{
var stream = new NetworkStream(soc);
var reader = new StreamReader(stream);
var writer = new StreamWriter(stream);
writer.AutoFlush = true;
//writer.WriteLine("Welcome to Student TCP Server");
// writer.WriteLine("Please enter the student id");
while (true)
{
string id = reader.ReadLine();
SetText(id);
// writer.WriteLine("END");
if (String.IsNullOrEmpty(id))
break; // disconnect
//if (_data.ContainsKey(id))
// writer.WriteLine("Student's name: '{0}'", _data[id]);
else
{
writer.WriteLine("END");
// writer.WriteLine("Can't find name for student id '{0}'", id);
}
}
stream.Close();
}
catch (Exception ex)
{
SetText("Error: " + ex);
}
// Console.WriteLine("Client disconnected: {0}",soc.RemoteEndPoint);
soc.Close();
currentconnect = currentconnect - 1;
SetText("Numbers Connection " + currentconnect.ToString());
}
}
private void SetText(string text)
{
if (this.rtbText.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText); // khởi tạo 1 delegate mới gọi đến SetText
this.Invoke(d, new object[] { text });
}
else
{
this.AddMsg(text);
}
}
private void SaveText(string text)
{
const string textFileName = "Log.txt";
const int insertAtLineNumber = 0;
List<string> fileContent = File.ReadAllLines(textFileName).ToList();
// AddMsg(fileContent.Count.ToString());
//fileContent.InsertRange(insertAtLineNumber, text);
fileContent.Insert(insertAtLineNumber, text);
File.WriteAllLines(textFileName, fileContent);
}
private void AddMsg(string msg)
{
rtbText.Items.Add(DateTime.Now + " : " + msg);
SaveText(DateTime.Now + " : " + msg);
if (rtbText.Items.Count >= 150)
{ rtbText.Items.RemoveAt(0); }
}
}
}
As the Arduino card attached to PC 1 cannot be accessed from the PC 2.
You need to pass the Arduino data to the MSSQL Database. Then Retrieve the data in PC 2 by accessing it from PC 1. You can use this Reference for How to access Database over network
Up to now, when I returned this case I had a solution.
In PC1, there are 2 network cards, you just need to use the Network class to find the IP with the IP with IP in PC2
Instead of reading from the log file I was inspired directly from Arduino returned and transmitted to PC2
string hostname = Dns.GetHostName();
System.Net.IPHostEntry ip = new IPHostEntry();
ip = Dns.GetHostByName(hostname);
foreach (IPAddress listip in ip.AddressList)
{
if (listip.ToString().StartsWith("110."))
{
ipMay = listip.ToString();
macPairIp = GetMacByIP(ipMay);
try
{
//Do work here
}
catch (...)
{}
}
}
In my project I need receive a video through UDP. Source have a IP 224.0.0.21, Sink have a IP 169.254.170.141. I receive video through a port 3956 (This is a valid information from Wireshark). I use SharpPcap for receive UDP traffic, but it have not methods for join to multicast. I try this code from MSDN, but it dont work.
IPAddress multicastaddress = IPAddress.Parse("224.0.0.21");
IPEndPoint remoteep = new IPEndPoint(IPAddress.Any, 3956);
m_ClientTarget.JoinMulticastGroup(multicastaddress, localAddr);
In my PC I have some network adapters, but I use the IP address from device, that connected to source video. Source and sink connected directly. When I start monitor traffic in the wireshark my programm also receive packet, but without the wireshack it cant do it.
My code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SharpPcap;
using SharpPcap.LibPcap;
using SharpPcap.AirPcap;
using SharpPcap.WinPcap;
using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Threading;
namespace GVSPCapture
{
public partial class Form1 : Form
{
static int frameCounter = 0;
static byte[] pixels = new byte[1920 * 1080 * 3];
static IPAddress fpgaAddr = IPAddress.Parse("224.0.0.21");
static IPAddress localAddr = IPAddress.Parse("169.254.170.141");
static MulticastOption mcastOption = new MulticastOption(fpgaAddr, localAddr);
private static UdpClient m_ClientTarget = new UdpClient(3956);
private static IPAddress m_GrpAddr;
const int GroupPort = 3956;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
findDevices();
}
public void findDevices()
{
string ver = SharpPcap.Version.VersionString;
var devices = CaptureDeviceList.Instance;
foreach (var dev in devices)
{
lbxDevices.Items.Add(dev.Name + dev.Description);
}
}
private void JoinVideoMulticast()
{
IPAddress multicastaddress = IPAddress.Parse("224.0.0.21");
IPEndPoint remoteep = new IPEndPoint(IPAddress.Any, 3956);
m_ClientTarget.JoinMulticastGroup(multicastaddress, IPAddress.Parse("169.254.170.141"));
while (true)
{ }
}
private void startCapture(ICaptureDevice dev)
{
if (!dev.Started)
{
dev.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
int readTimeoutMilliseconds = 1000;
if (dev is AirPcapDevice)
{
// NOTE: AirPcap devices cannot disable local capture
var airPcap = dev as AirPcapDevice;
airPcap.Open(SharpPcap.WinPcap.OpenFlags.DataTransferUdp, readTimeoutMilliseconds);
}
else if (dev is WinPcapDevice)
{
var winPcap = dev as WinPcapDevice;
winPcap.Open(SharpPcap.WinPcap.OpenFlags.DataTransferUdp | SharpPcap.WinPcap.OpenFlags.NoCaptureLocal, readTimeoutMilliseconds);
}
else if (dev is LibPcapLiveDevice)
{
var livePcapDevice = dev as LibPcapLiveDevice;
livePcapDevice.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
}
else
{
throw new System.InvalidOperationException("unknown device type of " + dev.GetType().ToString());
}
dev.StartCapture();
Thread recvThread = new Thread(JoinVideoMulticast);
recvThread.Start();
}
}
delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.tbxCnt.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.tbxCnt.Text = text;
}
}
private void device_OnPacketArrival(object sender, CaptureEventArgs e)
{
var time = e.Packet.Timeval.Date;
var len = e.Packet.Data.Length;
if (len == 572)
{
var tmp = e.Packet.Data;
int packet_id = tmp[47] << 16 | tmp[48] << 8 | tmp[49];
int startPos = (packet_id - 1) * 522;
for (int i = 50; i < tmp.Length; i+=3)
{
pixels[startPos + i + 0 - 50] = tmp[i];
pixels[startPos + i + 1 - 50] = tmp[i];
pixels[startPos + i + 2 - 50] = tmp[i];
}
}
if (len == 60)
{
var im = CopyDataToBitmap(pixels);
pictbFrame.Image = im;
frameCounter += 1;
SetText(frameCounter.ToString());
}
}
public Bitmap CopyDataToBitmap(byte[] data)
{
GCHandle pinned = GCHandle.Alloc(data, GCHandleType.Pinned);
IntPtr ptr = pinned.AddrOfPinnedObject();
BitmapData dt = new BitmapData();
dt.Scan0 = ptr;
dt.Stride = 5760;
dt.Width = 1920;
dt.Height = 1080;
dt.PixelFormat = PixelFormat.Format24bppRgb;
Bitmap btm = new Bitmap(1920, 1080, 5760, PixelFormat.Format24bppRgb, dt.Scan0);
return btm;
}
private void btnStart_Click(object sender, EventArgs e)
{
int devNum = lbxDevices.SelectedIndex;
if (devNum > 0)
{
var device = CaptureDeviceList.Instance[devNum];
startCapture(device);
}
}
private void btnStop_Click(object sender, EventArgs e)
{
int devNum = lbxDevices.SelectedIndex;
if (devNum > 0)
{
var device = CaptureDeviceList.Instance[devNum];
if (device.Started)
{
device.StopCapture();
device.Close();
}
}
m_ClientTarget.DropMulticastGroup(fpgaAddr);
}
}
}
Without seeing your code (I´m assuming that there´s more than the snippet you show) it´s difficult to help you.
A basic setup for a client receiving multicast datagrams would be something like this untested snippet:
UdpClient mClient = new UdpClient(3956, AddressFamily.InterNetwork);
IPAdress groupAddress = IPAddress.Parse("224.0.0.21);
mClient.JoinMulticastGroup(groupAddress);
After that you the receiving using mClient.Receive()...
Maybe this helps? Or the documentation on MSDN (https://msdn.microsoft.com/en-us/library/ekd1t784(v=vs.110).aspx).
C.
I tested the code with ffmpeg
ffmpeg.exe -i aa.mp4 -f mpeg udp://224.0.0.21:3956
int PORT = 3956;
string MULTICAST_IP = "224.0.0.21";
UdpClient udpClient = new UdpClient(PORT);
udpClient.JoinMulticastGroup(IPAddress.Parse(MULTICAST_IP));
var from = new IPEndPoint(0, 0);
var recvBuffer = udpClient.Receive(ref from);
On my desktop pc i have one gmail account.
On my laptop here i have another differenet gmail account.
My JSON file: client_secrets contain on both laptop and desktop pc same one gmail account the one on my desktop pc. But when i'm uploading the video file from my laptop it's uploading it to my gmail account on the laptop. And i want it to upload it to my gmail youtube account on my desktop pc.
First why on the laptopn it's uploading to the gmail account on the laptop and not the gmail on the desktop pc ?
Second how can i change it ? Even if on laptop and desktop pc i'm using same client_secrets file on laptopn it's uploading it to the gmail on the laptop.
another thing is that on my laptop i'm connected to my gmail account of the laptop and on the desktop pc connected to the gmail account of the desktop pc.
But i was sure that the gmail account on the JSON file set where the file will be upload to.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
using Google.GData.Client;
using Google.GData.Extensions;
using System.Reflection;
using System.IO;
using System.Threading;
using System.Net;
namespace Youtubeupload
{
public partial class Youtube_Uploader : Form
{
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
YouTubeService service;
string apiKey = "myapikey";
string FileNameToUpload = "";
string[] stringProgressReport = new string[5];
long totalBytes = 0;
DateTime dt;
public static string fileuploadedsuccess = "";
Upload upload;
public Youtube_Uploader(string filetoupload)
{
InitializeComponent();
FileNameToUpload = #"C:\Users\tester\Videos\test.mp4";
service = AuthenticateOauth(apiKey);
var videoCatagories = service.VideoCategories.List("snippet");
videoCatagories.RegionCode = "IL";
var result = videoCatagories.Execute();
MakeRequest();
backgroundWorker1.RunWorkerAsync();
}
public static string uploadstatus = "";
Video objects = null;
private void videosInsertRequest_ResponseReceived(Video obj)
{
System.Timers.Timer aTimer;
aTimer = new System.Timers.Timer();
aTimer.Elapsed += aTimer_Elapsed;
aTimer.Interval = 10000;
aTimer.Enabled = false;
uploadstatus = obj.Status.UploadStatus;
if (uploadstatus == "uploaded")
{
fileuploadedsuccess = "file uploaded successfully";
}
if (uploadstatus == "Completed")
{
fileuploadedsuccess = "completed";
}
objects = obj;
}
void aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
}
double mbSent = 0;
int percentComplete = 0;
VideoProcessingDetailsProcessingProgress vp = new VideoProcessingDetailsProcessingProgress();
private void videosInsertRequest_ProgressChanged(IUploadProgress obj)
{
ulong? ul = vp.TimeLeftMs;
stringProgressReport[1] = obj.Status.ToString();
mbSent = ((double)obj.BytesSent) / (1 << 20);
stringProgressReport[2] = mbSent.ToString();
percentComplete = (int)Math.Round(((double)obj.BytesSent) / totalBytes * 100);
stringProgressReport[3] = percentComplete.ToString();
if (obj.BytesSent != 0)
{
var currentTime = DateTime.Now;
TimeSpan diff = currentTime - dt;
double diffSeconds = (DateTime.Now - dt).TotalSeconds;
double averageSpeed = obj.BytesSent / diffSeconds;
double MBunits = ConvertBytesToMegabytes((long)averageSpeed);
stringProgressReport[4] = string.Format("{0:f2} MB/s", MBunits);
}
}
public static YouTubeService AuthenticateOauth(string apiKey)
{
try
{
YouTubeService service = new YouTubeService(new YouTubeService.Initializer()
{
ApiKey = apiKey,
ApplicationName = "YouTube Uploader",
});
return service;
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
return null;
}
}
private void MakeRequest()
{
var searchListRequest = service.Search.List("snippet");
searchListRequest.Q = "daniel lipman gta"; // Replace with your search term.
searchListRequest.RegionCode = "IL";
searchListRequest.MaxResults = 50;
// Call the search.list method to retrieve results matching the specified query term.
var searchListResponse = searchListRequest.Execute();
List<string> videos = new List<string>();
List<string> channels = new List<string>();
List<string> playlists = new List<string>();
// matching videos, channels, and playlists.
foreach (var searchResult in searchListResponse.Items)
{
switch (searchResult.Id.Kind)
{
case "youtube#video":
videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId));
break;
case "youtube#channel":
channels.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId));
break;
case "youtube#playlist":
playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId));
break;
}
}
}
static Video video = new Video();
private void UploadVideo(string FileName, string VideoTitle, string VideoDescription)
{
try
{
UserCredential credential;
using (FileStream stream = new FileStream(#"D:\C-Sharp\Youtube-Manager\Youtube-Manager\Youtube-Manager\bin\Debug\client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None,
new FileDataStore("YouTube.Auth.Store")).Result;
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
video.Snippet = new VideoSnippet();
video.Snippet.Title = VideoTitle;
video.Snippet.Description = VideoDescription;
video.Snippet.Tags = new string[] { "tag1", "tag2" };
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "public";
using (var fileStream = new FileStream(FileName, FileMode.Open))
{
const int KB = 0x400;
var minimumChunkSize = 256 * KB;
var videosInsertRequest = youtubeService.Videos.Insert(video,
"snippet,status", fileStream, "video/*");
videosInsertRequest.ProgressChanged +=
videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived +=
videosInsertRequest_ResponseReceived;
// The default chunk size is 10MB, here will use 1MB.
videosInsertRequest.ChunkSize = minimumChunkSize * 3;
dt = DateTime.Now;
videosInsertRequest.Upload();
}
}
catch (Exception errors)
{
string errorss = errors.ToString();
}
}
static double ConvertBytesToMegabytes(long bytes)
{
return (bytes / 1024f) / 1024f;
}
private void Youtube_Uploader_Load(object sender, EventArgs e)
{
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
UploadVideo(FileNameToUpload, "Gta v ps4", "Testing gta v ps4");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
int eventIndex = 0;
try
{
eventIndex = (int)e.UserState;
}
catch
{
MessageBox.Show(e.UserState == null ? "null" : e.UserState.GetType().FullName);
throw;
}
if (eventIndex == 0) // upload status.
{
label14.Text = stringProgressReport[0];
}
else if (eventIndex == 1) // obj.Status
{
label16.Text = stringProgressReport[1];
}
else if (eventIndex == 2) // mb sent so far
{
stringProgressReport[2];
label5.Text = stringProgressReport[2];
}
else if (eventIndex == 3) // percent complete
{
progressBar1.Value = Int32.Parse(stringProgressReport[3]);
}
else if (eventIndex == 4) // percent complete
{
label8.Text = stringProgressReport[4];
}
else
{
throw new Exception("Invalid event index: " + eventIndex);
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
}
}
}
What i want is that it will upload the video files to my gmail account that is on the desktop pc even if i'm uploading it from the laptop pc and there i'm connected to another gmail account.
I wrote a C# app which takes screenshot every 5 mins a saves it to server. It is timer, 2 threads, few methods(ping srv, check folder, take screenshot etc.).
As process (exe) it runs great, but I need to install it as service. I am installing it trough installutil (Framework service installer).
My problem is, that when it is installed as service, it doesn't take screenshots. Pull out some, when stopping the service. Not the right resolution and black.
I assume, that the executive code is misplaced (see main). I don't know where to put it, since I cannot have more than one main method. Please help.
Code of main application:
I've deleted some not important code.
using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
//using System.Timers;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.ComponentModel;
using System.Configuration.Install;
namespace LogWriterService
{
static class Program
{
public static int TimeO = 5; // zpoždění časovače v minutách
private static bool Online;
private static bool active = false;
public static String GetIP()
{
// ...
// returns IP like xxx.xxx.xxx.xxx
// ...
}
// Test dostupnosti serveru
public static bool PingTest()
{
// ...
// return true if server is reachable
// ...
}
/*
* Z Windows.Forms _ screenů získá obrazová data, která uloží na
* server jako ../[IP]/[současný_systémový_čas].jpg
*/
public static void ScreenShot() //Bitmap
{
Int64 CurrTime = Int64.Parse(DateTime.Now.ToString("yyyyMMddhhmmss")); //yyyyMMddhhmmss
Rectangle bounds = Rectangle.Empty;
foreach (Screen s in Screen.AllScreens)
bounds = Rectangle.Union(bounds, s.Bounds);
Bitmap screenShotBMP = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb); // PixelFormat.Format32bppArgb
Graphics screenShotGraphics = Graphics.FromImage(screenShotBMP);
screenShotGraphics.CopyFromScreen(bounds.X, bounds.Y,
0, 0, bounds.Size, CopyPixelOperation.SourceCopy);
string path = null; //"D:/TEMP/" + CurrTime + ".jpg"; // GetIP()
// Ukládání obrázků do dočasné složky a přesun, pokud se připojí
if (PingTest() == true)
{
path = "//10.0.0.10/Upload/screen/test/" + GetIP() + "/" + CurrTime + ".jpg";
string path2 = "//10.0.0.10/Upload/screen/test/" + GetIP() + "/";
Online = true;
if (Directory.Exists(path2))
{
MoveCached();
}
else
{
Console.WriteLine("Online slozka neni dostupna.");
}
} else {
Console.WriteLine("Caching .. ");
path = "C:/TEMP/" + CurrTime + ".jpg"; // "C:/TEMP/" + GetIP() + "/" + CurrTime + ".jpg"
string LPath = #"c:\TEMP";
if (!Directory.Exists(LPath))
{
DirectoryInfo di = Directory.CreateDirectory(LPath);
di.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
Console.WriteLine("Lokalni slozka neexistuje. Vytvarim ..");
}
Online = false;
}
screenShotBMP.Save(path, ImageFormat.Jpeg); // C:\\test\\test.jpg
screenShotGraphics.Dispose();
screenShotBMP.Dispose();
return; //screenShotBMP;
}
/*
* Přesune cache soubory (za dobu offline) na server
*/
public static void MoveCached()
{
// ...
// after conect, move localy saved screenshots to server
// ...
}
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
// Vytvoří událost signalizující hranici odpočtu ve
// zpětném volání časovače
AutoResetEvent autoEvent = new AutoResetEvent(false);
// Počet průchodů timeru
StatusChecker statusChecker = new StatusChecker(Timeout.Infinite); // 1440
// Vytvoří odvozeného delegáta, který vyvolá metody pro časovač
TimerCallback tcb = statusChecker.CheckStatus;
// Create a timer that signals the delegate to invoke
// CheckStatus after one second, and every 1/4 second
// thereafter.
System.Threading.Timer stateTimer = new System.Threading.Timer(tcb, autoEvent, 1000, TimeO * 1000); // TimeO * 1000 * 60 * 12 * 5, 250
// When autoEvent signals, change the period to every
// 1/2 second.
autoEvent.WaitOne(15000, false);
stateTimer.Change(0, TimeO * 1000 * 60); // TimeO * 1000 * 60
Console.WriteLine("menim poprve..");
// When autoEvent signals the second time, dispose of
// the timer.
autoEvent.WaitOne(Timeout.Infinite, false);
stateTimer.Change(0, TimeO * 1000 * 60); // TimeO * 1000 * 60
Console.WriteLine("menim podruhe..");
//stateTimer.Dispose();
// Garbage collector
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}
class StatusChecker
{
private int invokeCount;
private int maxCount;
Int64 CurrTime = Int64.Parse(DateTime.Now.ToString("hh")); // screeny od 6:00 do 16:00
public StatusChecker(int count)
{
invokeCount = 0;
maxCount = count;
}
// Tato metoda je volána delegátem časovače
public void CheckStatus(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
//if ((CurrTime > 6) & (CurrTime < 16)) // 16
//{
LogWriterService.Program.ScreenShot();
Console.WriteLine("ScreenShot ..");
//}
Console.WriteLine("{0} Kontroluji stav {1,2}.",
DateTime.Now.ToString("h:mm:ss.fff"),
(++invokeCount).ToString());
if (invokeCount == maxCount)
{
// Resetuje čítač a signál Main.
invokeCount = 0;
autoEvent.Set();
}
// Garbage collector
GC.Collect();
Console.WriteLine("Paměť uvolněna .. \n");
}
}
Code of service:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
namespace LogWriterService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
EventLog.WriteEntry("Sluzba screenshot se spustila.");
}
protected override void OnStop()
{
EventLog.WriteEntry("Sluzba screenshot se zastavila.");
}
}
}
I thing the problem may be here:
public static void CreateProcessAsUser()
{
IntPtr hToken = WindowsIdentity.GetCurrent().Token;
IntPtr hDupedToken = IntPtr.Zero;
ProcessUtility.PROCESS_INFORMATION pi = new ProcessUtility.PROCESS_INFORMATION();
try
{
ProcessUtility.SECURITY_ATTRIBUTES sa = new ProcessUtility.SECURITY_ATTRIBUTES();
sa.Length = Marshal.SizeOf(sa);
bool result = ProcessUtility.DuplicateTokenEx(
hToken,
ProcessUtility.GENERIC_ALL_ACCESS,
ref sa,
(int)ProcessUtility.SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
(int)ProcessUtility.TOKEN_TYPE.TokenPrimary,
ref hDupedToken
);
if (!result)
{
throw new ApplicationException("DuplicateTokenEx failed");
}
ProcessUtility.STARTUPINFO si = new ProcessUtility.STARTUPINFO();
si.cb = Marshal.SizeOf(si);
si.lpDesktop = String.Empty;
string folder = "D:\\test"; //Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string path = folder + "\\LogWriter\\LogWriter.exe"; // "C:/TEMP/" + GetIP() + "/" + CurrTime + ".jpg"
result = ProcessUtility.CreateProcessAsUser(
hDupedToken,
#path, // C:\Users\ToXiC\AppData\Roaming\LogWriter\LogWriter.exe
String.Empty,
ref sa, ref sa,
false, 0, IntPtr.Zero,
#"D:\\test", ref si, ref pi
);
if (!result)
{
int error = Marshal.GetLastWin32Error();
string message = String.Format("CreateProcessAsUser Error: {0}", error);
throw new ApplicationException(message);
}
}
finally
{
if (pi.hProcess != IntPtr.Zero)
ProcessUtility.CloseHandle(pi.hProcess);
if (pi.hThread != IntPtr.Zero)
ProcessUtility.CloseHandle(pi.hThread);
if (hDupedToken != IntPtr.Zero)
ProcessUtility.CloseHandle(hDupedToken);
}
}
}
The screenshots are all black I think. This happens because a windows service runs in Session 0 Isolation
One solution is to start a console application (with UI hidden) from the service after every 5 mins. The console application can take the screenshot and exit.
Some code to start a console app from windows service:
string applicationPath = ...;
private ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(applicationPath);
//set working directiory
Directory.SetCurrentDirectory(Path.GetDirectoryName(applicationPath));
psi.WorkingDirectory = Path.GetDirectoryName(applicationPath);
//psi.CreateNoWindow = false;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
//psi.UseShellExecute = false;
prcs = System.Diagnostics.Process.Start(psi);
Edit: The console application will be started in session 0. Workaround is to use the WIN API CreateProcessAsUser pinvoke call and start the console application in a user session.
Some links with code samples on how to achieve this:
http://odetocode.com/blogs/scott/archive/2004/10/28/createprocessasuser.aspx
http://blogs.msdn.com/b/alejacma/archive/2007/12/20/how-to-call-createprocesswithlogonw-createprocessasuser-in-net.aspx
http://social.msdn.microsoft.com/Forums/en-US/windowssecurity/thread/31bfa13d-982b-4b1a-bff3-2761ade5214f/
Problem was with token. I found working solution here
how-can-windows-service-execute-gui
Thank you all for helping me out of it. I understand now much more how windows service works.