C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,962 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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);
}
}
}
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";
}
}
}
-----------
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://learn.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;
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();
}