‏הצגת רשומות עם תוויות תכנות #C. הצג את כל הרשומות
‏הצגת רשומות עם תוויות תכנות #C. הצג את כל הרשומות

יום שלישי, 16 ביולי 2024

c# החלפת משתמש בווינדוס / נעילת המחשב


[DllImport("user32.dll")]
public static extern void LockWorkStation();

// The function to switch user/lock the computer
void foo() { LockWorkStation(); } 
  

יום שני, 28 בנובמבר 2022

WPF - בחירת עמודות מטופס חיצוני - Column Chooser

בשביל שימוש בפקדים של telerik צריך להוסיף ref לקבצים:

Telerik.Windows.Controls
Telerik.Windows.Controls.GridView
Telerik.Windows.Controls.Input
Telerik.Windows.Data

  https://www.telerik.com/blogs/how-to-column-chooser-for-radgridview-for-silverlight-and-wpf

MainWindow.xaml

MainWindowxaml.cs

dummy class

VisisbilityToBoolConverter

ColumnChooser xaml page

ColumnChooser xaml.cs page

יום שלישי, 11 בינואר 2022

C# - Udp Server & Client

UDP Server:


  Thread trdServerUdp = 
     new Thread(new ThreadStart(serverThread));
  trdServerUdp.Start();
}

void ServerThread() {
  UdpClient server = new UdpClient(port);
  while (true) {
    IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Parse(ip), port);
    byte[] receiveBytes = server.Receive(ref remoteIpep);
    string str = Encoding.ASCII.GetString(receiveBytes);
    Console.WriteLine($"{remoteIpep}: {str}");
  }
}
  
UDP Client:


  string ip = "127.0.0.1";
  int port = 8080;

  string input;
  UdpClient client = new UdpClient();
  client.Connect(ip, port);

  byte[] data;
  while (true) {
    input = Console.ReadLine();
    if (input == "exit") break;
    data = Encoding.ASCII.GetBytes(input);
    client.Send(data, data.Length);
  }
}
  

C# - Tcp Server & Client

קוד סרבר שמחכה עד שקליינט יתחבר, ואז מקבל הודעות ומחזיר אותן אל הקליינט:

TCP Server:

void server_foo(){
  int port = 9050;
  int recv;
  byte[]data = new byte[1024];
  IPEndPoint ipep = new IPEndPoint(IPAdress.Any, port);
  Socket newsock = new Socket(AddressFamily.InterNetwork, 
                        SocketType.Stream,
                        ProtocolType.Tcp);

  newsock.Bind(ipep);
  newsock.Listen(10);

  Console.WriteLine("waiting for client...");
  Socket client = newsoc.Accept();

  IPEndPoint clientep = (IPEndPoint )client.RemoteEndPoint;
  Console.WriteLine($"Connected with {clientep.Address} at port {clientep.Port}");
  data = Encoding.ASCII.GetBytes("[CONNECTED TO SERVER]");
  client.Send(data, data.Length, SocketFlag.None);

  while (true) {
     try {
        data = new byte[1024];
        recv = client.Receive(data);
        Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
        if(recv == 0) break; // 0 == exit
        client.Send(data, recv, SocketFlags.None);
     }
     catch (Exception ex) {
        Console.WriteLine(ex.Message);
        Console.ReadLine();
        break;
     }
     finally {
        client.Close();
        newsock.Close();
     }
  }
  Console.WriteLine($"Disconnected from {clientep.Address}:{clientep.Port}");
}
  
לחץ כאן כדי להעתיק את הקוד

קוד קליינט שמנסה כל 5 שניות להתחבר:

TCP Client:

void client_foo(){
   byte[]data = new byte[1024];
   string input, stringData;
   IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ip), port);
   Socket server = new Socket(AddressFamily.InterNetwork, 
        SocketType.Stream,
        ProtocolType.Tcp);
  
  //try to connect:
  while (true) {
    try {
      server.Connect(ipep);
      Console.WriteLine("CONNECTED");
      break;
    }
    catch {
      //try to reconnect:
      Console.WriteLine("Unable to connect: " + ex.Message);
      Console.WriteLine("Trying to reconnect in:");
  
      for (int i = 1; i <= 5; i++) {
        Console.Write(i);
        Console.CursorLeft = 0;
        Thread.Sleep(1000);
      }
    }
  }

  // connected
  int recv = server.Receive(data);
  stringData = Encoding.ASCII.GetString(data, 0 ,recv);
  Console.WriteLine(stringData);
                            
  while (true) {
    input = Console.ReadLine();
    if (input == "exit") break;

    // send message
    server.Send(Encoding.ASCII.GetBytes(input));
                            
    // get message back
    data = new byte[1024];
    recv = server.Receive(data);
    stringData = Encoding.ASCII.GetString(data, 0 ,recv);
    Console.WriteLine(stringData);
  }

  //close connection to server
  Console.WriteLine("Disconnected from server");
  server.Shutdown(SocketShutdown.Both);
  server.Close();
}
לחץ כאן כדי להעתיק את הקוד

יום חמישי, 22 בנובמבר 2018

כתיבה וטעינה של קבצי XML - שפת c#

כתיבה וטעינה של קבצי XML בשפת c#
ניתן לכתוב/לקרוא XML לכל סוג של מחלקה/אובייקט, גם אם יהיה זה אובייקט בסיסי (לדוגמה string) או מחלקה שנוצרה על-ידי המשתמש:

public class SnirXmlHandler
{
   /// <summary>save xml</summary>
   public static void Save<T>(T t, string filename)
   {
      try 
      {
         XmlSerializer serializer = new XmlSerializer(typeof(T));
         using (TextWriter textWriter = new StreamWriter(filename)) 
         {
            serializer.Serialize(textWriter, t);
            textWriter.Close();
         }
      }
      catch (Exception ex) { throw; }
   }

   /// <summary>load xml file</summary>
   public static T Load<T>(string filename)
   {
      T t;
      try 
      {
         XmlSerializer deserializer = new XmlSerializer(typeof(T));
         using (TextReader textReader = new StreamReader(filename)) 
         {
            t = (T)deserializer.Deserialize(textReader);
            textReader.Close();
         }
      }
      catch (Exception ex) { throw; }
      return t;
   }
}

שימוש לדוגמה:
public class MyClass
{
    public string Name { get; set; }
    public int[] Age { get; set; }
    public MyClass2 Mc2 { get; set; }
}

public class MyClass2
{
    public int[] Num { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        MyClass myclass = new MyClass()
        {
            Name = "snir",
            Age = new int[] { 1, 2, },
            Mc2 = new MyClass2 
            {
                Num = new int[] { 10, 45 }
            }
        };
        SnirXmlHandler.Save(myclass, "snir.xml");
        MyClass mc = SnirXmlHandler.Load("snir.xml");
    }
}



קובץ XML תוצאה:
<myclass xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <age> <name>snir</name> <age> <int>1</int> <int>2</int> </age> <mc2> <num> <int>10</int> <int>45</int> </num> </mc2> </myclass>

קונטרול webbrowser לגרסת Internet Explorer הכי גבוהה

כיצד להשתמש בקונטרול C# webbrowser שישתמש בגרסת internet explorer גבוהה (ולא גרסה 7 - ברירת מחדל)

1. יש לגשת לתיקיה זו ברגיסטרי
ולשנות/להוסיף מפתח זה עבור כל תוכנה רצויה
>HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION

לערכים הבאים עבור גרסאות ie (בהתאמה לי המספר)
  • 7000 , 8888, 9000, 10000, 11000 (standards-based !DOCTYPE directives)
  • 8888, 9999, 10001, 11001 (regardless of the !DOCTYPE directive)

2. לאחר מכן, צריך להגדיר את internet explorer 11, לפי התמונות להלן:
(אפשרות זו אינה קיימת ב-internet explorer edge)
תרגום לעברית: הגדרות של תצוגת תאימות


יש אפשרות לעשות שהתוכנה תרשום את עצמה ברגיסטרי עבור שימוש בגרסה IE גבוהה יותר:
/// <summary>
/// Set IE Version to registry.
/// Options: 8888, 9999, 10001, 11001 (regardless of the !DOCTYPE directive) 
/// 7000, 8000, 9000, 10000, 11000 (standards-based !DOCTYPE directives)
/// </summary>
private void SetIeVersionInRegistery(string version)
{
   try
   {
      string key_str = @"Software\Microsoft\Internet Explorer\
                                      Main\FeatureControl
                                      \FEATURE_BROWSER_EMULATION";
      string exe_name = System.AppDomain.CurrentDomain.FriendlyName;

      RegistryKey myKey = Registry.CurrentUser.OpenSubKey(key_str, true);

      using (RegistryKey key = myKey.OpenSubKey(key_str, true))
      {
         if (myKey != null)
         {
            myKey.SetValue(exe_name, version, RegistryValueKind.DWord);
         }
      }
   }
   catch (Exception ex)
   {
      throw ex;
   }
}

יום שני, 8 באוקטובר 2018

איך לדחוף dll לתוך קובץ exe


1. במאפיינים של קובץ ה-dll שנוסף בתור reference, יש לשנות את Copy Local=False
2. את אותו קובץ שהוספנו בתור reference יש לגרור אל תוך הפרויקט ב-solution explorer
3. יש לשנות את המאפיין של קובץ זה: Build Action=Embedded
4. יש להעתיק את הקוד הבא למקום שלפני Application.Run בתוך הקוד של exe:

static class Program
{
   /// <summary>
   /// The main entry point for the application.
   /// </summary>
   [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
            Application.Run(new Form1());
        }

   private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
   {
            string dllName = args.Name.Contains(',') 
                ? args.Name.Substring(0, args.Name.IndexOf(',')) 
                : args.Name.Replace(".dll", "");
            dllName = dllName.Replace(".", "_");
            if (dllName.EndsWith("_resources"))
                return null;

            using (var stream = Assembly.GetExecutingAssembly()
                .GetManifestResourceStream(GetCurrentNamespace() + "." + dllName + ".dll"))
            {
                byte[] assemblyData = new byte[stream.Length];
                stream.Read(assemblyData, 0, assemblyData.Length);
                return Assembly.Load(assemblyData);
            }
   }

   [System.Runtime.CompilerServices.MethodImpl(MethodImplOptions.NoInlining)]
   public static string GetCurrentNamespace()
   {
            return 
    System.Reflection.Assembly.GetCallingAssembly().EntryPoint.DeclaringType.Namespace;
    }
 }

יום שני, 20 בנובמבר 2017

כיצד לתקשר בין צד c# אל צד js בתוך WebBrowser ולהיפך

פרויקט דוגמה להורדה

יש להוסיף בראש הדף (לפני המחלקה הראשונה) את הקוד הבא:
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[ComVisible(true)]
//[ComVisibleAttribute(true)]
public partial class Form1 : Form {   ... }

בחלק Load של הדף יש להגדיר את WebBrowser ולצורך הדוגמה נכתוב בתוכו את ה-html:
private void Form1_Load(object sender, EventArgs e)
{
  // 4. Set the ObjectForScripting property in the 
      // form's constructor or a Load event handler.
      // The following code uses the form class 
      // itself for the scripting object.
      // Component Object Model (COM) must be able 
      // to access the scripting object.
      // Use [ComVisible(true)] in order to make your 
      //form visible to COM 
      // (add the ComVisibleAttribute attribute to your form class).
  webBrowser1.ObjectForScripting = this;
webBrowser1.DocumentText =
  @"<html><head>
  <script>
  // the js function to call from the c# side:
  function myFoo(arg) { alert(arg); }   </script>   </head><body>
  send code to c# side: <br/>
  <input type='text' id='snir' value='snir send to c#'></input>
  <button onclick='window.external.Test(document.getElementById('snir').value)'>
  call client C# code from javscript code</button>
  </body>
  </html>";
}


נגדיר מתודה שתקבל את המיד מצד js:
// get message from the webpage's js
[ComVisible(true)]
public void Test(string arg)
{
  MessageBox.Show(argt, "C# side");
}

נגדיר מתודה שתשלח מידע אל צד js:
private void SendToWebpage()
{
  webBrowser1.Document.InvokeScript(
    "myFoo",
    new String[] { textBox1.Text }
  );
}

יום שני, 20 במרץ 2017

איך להעתיק webbrowser ל-pictureBox ומשם לקליפבורד בעזרת בחירה

איך להעתיק webbrowser ל-pictureBox ומשם לקליפבורד בעזרת בחירה

namespace WriteBraille
{
    public partial class WebbrowserToPanel : Form
    {
        public WebbrowserToPanel()  {      InitializeComponent();   }

        private void WebbrowserToPanel_Load(object sender, EventArgs e)
        {
            webBrowser1.Url = new Uri(textBox1.Text);
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
                webBrowser1.Url = new Uri(textBox1.Text);
        }

        private Point RectStartPoint;
        private Rectangle Rect = new Rectangle();
        private Brush selectionBrush = new SolidBrush(Color.FromArgb(128, 72, 145, 220));

        private void button1_Click(object sender, EventArgs e)
        {
            Control c = webBrowser1;
            Bitmap bmp = new Bitmap(c.Width, c.Height);
            c.DrawToBitmap(bmp, c.ClientRectangle);
            pictureBox1.Image = bmp;
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            // Determine the initial rectangle coordinates...
            RectStartPoint = e.Location;
            Invalidate();
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            // Draw the rectangle...
            if (pictureBox1.Image != null)
            {
                if (Rect != null && Rect.Width > 0 && Rect.Height > 0)
                {
                    e.Graphics.FillRectangle(selectionBrush, Rect);
                }
            }
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left)
                return;
            Point tempEndPoint = e.Location;
            Rect.Location = new Point(
                Math.Min(RectStartPoint.X, tempEndPoint.X),
                Math.Min(RectStartPoint.Y, tempEndPoint.Y));
            Rect.Size = new Size(
                Math.Abs(RectStartPoint.X - tempEndPoint.X),
                Math.Abs(RectStartPoint.Y - tempEndPoint.Y));
            pictureBox1.Invalidate();
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (Rect.Contains(e.Location))
                {
                    selectionBrush.Dispose();
                    //Debug.WriteLine("Right click");
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Image img = (pictureBox1.Image as Bitmap).Clone(Rect, pictureBox1.Image.PixelFormat);
            Clipboard.SetImage(img);
        }
    }
}

יום ראשון, 25 בדצמבר 2016

יצירת תיקיה זמנית בקבצי המערכת
כאשר נעשה שימוש בקבצים שנשמרים בתור Resources של התוכנה, ויש צורך להעתיק אותם אל הכונן בשביל שימוש - תמונות למשל – קיימת כמובן האפשרות ליצור תיקיית-בת בתוך תיקיית התוכנה, אך ניתן גם לעשות שימוש נוח יותר ולפרוס את הקבצים אל תוך קבצי המערכת.
ראשית יש לשים לב להגדרות הבאות לקבצים:
-          Build Action: Embedded Resources
-          Copy To Output Directory: Do Not Copy
שלבי הביצוע:
1.   יצירת תיקיה עם שם אקראי כדי לשמור בתוכה את הקבצים
// Create a temp dirctory to save the images in:
string tempDirName = Path.Combine( Path.GetTempPath(), 
                      System.Guid.NewGuid().ToString());
Directory.CreateDirectory(tempDirName);


2.  חילוץ הקבצים מתוך האסמבלי
//Extract the images from the assembly resources
System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetExecutingAssembly();
// You can get the images path in embedded resources by watching:
string file = myAssembly.GetManifestResourceNames()[0];


3. שמירת  כל קובץ (תמונה) בתיקיה הזמנית שיצרנו
using (Stream myStream = myAssembly.GetManifestResourceStream(file))
{
   using (Stream file_stream = File.Create(file)) {
      CopyStream(myStream, file_stream);
   }
}

private static void CopyStream(Stream input, Stream output)
{
   byte[] buffer = new byte[8 * 1024];
   int len;
   while ((len = input.Read(buffer, 0, buffer.Length)) > 0) {
      output.Write(buffer, 0, len);
   }
}

4. לא נשכח למחוק את הקבצים ביציאה מהתוכנה

private static void Form1_Closing(object sender, FormClosingEventArgs e)
{
   try {
      Directory.Delete(tempDirName, true);
   }
   catch(Exception ex) { MessageBox.Show(ex.Message); }
}

יום ראשון, 21 באוגוסט 2016

שינוי גודל דינמי של פנל - תכנות C#

לאחר חיפושים מצאתי פנל שניתן לשלוט על הגודל שלו - תוך כדי ריצה (כמו תיבת טקסט בוורד, עם עיצוב קצת שונה)
public class SizeablePanel : ContainerControl {
    const int WS_SIZEBOX = 0x00040000;
    protected override CreateParams CreateParams {
        get {
            CreateParams cp = base.CreateParams;
            cp.Style |= WS_SIZEBOX;
            return cp;
        }
    }
}

יש ליצור מחלקה (class) שתכיל את הקוד הזה ולמקם אותה בפרויקט.
הפקד (control) יופיע בתיבת הפקדים (Toolbox)

מקור:
http://forums.codeguru.com/showthread.php?480500-RESOLVED-User-resizable-container

יום שלישי, 3 במאי 2016

קונסול בחלון נפרד עבור תוכנת סי-שארפ

כיצד ליצור קונסול בחלון נפרד עבור תוכנת סי-שארפ 
הקוד מצורף להלן מדרג את ביצועי המחשב:

public partial class Form1 : Form
{
    // console - Allows the command line to be seen during normal execuation
    [DllImport("kernel32.dll", SetLastError = true)]
    [returnMarshalAsAttribute(UnmanagedType.Bool)]
    static extern bool AllocConsole();

    Thread trd;
    public Form1()
    {
        InitializeComponent();
        AllocConsole();
        trd = new Thread(new ThreadStart(render));
        trd.Start();
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        trd.Abort();
    }

    private void render()
    {
        int framesRendered = 0;
        long startTime = Environment.TickCount;

        while (true)
        {
            //Benchmarking
            framesRendered++;
            if (Environment.TickCount > startTime + 1000)
            {
                Console.WriteLine("Snir's Computer Benchmarking: " + framesRendered + " fps");
                framesRendered = 0;
                startTime = Environment.TickCount;
            }
        }
    }
}

יום ראשון, 3 בינואר 2016

קביעת מסך פתיחת חלון

כאשר מחוברים למחשב יותר ממסך אחד, ניתן לקבוע באיזה מסך ירוץ חלון c# שפותחים:
Form f = new Form();
f.StartPosition = FormStartPosition.Manual;
f.Location = Screen.AllScreens[0].WorkingArea.Location;
f.Show();

נשים לב שצריך לשנות את מיקום StartPosition ל-Manual (ידני).
לאחר מכן קובעים את מספר המסך ע"פ מספר.

יום שני, 2 ביוני 2014

Streams-and-IO-in-winrt

Streams and I/O
כאן אסביר שיטות עבודה עם קבצים ועם Stream (זרם של נתונים) בתכנות win-RT (תכנות Win8)

המרת משתנים ב-c#-win8

Index:
-   String to byte[]
-   Byte[] to string

-   Covert File to Byte Array
-   Save A File
-   bytes[] to filestream
    
-   Get thumbnail from video / image
-   ImageSource To BitmapImage
-   Byte[] to bitmap
-   Byte[] to Stream
-   stream to byte[]

-    stream to IrandomAccessStream
-    IRandomAccessStream to stream
-   Buffer to stream
-   stream to buffer
-   Byte[] to InMemoryRandomAccessStream or IRandomAccessStream
-   Conversion between IRandomAccessStream and FileInputStream/FileOutputStream
-   Byte[] to InMemoryRandomAccessStream or IRandomAccessStream
-   Write a file using StreamWriter
    
-   Path to StorageFile
-   Get file to storageFile
-   Get a file from media folder to a StorageFile var
-   Storagefile to string
-   byte[] to storagefile
-   StorageFile to Byte[]
-   Storagefile to IRandomAccessStream , to ImageSource (bitmap)
    
-   IRandomAccessStream to byte[]

-   Binary To String To Binary