Showing posts with label CSharp. Show all posts
Showing posts with label CSharp. Show all posts

Multiple CustomActionData fields

Posted by senthil | 8:02:00 AM | , , | 0 comments »

This is multiple CustomActionData field pass in SetUp  file.

 it is possible to add one or more custom screens in the setup wizard, with fields (e.g. text boxes) where the user can enter additional installation parameters.
A custom field can then be passed to a "Custom Action" class library project, to handle the user field. The image below shows how the property "ServerName" gets mapped to the EDITB1 text field:


Within the Custom Action class, the property is accessed as follows:
string targetdir = Context.Parameters["TARGETDIR"];
string stationname = Context.Parameters["STATIONNAME"];
string facility = Context.Parameters["FACILITY"];
string line = Context.Parameters["Line"];
string email = Context.Parameters["Email"];
string environment = Context.Parameters["ENVIRONMENT"];
/TARGETDIR="[TARGETDIR]\" /STATIONNAME="[STATIONNAME]" /FACILITY="[FACILITY]" /LINE="[LINE]" /EMAIL="[EMAIL]" /ENV="[ENVIRONMENT]"
Read more ...

Sample Multi thread Functionality in C#

Posted by senthil | 6:43:00 PM | , | 0 comments »

this code sample main class i created multi thread concept. already i used thread in my application while call my method continuously but there is deadlock occurred because already different thread runing there so thats what i used multi thread like this.
using System; 
using System.Threading; 
public class Test { 
static void Main() { 
ThreadStart job = new ThreadStart(ThreadJob); 
Thread thread = new Thread(job); 
thread.Start();
 for (int i=0; i < 5; i++) { 
Console.WriteLine ("Main thread: {0}", i); 
Thread.Sleep(1000); 
}
 }
 static void ThreadJob() { 
for (int i=0; i < 10; i++) {
 Console.WriteLine ("Other thread: {0}", i); 
Thread.Sleep(500); 
}
}
 } 
Read more ...

I am working in wpf application. i want to call the print method till when i click stop button. So that case i have used in thread concept while i was getting This error 'The calling thread cannot access this object because a different thread owns it' because also multiple thread run in that method so i handled this type of solution. my print method called in PrintElement like this;
public static PrintLable PrintElement()
{
    PrintLable printLable= null;
    Application.Current.Dispatcher.Invoke(
       System.Windows.Threading.DispatcherPriority.Normal, new Action(
          delegate()
          {
              PrintElement printLable = new PrintElement();
              // Initialize your PrintElement here
          }));
    return printLable;
}
Read more ...

This is all the USB device read from your local machine using C#. I am working in wpf windows application. When i want to read my system USB Device i got this sample code. This code every easy to learn and implement as you want. just copy and past in your application.
public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

  static void Main()
        {
            var usbDevices = GetUSBDevices();

            foreach (var usbDevice in usbDevices)
            {
                Console.WriteLine("Device ID: {0}, PNP Device ID: {1}, Description: {2}",
                    usbDevice.DeviceID, usbDevice.PNPDevideID, usbDevice.Description);
            }

            Console.Read();
        }


        static List<USBDeviceInfo> GetUSBDevices()
        {
            List<USBDeviceInfo> devices = new List<USBDeviceInfo>();

            ManagementObjectCollection collection;
            using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub"))
                collection = searcher.Get();

            foreach (var device in collection)
            {
                devices.Add(new USBDeviceInfo(
                (string)device.GetPropertyValue("DeviceID"),
                (string)device.GetPropertyValue("PNPDeviceID"),
                (string)device.GetPropertyValue("Description")
                ));
            }

            collection.Dispose();
            return devices;
        }
    }

    class USBDeviceInfo
    {
        public USBDeviceInfo(string deviceID, string pnpDeviceID, string description)
        {
            this.DeviceID = deviceID;
            this.PNPDeviceID = pnpDeviceID;
            this.Description = description;
        }
        public string DeviceID { get; private set; }
        public string PNPDeviceID { get; private set; }
        public string Description { get; private set; }
    } 
Read more ...

LINQ using XML data load to combobox.

Posted by senthil | 8:40:00 PM | , , | 0 comments »

To use LINQ to XML you will need to import a two of namespaces.
using System.Linq;
using System.Xml.Linq;


private void StudentsLoad()
{
  var xElem = XElement.Load(@"Student.xml");

  var students = from prod in xElem.Descendants("Student")
           orderby prod.Element("StudentName").Value
           select prod.Element("StudentName").Value;

  lstStudents.DataContext = students;
}
Read more ...

This code XML data load to gridview in wpf application. when i want to xml data load to the gridview using back end csharp code. its very simple. 1. Create DataSet object and then 2. Load the xml file to dataset using readxml property. 3. dataset value pass to the gridview itemsource.
DataSet dataSet = new DataSet();

dataSet.ReadXml(@"C:\Students\Students.xml"); 

dataGrid1.ItemsSource = dataSet.Tables[0].DefaultView; 
Read more ...

I am working in wpf application when i want to open the child window from Parent window button click. that time i am getting this solution. Just write Parent window click event method like this.
private void Button_Click(object sender, RoutedEventArgs e)
        {            
            window2 win2= new window2();
            win2.Show();
            this.Close();
        }
Read more ...

This code create an round button in wpf application using ResourceDictionary. create an xaml file like this.
<ResourceDictionary 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >

<Style x:Key="RoundButtonTemplate" TargetType="Button">
        <Setter Property="Background" Value="Brown"/>
        <Setter Property="Foreground" Value="White" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border CornerRadius="15" Background="{TemplateBinding Background}"
                                BorderThickness="1">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center">

                        </ContentPresenter>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</ResourceDictionary>
after that create and main window xaml file and then just call this RoundButtonTemplate style using Window.Resources load the GlassButton.xaml file and then call the StaticResource in main window like this.
<Window x:Class="GlassButton.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Glass Buttons" Height="228" Width="272">

    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Resources\GlassButton.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
<Grid>
 <StackPanel Orientation="Horizontal">
<Button Focusable="False"
        Style="{StaticResource RoundButtonTemplate}"
        Width="264"
       Height="90" 
       Grid.Row="0"
       Margin="0,0,0,0"
       HorizontalAlignment="Center"
       BorderBrush="#FFF"
       Name="PasswordButton"
       Click="PasswordButton_Click"> 
                                             
 </Button>
  </StackPanel>
</Grid>
</Window>
Read more ...

This is code i have an exprience when i want to create a round button in my application i have used this code. this is one way of the create round button in wpf application. if we want change the color and Radial Gradient color and also we can able to apply the Transform using opacity. its very useful i have past the following code.
<Button Width="100" Height="100">
                <Button.Template>
                    <ControlTemplate TargetType="Button">
                        <Grid>
                            <Ellipse Stroke="#5ECF5E"
                         StrokeThickness="2">
                                <Ellipse.Fill>
                                    <RadialGradientBrush GradientOrigin="0.496,1.052">
                                        <RadialGradientBrush.RelativeTransform>
                                            <TransformGroup>
                                                <ScaleTransform CenterX="0.5" CenterY="0.5" ScaleX="1.5" ScaleY="1.5"/>
                                                <TranslateTransform X="0.02" Y="0.2"/>
                                            </TransformGroup>
                                        </RadialGradientBrush.RelativeTransform>
                                        <GradientStop Offset="1" Color="#5ECF5E"/>
                                        <GradientStop Offset="0.2" Color="#FFFFFFFF"/>
                                    </RadialGradientBrush>
                                </Ellipse.Fill>
                            </Ellipse>
                            <ContentPresenter HorizontalAlignment="Center"
                                  VerticalAlignment="Center"/>
                        </Grid>
                    </ControlTemplate>
                </Button.Template>
            </Button>
another one way to create the round button.
<Button  Width="100" Height="100" Content="Abcd">
        <Button.Template>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid>
                <Ellipse Fill="Red"/>
                    <ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </Grid>
            </ControlTemplate>
        </Button.Template>
    </Button>
this code create an rectangle button with color and Radial Gradient color and also we can able to apply the Transform using opacity.
<UserControl x:Class="WindowsFormsApplication8.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="154" Width="177">
    <Grid>
        
        <Rectangle Name="rectangle1" Stroke="Black" RadiusX="10" RadiusY="10" >
        </Rectangle>
 
        <Button Name="rectangle2" Foreground="Black" Margin="3,3,3,3" >
            <Button.Background >
                <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
                    <GradientStop Color="Green" Offset="0.0" />
                    <GradientStop Color="White" Offset="0.9" />
                </LinearGradientBrush>
            </Button.Background>
        </Button>
    </Grid>
</UserControl>
Read more ...

This Warning i have experienced. When i going to change the Windows .Net Framework installer i had changed .Net Framework version 3.5 to version 4.0 that time i'm getting this issue. Its a easy to fix in this issue. Just Right click the setup solution explorer file and click the "view" and then click "Launch Conditions" the Issue founded.


and then Right Click the Launch Conditions "Properties Windows"




after that select the correct .Net Framework version





after that Right click the setup solution explorer file and select the properties




there is select on "Prerequsities" selection correct .Net Framework version.


Read more ...

When i click the button i want to assign the textbox value from another class.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        Download myDownload = new Download();
        static string textBoxString;
        public Form1()
        {
            InitializeComponent();
        }

        public static string TextboxText
        {
            set { textBoxString = value; }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            myDownload.Do();
            textBox1.Text = textBoxString;
            textBox1.Invalidate();
        }
    }

    public class Download
    {
        public void Do()
        {
            Form1.TextboxText = "My text";
        }
    }
}

An even better solution would be to define the possible interactions in an interface, and let that interface be the contract between your form and the other class. That way the class is completely decoupled from the form, and can use anyting implementing the interface (which opens the door for far easier testing):

interface IYourForm
{
    string FirstName { get; set; }
}

In your form class:


class YourFormClass : Form, IYourForm
{
    // lots of other code here

    public string FirstName
    {
        get { return firstNameTextBox.Text; }
        set { firstNameTextBox.Text = value; }
    }
}
...and the class:


class SomeClass
{
    private readonly IYourForm form;
    public SomeClass(IYourForm form)
    {
        this.form = form;
    }

    // and so on

}
Read more ...

Windows installer error

Posted by senthil | 1:26:00 PM | , | 0 comments »

When i install my wpf installer while getting error like this. any body know about this issue.

Question :-

Error 1001. Unable to get installer types in the C:\\YM\ConfigUI\ConfigUI.exe assembly. --> Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

 The description for Event ID 11001 from source MsiInstaller cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.

 If the event originated on another computer, the display information had to be saved with the event.

 The following information was included with the event: Product: YottaMark Case Labeling Solution -- Error 1001. Error 1001. Unable to get installer types in the C:\YM\ConfigUI\ConfigUI.exe assembly. --> Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
(NULL)
(NULL)
 (NULL)
(NULL)
(NULL)
 the message resource is present but the message is not found in the string/message table

Answer : -

Based on the error message in your second comment, it appears that your ConfigUI.exe assembly has been added as a Custom Action with the InstallerClass property set to true, but either no installer classes could be found in the exe or the exe could not be loaded due to missing dependencies.

You can see the list of Custom Actions by right-clicking on the installer project, selecting View and then Custom Actions.

If your exe does not can an installer class, then you can remove it from the list of custom actions.

If it does contain an installer class, then the issue is going to be missing dependencies. If fuslogvw doesn't work for you (it has always helped resolve this kind of issue for us), you can carefully review the list of references in the exe's project and compare them to what is listed in the installer project.

The other trick that we use is to examine the install directory while the error message is displayed on the screen. We can often see that DLLs are missing by doing this, usually because the path was entered incorrectly in the DLL entry within the installer project or because a condition was set incorrectly.

Read more ...

Application Manifest Schema:

Posted by senthil | 12:41:00 AM | , | 0 comments »

Application manifests are not new to the Windows Vista release. Manifests were used in Windows XP to help application developers identify such things as which versions of DLLs the application was tested with. Providing the execution level is an extension to that existing application manifest schema. The Windows Vista application manifest has been enhanced with attributes that permit developers to mark their applications with a requested execution level. The following is the format for this:
<requestedExecutionLevel
level="asInvoker|highestAvailable|requireAdministrator"
uiAccess="true|false"/>
Your application will prompt for elevation if the user is an administrator and UAC is enabled
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
  <security>
   <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
    <!-- UAC Manifest Options
      If you want to change the Windows User Account Control level replace the 
      requestedExecutionLevel node with one of the following.

    <requestedExecutionLevel level="asInvoker" uiAccess="false" />
    <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
    <requestedExecutionLevel level="highestAvailable" uiAccess="false" />

      Specifying requestedExecutionLevel node will disable file and registry virtualization.
      If you want to utilize File and Registry Virtualization for backward 
      compatibility then delete the requestedExecutionLevel node.
    -->
    <requestedExecutionLevel level="highestAvailable" uiAccess="false" />
   </requestedPrivileges>
  </security>
 </trustInfo>
Read more ...

This error i have experienced. when i going to start my application service while happened this error. Just start your service using sample application create one button click and then place this code. Its service start using ServiceController.
private void button1_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ServiceController sc = new ServiceController("YottaMark Code Dispenser");
                if ((sc.Status.Equals(ServiceControllerStatus.Stopped)))
                {
                    sc.Start();

                    MessageBox.Show("Starting the  YottaMark Code Dispenser");
                }
                MessageBox.Show("Started the YottaMark Code Dispenser");
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }
Read more ...

This code create a new gridview in wpf application. its working good.
<Grid>
        <DataGrid x:Name="MyDataGrid" x:Uid="MyDataGrid" AutoGenerateColumns="False" 
                       AlternationCount="2" SelectionMode="Single" Height="175" VerticalAlignment="Bottom" Background="White" Margin="12,0,12,12" CanUserAddRows="False" CanUserDeleteRows="False">
            <DataGrid.Columns>
                <DataGridTextColumn IsReadOnly="True" Binding="{Binding Path=Name}"
                                    Header="Name" Width="SizeToHeader" />
                <DataGridTextColumn IsReadOnly="True" Binding="{Binding Path=Email}" 
                                    Header="Email" Width="SizeToHeader" />
                <DataGridTextColumn IsReadOnly="True" Binding="{Binding Path=DOB}"
                                    Header="DOB" Width="SizeToHeader" />
                <DataGridTextColumn IsReadOnly="True" Binding="{Binding Path=Address1}"
                                    Header="Address1" Width="SizeToHeader" />
                <DataGridTextColumn IsReadOnly="True" Binding="{Binding Path=City}"
                                    Header="City" Width="SizeToHeader" />
                <DataGridTextColumn IsReadOnly="True" Binding="{Binding Path=Country}"
                                    Header="Country" Width="SizeToHeader" />
                <DataGridTemplateColumn Header="Edit">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Edit" Click="EditButton_Click" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="Delete">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Delete" Click="DeleteButton_Click" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>                    
                </DataGridTemplateColumn>               
            </DataGrid.Columns>
        </DataGrid>
        <Label Content="Printer Configuration" FontSize="16" Foreground="Blue" Height="28" HorizontalAlignment="Left" Margin="8,5,0,0" Name="Title" VerticalAlignment="Top" Width="272" />
        <Button Content="Add Printer" Height="23" HorizontalAlignment="Left" Margin="409,12,0,0" Name="btnAddPrinter" VerticalAlignment="Top" Width="141" Background="Blue" Foreground="White" FontSize="13" Click="btnAddEmploy_Click" />
    </Grid>
Just copy this code and past your wpf xaml file side of the window after that
public void LoadEmploys()
        {
string employconfigFolder="D:\\Employ.xml"
            var doc = new XmlDocument();
            doc.Load(employconfigFolder);

            XmlNodeList employ = doc.GetElementsByTagName("Employ");

            List<EmployAttribute> authors = new List<EmployAttribute>();

            foreach (XmlNode item in employ)
            {
                bool defaultPrinter = false;

                authors.Add(new PrinterAttribute()
                {
                    Name = item.Attributes["Name"].Value,
                    Email = item.Attributes["Email"].Value,
                    DOB = item.Attributes["DOB"].Value,
                    Address1 = item.Attributes["Address1"].Value,
                    City = item.Attributes["City"].Value,
                    Country = item.Attributes["Country"].Value,
                });
            }
            MyDataGrid.ItemsSource = authors;
        }



 public class EmployAttribute
        {
            public string Name { get; set; }
            public string Email { get; set; }
            public string DOB { get; set; }
            public string Address1 { get; set; }
            public bool City { get; set; }
            public bool Country { get; set; }
        }
you can call LoadEmploys() method in your window_Loaded() its working fine.
Read more ...

How to method call using Timer in c#

Posted by senthil | 12:09:00 PM | | 0 comments »

this code using the system timer we can call the method. i tried working good. its a easy way to call the method using Timer interval time. Following the sample code:
private void button1_Click(object sender, RoutedEventArgs e)
        {
            aTimer = new System.Timers.Timer(10000);

            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

            aTimer.Interval = 2000;
            aTimer.Enabled = true;

            Console.WriteLine("Press the Enter key to exit the program.");
            Console.ReadLine();
           
        }

        private static void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            aTimer.Enabled = false;
            Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
        }
Read more ...

This is code when i create my sample web application i want to create html ui in back end code so i created using string builder.
if (dt.Rows.Count > 0)
            {
                StringBuilder strb = new StringBuilder();
                strb.Append("<br/><br/>");
                strb.Append("<table border='1' cellpadding='3'>");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    strb.Append("<tr><td>");
                    strb.Append(dt.Rows[i]["Subject"].ToString());
                    strb.Append("</td>");
                    strb.Append("<td>");
                    strb.Append("<input type=\"text\" name=\"subject\" id=\"txtSubject" + i.ToString() + "\" runat=\"server\" />");
                    strb.Append("<input type=\"hidden\" name=\"hidsubject\" id=\"hidSubject" + i.ToString() + "\" runat=\"server+\" value=" + dt.Rows[i]["Subject_ID"].ToString() + "/>");
                    strb.Append("</td></tr>");
                }
                //subject = subject + "," + dt.Rows[i]["Subject_ID"].ToString();
                //hidSubject.Value = subject;
                strb.Append("</table>");
                divMark.InnerHtml = strb.ToString();
            }
Read more ...

This solution i experienced. when i develop wpf application there i used combobox. when i try to add new student that time combobox items not reloaded. because of application loading time i loaded dynamically. so i don't no how to refresh the combobox list. After that i got this solution. when u add new item while after "objwindow.ShowDialog()" refresh the combobox.
 <ComboBox Name="Student" ItemsSource="{Binding Source={StaticResource Students}, XPath=Student/@StudentName}"
SelectionChanged="{pti:DelegateCreator student_Changed}" MinWidth="150"
Style="{StaticResource RequiredComboBox}" />
if you want to refresh from the controller your combobox name declare commonly like
ComboBox _studentList = FindLogicalNode(window, STUDENT_LIST) as ComboBox;
other wise your refresh from the xaml.cs file there your can declare like "this.FindResource"
private static void studentConfig_Click(object source, RoutedEventArgs args)
        {
            StudentConfiguration objwindow = new StudentConfiguration();
            objwindow.ShowDialog();
            (_studentList.FindResource("Students") as XmlDataProvider).Refresh();            
        }
Read more ...

This code when i want to get all my system printer list and set the default printer in my application while i used this code its working good. because of i want to do bar code printer so i have used more then one printer. Its very easy to get the system printer name using this method.
using System.Text;
using System.Windows.Forms;
using System.Management;
using System.Drawing.Printing;

namespace GetPrintersName
{
    public partial class Form1 : Form
    {
        public Form1()
        {           
            InitializeComponent();
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        printer();
    }

    public static void printer() 
    {
        foreach (string printer in PrinterSettings.InstalledPrinters)
                 Console.WriteLine(printer);
 
            var printerSettings = new PrinterSettings();
            Console.WriteLine(string.Format("The default printer is: {0}",                         printerSettings.PrinterName));                 
     }
}
Read more ...

How to Add config file xml node using C#

Posted by senthil | 11:26:00 AM | | 0 comments »

This is code Add xml node in configuration file using C# method. Step:1 this is sample.config file
<TABLE>
<ROW>
    <COLUMN SOURCE="1" NAME="age" />
    <COLUMN SOURCE="3" NAME="firstname" />
    <COLUMN SOURCE="4" NAME="lastname" />
  </ROW>
</TABLE>
Step:2 I want to add xml node for my application configuration settings. so i want to add configuration setting using user interface Step:3 I created user interface one add page for add xml node. Step:4 I used this method and pass the xml value add the node.
public bool AddconfigFileXmlNode()
        {
            try
            {
                var doc = new XmlDocument();
                doc.Load("D:\\sample.config");
                 
                XmlNode profile;                
                profile = doc.SelectSingleNode("TABLE/ROW");

                XmlElement newChild = doc.CreateElement("COLUMN");

                newChild.SetAttribute("SOURCE", "4");
                newChild.SetAttribute("NAME", "lastname");  
            

                profile.AppendChild(newChild);
                doc.Save("D:\\sample.config");
            }
            catch { }
            return true;
        }
Read more ...

Related Posts Plugin for WordPress, Blogger...