question

MorsorMaya-0953 avatar image
0 Votes"
MorsorMaya-0953 asked RobertWatson-0327 published

How to format Code in C#

 public partial class Form1 : Form
     {
         public Form1()
         {
             InitializeComponent();
         }
    
         private void Form1_Load(object sender, EventArgs e)
         {
             // TODO: Diese Codezeile lädt Daten in die Tabelle "dsCountries.CustomersCountry". Sie können sie bei Bedarf verschieben oder entfernen
             this.customersCountryTableAdapter.Fill(this.dsCountries.CustomersCountry);
             this.customersBindingSource.Sort = "CompanyName";
             if(cboCountry.Items.Count > 1)
             {
                 cboCountry.SelectedIndex = 1;
                 cboCountry.SelectedIndex = 0;
             }
             // TODO: Diese Codezeile lädt Daten in die Tabelle "northwindCustomerDataSet.Customers". Sie können sie bei Bedarf verschieben oder entfernen.
             //this.customersTableAdapter.ClearBeforeFill = true;
             //this.customersTableAdapter.Fill(this.northwindCustomerDataSet.Customers);
    
         }
    
         private void cboCountry_SelectedIndexChanged(object sender, EventArgs e)
         {
             this.customersTableAdapter.Fill(this.northwindCustomerDataSet.Customers, (String) cboCountry.SelectedValue);
         }
    
         private void btnDeleteData_Click(object sender, EventArgs e)
         {
             //Save to db
             /*
              *
              * customersBindingSource.EndEdit();
              * customersTableAdapter.Update(northwindCustomerDataSet.Customers);
             */
             var confirmResult = MessageBox.Show("Are you sure to delete all selected items??\nYou can only restore this date with an export-file!",
                                      "Confirm Delete!!",
                                      MessageBoxButtons.YesNo);
             if (confirmResult == DialogResult.Yes)
             {
                 this.northwindCustomerDataSet.Clear();
             }
    
         }
    
         private void btnExport_Click(object sender, EventArgs e)
         {
             try
             {
                 SaveFileDialog saveDialog = new SaveFileDialog
                 {
                     Title = "Select XML File",
                     CheckPathExists = true,
    
                     DefaultExt = "xml",
                     Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*",
                     RestoreDirectory = true,
                 };
    
                 if (saveDialog.ShowDialog() == DialogResult.OK)
                 {
                     northwindCustomerDataSet.WriteXml(saveDialog.FileName, XmlWriteMode.WriteSchema);
                 }
             } catch(Exception ex) {
                 MessageBox.Show("Es ist ein Fehler aufgetreten: " + ex.Message + "\n\n" + ex.StackTrace, "Error exporting",
                     MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
              
         }
    
         private void btnImport_Click(object sender, EventArgs e)
         {
             try
             {
                 foreach (DataTable dataTable in northwindCustomerDataSet.Tables)
                     dataTable.BeginLoadData();
    
                 using (OpenFileDialog openFileDialog = new OpenFileDialog())
                 {
                     openFileDialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*";
                     openFileDialog.RestoreDirectory = true;
    
                     if (openFileDialog.ShowDialog() == DialogResult.OK)
                     {
                         northwindCustomerDataSet.ReadXml(openFileDialog.FileName);
                     }
                 }
    
                   
    
                 foreach (DataTable dataTable in northwindCustomerDataSet.Tables)
                     dataTable.EndLoadData();
                 northwindCustomerDataSet.AcceptChanges();
    
             }
             catch (Exception ex)
             {
                 MessageBox.Show("Es ist ein Fehler aufgetreten: " + ex.Message + "\n\n" + ex.StackTrace, "Error exporting",
                     MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
                
                
         }
     }


    private void openDLL_Click(object sender, EventArgs e)
         {
             OpenFileDialog dllDialog = new OpenFileDialog();
             dllDialog.Title = "Öffne Assembly-DLL";
             dllDialog.Filter = "Assembly-DLL|*.dll|Assembly-EXE|*.exe";
             if(dllDialog.ShowDialog() == DialogResult.OK)
             {
                 try {
                     typeTree.BeginUpdate();
                     Assembly assembly = Assembly.LoadFile(dllDialog.FileName);
                     assemblyName.Text = "Assembly-Name: " + assembly.GetName().Name;
                     typeTree.Nodes.Clear();
                     foreach (Type type in assembly.GetTypes())
                     {
                         Console.WriteLine(type.ToString());
                         //Add Type to tree
                         TreeNode node = new TreeNode(type.Name);
                         //Check if theire are any methods
                         if (type.GetMethods().Length != 0)
                         {
                             //Add all Methods
                             TreeNode methodsNode = new TreeNode("Methods: ");
                             foreach (MethodInfo method in type.GetMethods())
                             {
                                 TreeNode methodNode = new TreeNode(method.Name);
                                 if (method.GetParameters().Length != 0)
                                 {
                                     TreeNode paramNode = new TreeNode("Parameters: ");
                                     foreach (ParameterInfo paramInfo in method.GetParameters())
                                     {
                                         if (!paramInfo.IsOut)
                                         {
                                             paramNode.Nodes.Add(paramInfo.ParameterType.Name + " " + paramInfo.Name);
                                         }
                                     }
                                     methodNode.Nodes.Add(paramNode);
                                 }
                                 methodNode.Nodes.Add(new TreeNode("Returns: " + method.ReturnType.Name));
                                 methodsNode.Nodes.Add(methodNode);
                             }
                             node.Nodes.Add(methodsNode);
                         }
                         //Check if theire are any properties
                         if(type.GetProperties().Length != 0)
                         {
                             TreeNode memberNode = new TreeNode("Properties: ");
                             foreach (PropertyInfo prop in type.GetProperties())
                             {
                                 memberNode.Nodes.Add(prop.PropertyType.Name + " " + prop.Name);
                             }
                             node.Nodes.Add(memberNode);
    
                             typeTree.Nodes.Add(node);
                         }
                     }
                     typeTree.EndUpdate();
                 }
                 catch (BadImageFormatException)
                 {
                     MessageBox.Show("Konnte diese Datei nicht laden, da diese ein ungültiges Format hat!", "Fehler", MessageBoxButtons.OK, MessageBoxIcon.Error);
                 }
             }
         }


47701-grafik.png
47702-grafik.png


dotnet-csharp
grafik.png (11.4 KiB)
grafik.png (5.4 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

karenpayneoregon avatar image
1 Vote"
karenpayneoregon answered

Hello @MorsorMaya-0953

If the question "how to format code" means using a shortcut key in Visual Studio to format code shown you can find the shortcut under Visual Studio options, keyboard. Note that the default shortcut is different dependent on the schema used as per the second screenshot

If this is not what you mean please explain.


47711-a1.png


47721-a1a.png



a1.png (55.2 KiB)
a1a.png (9.3 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

WayneAKing-0228 avatar image
0 Votes"
WayneAKing-0228 answered

You should expend a little effort to describe what exactly
you are asking,

We cannot infer from a bunch of code what you expect as an
answer to a question only asked vaguely in the thread subject.

Taking that subject: "How to format Code in C#"
literally and at face value, look at the menus in the IDE.

Under Edit->Advanced you should see two menu items:

"Format Document" and "Format Selection".

  • Wayne

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

NickJefferson-0029 avatar image
0 Votes"
NickJefferson-0029 answered NickJefferson-0029 published

 ************************Server*************************
 using System;
 ``using System.Data;
     using System.Data.SqlClient;
        
     namespace Server
     {
         public class RemoteServer : MarshalByRefObject
         {
             public DataSet GetDataSet()
             {
                 DataSet ds = new DataSet();
                 ds.ReadXml("D:/4.Klasse/POSE/C#/Remoting/Server/Server/cd_catalog.xml");
                 return ds;
             }
         }
     }
    
    
 using Server;
 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Runtime.Remoting.Channels;
 using System.Runtime.Remoting.Channels.Http;
 using System.Text;
 using System.Threading.Tasks;
 using System.Windows.Forms;
    
    
 ******************************************Client*****************************
    
    
 namespace Client
 {
     public partial class Form1 : Form
     {
         public Form1()
         {
             InitializeComponent();
    
             HttpChannel ch = new HttpChannel(8088);
             ChannelServices.RegisterChannel(ch);
    
             try
             {
                 RemoteServer serverdata = (RemoteServer)Activator.GetObject(typeof(RemoteServer), "http://localhost:8086/Server/RemoteServer.soap");
    
                 DataSet ds = serverdata.GetDataSet();
    
                 dataGridView1.DataSource = ds;
                 dataGridView1.DataMember = ds.Tables[0].TableName;
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.ToString());
             }
         }
    
     }
 }
    
 *****************************************Config***************************************
 <?xml version="1.0" encoding="utf-8" ?>
 <configuration>
   <startup>
     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
   </startup>
   <system.runtime.remoting>
     <application name="Server">
       <service>
         <wellknown mode="Singleton"
                 type="Server.RemoteServer, Server"
                 objectUri="RemoteServer.soap"/>
       </service>
       <channels>
         <channel ref="http" port="8086"/>
       </channels>
     </application>
   </system.runtime.remoting>
 </configuration>
    
 using System;
 using System.Runtime.Remoting;
 using System.IO;
 using System.Reflection;
    
    
 *************************************TestApp**************************************************
 namespace Server
 {
     class TestApp
     {
         static void Main(string[] args)
         {
             // Get the Application Directory
             string strAppDir = Path.GetDirectoryName(
                 Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
    
             // Use the Configuration File to configure and start the Server
             string strConfigFile = strAppDir + "\\Server.exe.config";
             RemotingConfiguration.Configure(strConfigFile);
    
             // Keep the Server alive to respond to requests
             Console.WriteLine("Server running and waiting for requests ...");
             Console.WriteLine("Press [ENTER] to shut down Server");
             Console.ReadLine();
         }
     }
 }




5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

NickJefferson-0029 avatar image
0 Votes"
NickJefferson-0029 answered

62227-formatted.png



formatted.png (73.0 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

SamuelAnderson-7453 avatar image
0 Votes"
SamuelAnderson-7453 answered

 private void axInkEdit2_Change(object sender, EventArgs e)
         {
             string text = axInkEdit2.Text;
             int number = 0;
             bool success = Int32.TryParse(text, out number);
             if(success)
             axInkEdit2.Font = new Font("Microsoft Sans Serif", number); 
             else
             Form1.ActiveForm.BackColor = (Color)new ColorConverter().ConvertFromString(text);
    
             Console.WriteLine(number);
               
             number = 0;
             success = false;
             axInkEdit2.ResetText();
         }



5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

SamuelAnderson-7453 avatar image
0 Votes"
SamuelAnderson-7453 answered
 namespace RegistrationANDLogin
 {
     /// <summary>
     /// Summary description for Registration
     /// </summary>
     [WebService(Namespace = "http://tempuri.org/")]
     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
     [System.ComponentModel.ToolboxItem(false)]
     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
     // [System.Web.Script.Services.ScriptService]
     public class Registration : System.Web.Services.WebService
     {
         static string connectionString = @"Server=XISAN-PC\SQLEXPRESS;Database=serverDatabase;user id=sa; password=moveon";
         SqlConnection connection = new SqlConnection(connectionString);
    
         [WebMethod]
         public String RegistrationFunction(string Username,string Password,string ConfirmPassword,string ContactNumber,string IMEINumber)
         {
             //string connectionString = @"Server=XISAN-PC\SQLEXPRESS;Database=serverDatabase;user id=sa; password=moveon";
             //SqlConnection connection = new SqlConnection(connectionString);
             try
             {
                 string usrname_count = "select count(*) from registrationTable where userName = '"+Username+"'";
    
                 connection.Open();
                 SqlCommand cmd1 = new SqlCommand(usrname_count, connection);
                 int i = int.Parse(cmd1.ExecuteScalar().ToString());
                 if (i == 1)
                 {
                     return "age thekei ache";
                 }
                 else
                 {
                     string str = "insert into registrationTable values('" + Username + "','" + Password + "','" + ConfirmPassword + "','" + ContactNumber + "','" + IMEINumber + "','"+"0"+"','"+"0"+"')";
                     SqlCommand cmd = new SqlCommand(str, connection);
                     cmd.ExecuteNonQuery();
                     return "age theke nai";
                 }
             }
             catch(Exception exp)
             {
                 return exp.ToString();
             }
             finally
             {
                 connection.Close();
             }
             return "ajaira";
         }
         [WebMethod]
         public string LoginFunction(string Username, string Password)
         {
             //string connectionString = @"Server=XISAN-PC\SQLEXPRESS;Database=serverDatabase;user id=sa; password=moveon";
             //SqlConnection connection = new SqlConnection(connectionString);
             try
             {
                 connection.Open();
                 string count = "select count(*) from registrationTable where userName = '" + Username + "'";
                 SqlCommand cmd = new SqlCommand(count, connection);
                 int i = int.Parse(cmd.ExecuteScalar().ToString());
                 if (i == 1)
                 {
                     string search_pass = "select password from registrationTable where username = '"+Username+"'";
                     SqlCommand cmd1 = new SqlCommand(search_pass, connection);
                     string password = cmd1.ExecuteScalar().ToString().Replace(" ", "");
                     if (password == Password)
                     {
                         return "Login successfull";
                     }
                     else
                     {
                         return "Password is not correct";
                     }
                 }
                 else
                 {
                     return "Username is not correct";
                 }
             }
             catch(Exception exp)
             {
                 return exp.ToString();
             }
             finally
             {
                 connection.Close();
             }
         }
    
         [WebMethod]
         public string LangitudeAndLattitude(string Username, string Langitude, string Lattitude)
         {
             try
             {
                 connection.Open();
    
                 string str1 = "update registrationTable set latitude ='" + Lattitude + "' where userName = '" + Username + "'";
                 SqlCommand cmd1 = new SqlCommand(str1, connection);
                 cmd1.ExecuteNonQuery();
    
    
                 string str = "update registrationTable set longitude ='"+Langitude+"' where userName = '"+Username+"'";
                 SqlCommand cmd = new SqlCommand(str, connection);
                 cmd.ExecuteNonQuery();
    
                    
             }
             catch (Exception exp)
             {
                 return exp.ToString();
             }
             finally
             {
                 connection.Close();
             }
             return "something";
         }
     }
 }


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

CBergmann-4877 avatar image
0 Votes"
CBergmann-4877 answered

-----------Java

 @Override
 public synchronized Restlet createInboundRoot() {
     Router router = new Router(getContext());
    
     router.attach("/logbookentries/nextid", LogBookIDRessource.class);
    
     router.attach("/employees/{id}", EmployeeRessource.class ); //http://localhost:8111/
     router.attach("/employees", EmployeesRessource.class );
     router.attach("/employees/", EmployeesRessource.class );
    
     router.attach("/employees/{id}/logbookentries", EmployeeLogBookEntries.class );
     router.attach("/logbookentries/", LogBookEntriesRessource.class);
     router.attach("/logbookentries", LogBookEntriesRessource.class);
     router.attach("/logbookentries/{id}", LogBookEntryRessource.class);
     router.attachDefault(BaseServiceRessource.class);
    
     return router;
 }
    
 try {
     Component component = new Component();
     component.getServers().add(Protocol.HTTP, 8111);
     component.getDefaultHost().attach("/api", new RestletApplication());
     component.start();
     //new Server(Protocol.HTTP, 21524, new RestletApplication()).start();
 } catch (Exception e) {
     e.printStackTrace();
 }


 <?xml version="1.0" encoding="utf-8" ?>
 <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
     <xs:element name="test">
         <xs:complexType>
             <xs:sequence>
                 <xs:element type="xs:int" name="id"></xs:element>
                 <xs:element type="xs:string" name="name"></xs:element>
                 <xs:element type="xs:long" name="testlong"></xs:element>
             </xs:sequence>
         </xs:complexType>
     </xs:element>
     <xs:element name="testMore">
         <xs:complexType>
             <xs:sequence>
                 <xs:element type="xs:int" name="id"></xs:element>
                 <xs:element ref="test" maxOccurs="unbounded"></xs:element>
             </xs:sequence>
         </xs:complexType>
     </xs:element>
 </xs:schema>


 throw new ResourceException(418, "Could not find Employee! (Wrong ID)");
 doError(Status.CLIENT_ERROR_BAD_REQUEST, "ID must be an Integer!");
    
 ClientResource resource;
 resource = new ClientResource("http://localhost:8111/api/");
 baseService = resource.wrap(IBaseService.class);
    
 @WebServlet(urlPatterns = "/employees")
 public class EmployeesServlet extends HttpServlet {
    
    
     @SneakyThrows
     @Override
     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         doPostAndGet(req, resp);
     }
    
     @SneakyThrows
     @Override
     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         doPostAndGet(req, resp);
     }
    
    
     @SneakyThrows
     protected void doPostAndGet(HttpServletRequest req, HttpServletResponse resp) throws JAXBException {
         User user = (User) req.getSession().getAttribute("user");
         if(user == null || user.getUserID() == null) {
             req.getSession().setAttribute("errorMessage", "No user selected!");
             resp.sendRedirect("index.jsp");
             return;
         }
    
         String id;
         if((id = req.getParameter("deleteID")) != null) {
             try {
                 int userID = Integer.valueOf(id);
                 TimeTrackingRestClient.getInstance().getEmployeeService(userID).deleteRestCall();
             } catch (Exception e) {
                 req.setAttribute("error", "Could not delete User. Invalid ID!");
             }
         }
         if(req.getParameter("add") != null) {
             TimeTrackingRestClient.getInstance().getEmployeesService().addElement(new Employee());
         }
         if((id = req.getParameter("saveID")) != null) {
             try {
                 int userID = Integer.valueOf(id);
    
                 String userIDField = req.getParameter("idField");
                 String firstname = req.getParameter("firstnameField");
                 String lastName = req.getParameter("lastnameField");
                 String date = req.getParameter("birthday");
                 Employee employee = new Employee();
                 employee.setEmployeeID(new BigInteger(id));
                 employee.setFirstName(firstname);
                 employee.setLastName(lastName);
    
                 if(!date.trim().isEmpty() && date.split("-").length == 3) {
                     employee.setDateOfBirth(HtmlDateConverter.convertFromHtmlValue(date));
                 }
                 TimeTrackingRestClient.getInstance().getEmployeeService(userID).putRestCall(employee);
             } catch (Exception e) {
                 req.setAttribute("error", "Could not save User.");
             }
         }
         req.setAttribute("employees", TimeTrackingRestClient.getInstance().getEmployeesService().getEmployees());
         req.getRequestDispatcher("employees.jsp").forward(req,resp );
     }
    
     @Override
     public void init() throws ServletException {
         super.init();
     }
 }
    
    
    
 <jsp:useBean id="testmore" class="package.TestMore" scope="request"></jsp:useBean>
 <% if (BOOL) { %>
     ...
 <% }%>
    
 <%=e.getEmployeeID()%>
 ${employee.employeeID}

-----------Java End
-----------Load Images

 private const string DIR_NAME = "/imgs/";
    
 List<MyImage> images;
    
 //Init the List
 public Service1()
 {
     string dirPath = AppDomain.CurrentDomain.BaseDirectory + DIR_NAME;
     this.images = SearchFolderRec(dirPath);
            
 }
    
 public List<MyImage> SearchFolderRec(string path)
 {
     if (!Directory.Exists(path))
     {
         return new List<MyImage>();
     }
     List<MyImage> results = new List<MyImage>();
     //Get all files in dir
     string[] files = Directory.GetFiles(path);
     foreach(string file in files)
     {
         //Just check if it is a valid image
         try {
    
             Image img = Image.FromFile(file);
    
             results.Add(new MyImage(file, Path.GetFileNameWithoutExtension(file)));
         } catch (Exception e) {
    
         }
     }
     //Open all dirs (Can be comment out if you don't want it)
     string[] dirs = Directory.GetDirectories(path);
     foreach(string nextDir in dirs)
     {
         results.AddRange(SearchFolderRec(nextDir));
     }
    
     return results;
 }
    
 public byte[] getImage(string name)
 {
     MyImage rightImage = images.Find((image) => { return image.Name == name; });
     if (rightImage == null)
         return new byte[0];
    
     //Load image
     string path = AppDomain.CurrentDomain.BaseDirectory;
     Bitmap image1 = (Bitmap)Image.FromFile(rightImage.ImagePath, true);
     MemoryStream ms = new MemoryStream();
     image1.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
     byte[] imgData = ms.ToArray();
     //Return image
     return imgData;
 }
    
 public List<MyImage> getImageList()
 {
     return images;
 }

-----------Load CSV

 public string getCSV()
 {
     string[] lines = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + "test.csv");
     string rest = "";
     foreach(string line in lines)
     {
         foreach(string parts in line.Split(';'))
         {
             rest += parts+ "\t";
         }
    
         rest += "\n";
     }
     return rest;
 }

-----------Example Linq Csv

 public class Person
 {
     public int Id { get; set; }
    
     public string Name { get; set; }
    
     public int Age { get; set; }
    
     public Gender Gender { get; set; }
 }
    
 public enum Gender
 {
     Male,
     Female
 }
    
 Then create a Service that can load Data from the File:
    
 public static class PersonService
 {
     public static List<Person> ReadFile(string filepath)
     {
         var lines = File.ReadAllLines(filepath);
    
         var data = from l in lines.Skip(1)
                    let split = l.Split(';')
                    select new Person
                    {
                        Id = int.Parse(split[0]),
                        Name = split[1],
                        Age = int.Parse(split[2]),
                        Gender = (Gender)Enum.Parse(typeof(Gender), split[3])
                    };
    
         return data.ToList();
     }
 }
    
 And then use that to populate the UI:
    
 public partial class Window2 : Window
 {
     public Window2()
     {
         InitializeComponent();
    
         DataContext = PersonService.ReadFile(@"c:\file.csv");
     }
 }
    
 XAML:
    
 <Window x:Class="WpfApplication14.Window2"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         Title="Window2" Height="300" Width="300">
     <DataGrid AutoGenerateColumns="True"
               ItemsSource="{Binding}"/>
 </Window>

-----------DataBiding Examples

 <Window x:Class="TwoWayBinding.Window1"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     Title="Window1" Height="300" Width="300">
     <Grid Height="54" Width="165">
         <TextBox  Name="textBox" Margin="0,-77,0,0" Height="23" VerticalAlignment="Top"
                 Text ="{Binding ElementName=listBox,
                         Path=SelectedItem.Content,
                         Mode=TwoWay,
                         UpdateSourceTrigger=PropertyChanged}"
                 Background="{Binding ElementName=listBox, Path=SelectedItem.Content, Mode=OneWay}">
         </TextBox>
       <ListBox Name="listBox" >
             <ListBoxItem Content="Green"/>
             <ListBoxItem  Content="Yellow" IsSelected="True"/>
             <ListBoxItem Content="Orange" />
         </ListBox>
     </Grid>
 </Window>

-----------Databinding easy

 <TextBox Name="txtValue" />
         <WrapPanel Margin="0,10">
             <TextBlock Text="Value: " FontWeight="Bold" />
             <TextBlock Text="{Binding Path=Text, ElementName=txtValue}" />
         </WrapPanel>

-----------XmlSerializer
https://docs.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlserializer.deserialize?view=net-5.0
-----------XML-Docs

 <Window x:Class="DefaultApp.MainWindow"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 Title="MainWindow" Height="350" Width="525">
 <Grid>
 <DataGrid AutoGenerateColumns="False" Height="254" HorizontalAlignment="Left" Margin="12,12,0,0" Name="dataGrid" VerticalAlignment="Top" Width="479" ItemsSource="{Binding Path=Elements[Person]}" >
 <DataGrid.Columns>
 <DataGridTextColumn Header="Name" Binding="{Binding Path=Element[Name].Value}" />
 <DataGridTextColumn Header="Surname" Binding="{Binding Path=Element[Surname].Value}"/>
 <DataGridTextColumn Header="Phone no" Binding="{Binding Path=Element[PhoneNo].Value}"/>
 <DataGridTextColumn Header="Country" Binding="{Binding Path=Element[Country].Value}"/>
 </DataGrid.Columns>
 </DataGrid>
 </Grid>
 </Window>
    
 using System.Windows;
     
 namespace DefaultApp
 {
     using System.Xml.Linq;
     
     /// <summary>
     /// Interaction logic for MainWindow.xaml
     /// </summary>
     public partial class MainWindow : Window
     {
         public MainWindow()
         {
             InitializeComponent();
         }
     
         private void RefreshButtonClick(object sender, RoutedEventArgs e)
         {
             var peopleList =
                 XElement.Load(/*@"path to your xml file"*/);
  this.dataGrid.DataContext = peopleList;
  }
  }
 }
 -----------Obersavable Collection
 public class TrulyObservableCollection<T> : ObservableCollection<T>
         where T : INotifyPropertyChanged
 {
     public TrulyObservableCollection()
     {
         CollectionChanged += FullObservableCollectionCollectionChanged;
     }
    
     public TrulyObservableCollection(IEnumerable<T> pItems) : this()
     {
         foreach (var item in pItems)
         {
             this.Add(item);
         }
     }
    
     private void FullObservableCollectionCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
     {
         if (e.NewItems != null)
         {
             foreach (Object item in e.NewItems)
             {
                 ((INotifyPropertyChanged)item).PropertyChanged += ItemPropertyChanged;
             }
         }
         if (e.OldItems != null)
         {
             foreach (Object item in e.OldItems)
             {
                 ((INotifyPropertyChanged)item).PropertyChanged -= ItemPropertyChanged;
             }
         }
     }
    
     private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
     {
         NotifyCollectionChangedEventArgs args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, sender, sender, IndexOf((T)sender));
         OnCollectionChanged(args);
     }
 }
  public class Person : INotifyPropertyChanged
 {
     private string name;
     private string surname;
     private string phoneNo;
     private string country;
    
     public event PropertyChangedEventHandler PropertyChanged;
    
     [XmlElement("Name")]
     public string Name
     {
         get
         {
             return this.name;
         }
    
         set
         {
             if (value != this.name)
             {
                 this.name = value;
                 OnPropertyChanged();
             }
         }
     }
    
     [XmlElement("Surname")]
     public string Surname
     {
         get
         {
             return this.surname;
         }
    
         set
         {
             if (value != this.surname)
             {
                 this.surname = value;
                 OnPropertyChanged();
             }
         }
     }
    
     [XmlElement("PhoneNo")]
     public string PhoneNo
     {
         get
         {
             return this.phoneNo;
         }
    
         set
         {
             if (value != this.phoneNo)
             {
                 this.phoneNo = value;
                 OnPropertyChanged();
             }
         }
     }
    
     [XmlElement("Country")]
     public string Country
     {
         get
         {
             return this.country;
         }
    
         set
         {
             if (value != this.country)
             {
                 this.country = value;
                 OnPropertyChanged();
             }
         }
     }
    
    
     // Create the OnPropertyChanged method to raise the event
     // The calling member's name will be used as the parameter.
     protected void OnPropertyChanged([CallerMemberName] string name = null)
     {
         PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
     }
     public Person(string name, string surname, string phoneNo, string country)
     {
         Name = name;
         Surname = surname;
         PhoneNo = phoneNo;
         Country = country;
     }
    
     public Person()
     {
     }
 }
 <DataGrid 
     AutoGenerateColumns="False" 
     Height="254" 
     HorizontalAlignment="Left" 
     Margin="12,12,0,0" 
     Name="personGrid" 
     VerticalAlignment="Top" 
     Width="479"
     SelectionMode="Single"
     CanUserAddRows="True"
     CanUserDeleteRows="True"
     ItemsSource="{Binding}">
     <DataGrid.Columns>
         <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" />
         <DataGridTextColumn Header="Surname" Binding="{Binding Path=Surname}"/>
         <DataGridTextColumn Header="Phone no" Binding="{Binding Path=PhoneNo}"/>
         <DataGridTextColumn Header="Country" Binding="{Binding Path=Country}"/>
     </DataGrid.Columns>
 </DataGrid>
    
 public TrulyObservableCollection<Person> People { get; set; }
 public ObservableCollection<string> PeopleNameSelector { get; set; }
 People = new TrulyObservableCollection<Person>();
 personGrid.DataContext = People;



















5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

RobertWatson-0327 avatar image
0 Votes"
RobertWatson-0327 answered RobertWatson-0327 published
 public static void marshal(String fileName, Employees emp) {
         File file = new File(fileName);
    
         try {
             JAXBContext context = JAXBContext.newInstance(Employees.class);
             Marshaller marshaller = context.createMarshaller();
    
             marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
             marshaller.marshal(emp, file);
             System.out.println("Successfully generated file.");
         } catch (JAXBException e) {
             e.printStackTrace();
         }
     }
    
     public static Employees unmarshal(String fileName) {
         File file = new File(fileName);
    
         try {
             JAXBContext context = JAXBContext.newInstance(Employees.class);
             Unmarshaller unmarshaller = context.createUnmarshaller();
    
             return (Employees) unmarshaller.unmarshal(file);
         } catch (JAXBException e) {
             e.printStackTrace();
         }
         return null;
     }
 public class EmployeeApp extends Application {
     @Override
     public Restlet createInboundRoot(){
         Router r = new Router();
         r.attach("/employees",EmployeesServerRessource.class);
         r.attach("/employees/{id}",EmployeeServerRessource.class);
         r.attach("/logbookentries",LogBookEntriesServerRessource.class);
         r.attach("/logbookentries/{id}",LogBookEntryServerRessource.class);
         r.attach("/employees/{id}/logbookentries",EmployeeLogBookEntryServerRessource.class);
         return r;
     }
 }
 public class EmployeeServer {
     public static void main(String[] args) throws Exception {
         Component component = new Component();
         component.getServers().add(Protocol.HTTP,8888);
         component.getDefaultHost().attach("/api",new EmployeeApp());
         component.start();
    
     }
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.