Quantcast
Channel: Visual C# forum
Viewing all 31927 articles
Browse latest View live

C#: How to convert Keyboard.key (Unicode char as number) into correct char?

$
0
0

Our application uses barcode scanner.

when scanning a barcode and convert Keyboard.key (as ushort with value 16, it represents char ':') by using

1)(char)(Keyboard.key)

2) or Convert.ToChar(Keyboard.key),

both way convert into symbol '+'.

How to convert into ':'?

What is a correct way to convert Keyboard.key as ushort into correct char? Thx!


JaneC






Is there a design pattern for splitting up files into smaller files?

$
0
0

I am developing a project where I have to load very large files (upto 50 MB). Currently I am loading these files completely into (consecutive) memory. This has the advantage that I can very easily change bytes at certain locations, because I do not know the structure of all bytes.

However, my intention is to also change the structure, e.g. removing/adding 'chunks'. Now I have the idea to remove the 'known' parts out of it, store them in classes with a data chunk only containing those parts and make a sort of reference list to those chunks.

E.g.:

Original file:

  • Header
  • ChunkA 1
  • ChunkA 2
  • Intermediate
  • ChunkB 1
  • Footer

The result will be:

ChunkA 1 and ChunkA 2 instance. ChunkB 1 instance

'File' instance and a reference with base offsets + reference to all chunks.

At the end I have to 'recreate' or write the original file (with changes) back.

Is this in general a good idea or is there some design pattern helping me in this?

WPF AccessKeyManager annoying sound

$
0
0

I'm adding now some shortcut keys to my wpf application. I have one ComboBox and I want each item to be able to have a shortcut key. Now, I do this with custom class deriving from ComboBoxItem and having a property ShortcutKey, which register the access key via AccessKeyManager on set.

public class ComboBoxItemLanguage : ComboBoxItem
{
    private string _key;
    private ComboBox parent;

    public string LanguageCode
    {
        get; set;
    }

    public string ShortcutKey
    {
        get
        {
            return _key;
        }
        set
        {
            _key = value;

            AccessKeyManager.Register(value, this);
            AccessKeyManager.AddAccessKeyPressedHandler(this, AccessKeyPressedEventHandler);
        }
    }

    public ComboBoxItemLanguage()
    {

    }

    private void AccessKeyPressedEventHandler(object sender, AccessKeyPressedEventArgs e)
    {
        parent = parent ?? ItemsControl.ItemsControlFromItemContainer(this) as ComboBox; // gets the parent ComboBox
        parent.SelectedIndex = parent.Items.IndexOf(this);

        e.Handled = true;
    }
}

Then, in XAML it looks like this:

<ComboBox x:Name="cb_lang" SelectedValuePath="LanguageCode" SelectedValue="{Binding InputLanguage, UpdateSourceTrigger=PropertyChanged, Mode=OneWayToSource}"><local:ComboBoxItemLanguage Content="English" LanguageCode="en" ShortcutKey="e"/></ComboBox>
But always when I press the alt+something shortcut key, the annoying Windows beep sound is played as it had not been registered. Anyone knows, how to get rid of it? Or should I use commands? (But I think this solution is more re-usable).


What's wrong in my code???

$
0
0

Hi Everyone..

   Can any one tell me whats wrong in my code...I would like to store images into my database,but I'm not able to do that.

private void btnaddinfo_Click(object sender, EventArgs e)
        {
            string scn = ConfigurationManager.ConnectionStrings["Myconn"].ConnectionString;
            using (SqlConnection cn = new SqlConnection(scn))
                {
                using (SqlCommand cmd = new SqlCommand("SP_Info", cn))
                {
                    try
                    { 
                        byte[] img = null;
                        FileStream fs = new FileStream(imageloc, FileMode.Open, FileAccess.Read);
                        BinaryReader br = new BinaryReader(fs);
                        img = br.ReadBytes((int)fs.Length);     

                        cmd.CommandType = CommandType.StoredProcedure;

                        cmd.Parameters.Add("@Hp_Number", SqlDbType.NVarChar, 50).Value = tbhpnum.Text; ;
                        cmd.Parameters.Add("@Customer_Name", SqlDbType.VarChar, 50).Value = tbcusnam.Text;
                        cmd.Parameters.Add("@Customer_Contact_Number", SqlDbType.NVarChar, 15).Value = tbcusmblno.Text;
                        cmd.Parameters.Add("@Guarantor_Name", SqlDbType.VarChar, 50).Value = tbguanam.Text;
                        cmd.Parameters.Add("@Guarantor_Contact_Number", SqlDbType.NVarChar, 15).Value = tbguamblno.Text;
                        cmd.Parameters.Add("@Hp_Date", SqlDbType.DateTime).Value = DateTime.Parse(tbhpdat.Text);
                        cmd.Parameters.Add("@Customer_Address", SqlDbType.NVarChar, Max).Value = tbcusadd.Text;
                        cmd.Parameters.Add("@Vehicle", SqlDbType.VarChar, 50).Value = tbveh.SelectedItem.ToString();
                        cmd.Parameters.Add("@Vehicle_Model", SqlDbType.VarChar, 50).Value = tbvehmod.SelectedItem.ToString();
                        cmd.Parameters.Add("@Vehicle_Number", SqlDbType.NVarChar, 50).Value = tbvehnum.Text;
                        cmd.Parameters.Add("@Chasis_Number", SqlDbType.NVarChar, 50).Value = tbchanum.Text;
                        cmd.Parameters.Add("@Engine_Number", SqlDbType.NVarChar, 50).Value = tbengnum.Text;
                        cmd.Parameters.Add("@FC_Date", SqlDbType.DateTime).Value = DateTime.Parse(tbfcdat.Text);
                        cmd.Parameters.Add("@Insurance_Date", SqlDbType.DateTime).Value = DateTime.Parse(tbinsdat.Text);
                        cmd.Parameters.Add("@Insurance_Amount", SqlDbType.Int).Value = Convert.ToInt32(tbinsamt.Text);
                        cmd.Parameters.Add("@Paid_Amount", SqlDbType.Int).Value = Convert.ToInt32(tbpaiamt.Text);
                        cmd.Parameters.Add("@Vehicle_Pic", SqlDbType.Image).Value = boxvehpic;
                        cmd.Parameters.Add("@Customer_Pic", SqlDbType.Image).Value = boxcuspic;
                        cmd.Parameters.Add("@Guarantor_Pic", SqlDbType.Image).Value = boxguapic;
                        cmd.Parameters.Add("@Documents_Pic", SqlDbType.Image).Value = boxdocpic;
                        cmd.Parameters.Add("@Insurance_Pic", SqlDbType.Image).Value = boxinspic;

                        if (cn.State != ConnectionState.Open)
                            cn.Open();
                        int count = cmd.ExecuteNonQuery();
                        if (count == 1)
                        {
                            MessageBox.Show(count.ToString() + "Record(s) Saved.");
                        }
                        else
                        {
                            MessageBox.Show("Please correct the error which you have entered and then click on addinformation button");
                        }
                    }
                    catch (SqlException ex)
                    {
                        MessageBox.Show(ex.ToString());

                    }
                    finally
                    {
                        if (cn.State == ConnectionState.Open)
                            cn.Close();
                    }
                }
            }
        }


Thanks & Regards RAJENDRAN M

Single instance code, how to access the initial instance?

$
0
0

I have the 2 following pieces of code.

This part is in Program.cs

    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Boolean createdNew = true;

            using (Mutex mu = new Mutex(true, "guid here", out createdNew))
            {
                if (createdNew) {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new MainForm());
                } else {
                    String[] args = Environment.GetCommandLineArgs();
                    if (args.Length > 1)
                        MainForm.AddFile(args[1]);
                }
            }
        }
    }

These pieces are in MainForm

        static List<String> FileNames = new List<String>();

        public static void AddFile(String path)
        {
            FileNames.Add(path);
        }

There is a loop inside the main working section that is formed:

        for (Int32 iFileIndex = 0; iFileIndex < FileNames.Count; iFileIndex++) {
             // Doing other stuff here
        }

The bit inside Program.cs seems to be working as I don't get multiple instances running.

What I haven't figured out how to do yet is to get the instance that was first executed so I can send the filename to it through the static method.

What methods of getting access are available?  I'd prefer to not use interop if possible.

Andy

WSDoAllReceiver: Request does not contain required Security header

$
0
0

Hi

I'he the follow code:

var client = new ProspectaWSClient();

            //client.ClientCredentials.Windows.AllowNtlm = true;
            client.ClientCredentials.UserName.UserName = "316700";
            client.ClientCredentials.UserName.Password = "P71apr";
            client.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(@"C:\Users\Developer-4\Desktop\Certificados Prospecta\BanlineaClientCert.cer");

            try
            {
                //client.Open();
                client.consultaProspecta("2058", "54000000", "1");
            }
            catch (Exception)
            {
                throw;
            }

And here is my App.config:

<?xml version="1.0" encoding="utf-8"?><configuration><configSections><section name="microsoft.web.services3" type="Microsoft.Web.Services3.Configuration.WebServicesConfiguration, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /></configSections><startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /></startup><system.serviceModel><bindings><basicHttpBinding><binding name="ProspectaSoapBinding" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"><security mode="TransportCredentialOnly"><transport clientCredentialType="Basic" proxyCredentialType="None" realm=""></transport><message clientCredentialType="UserName" algorithmSuite="Default" /></security></binding></basicHttpBinding></bindings><client><endpoint address="http://cifinpruebas.asobancaria.com/ws/ProspectaWebService/services/Prospecta"
        binding="basicHttpBinding" bindingConfiguration="ProspectaSoapBinding"
        contract="ServiceReferenceProspecta.ProspectaWS" name="Prospecta" /></client></system.serviceModel><microsoft.web.services3><policy fileName="wse3policyCache.config" /></microsoft.web.services3></configuration>

And the exception message is: WSDoAllReceiver: Request does not contain required Security header

Any of iu have this problema before ?? Iu know why happend this ?? Have any of you the solution of this ???

GetCustomAttributes working only on some Enums

$
0
0

I have a bit of code that checks an enum to see if it has [Flags]. however, It only works for one of the enums that has a flag. the other ones are ignored for some reason.

var currentEnum = new EnumInfo() { Name = t.Name, IsFlagsEnum = t.GetCustomAttributes<FlagsAttribute>().Any() };


It loads the enums from an assembly and iterates through them. Nothing seems to be completely different between the enums other than the name and the values inside.

the t is the element in the foreach loop

foreach (Type t in query)
            {}

What would cause the get custom attributes to fail to find the [flags] attribute. 

C# Error when selecting text boxes

$
0
0

Hello

I have this problem where i am unable to work on my project due to features not working.

When i select a text box, it constantly flashes and when i look at my form properties they don't update.

I've added a little screen grab to show the issue.

http://i.gyazo.com/975a016b967adbc64ad218f53797c059.gif

I have uninstalled multiple times, and removed all sub folders and registry etc, it also happens on visual studio 2013 :/

Any help is appreciated, thanks.



Custom Video Player

$
0
0

I have a custom file type .mft which is basically a zip that has video inside (mpg,mp4,etc) that is encrypted/protected.

My ideia is to create a custom video player which will read those .mft files, for a private group of users (users provide user and password), and the custom player will not allow to save the video, so that no one can re-share it, and can only view it.

I saw that VLC has this library http://vlcdotnet.codeplex.com/releases/view/121099, so my player would use it.

My question is : Is it really possible to block users from not saving the video? I don't think so, because there are several software to record desktop activity.

What do you think?

Understanding C# Delegates Structure

$
0
0

I've been trying to understand C# delegates using Pro C# 5.

In short, the author describes the motivation for delegates as a structured way of dealing with function pointers and callbacks or two-way communication between objects.

The part I find confusing is the syntax/implementation for this:

  • On the one hand, an object of delegate type is seen as the handler or the one responsible for invoking some method or list of methods. To this end, it has methods such as Invoke() etc.

  • On the other hand, the delegate type is used as a 'wrapper' with which to pass around methods.

For example, it seems strange to me that a call to a delegate's GetInvocationList() returns an array of delegates. Shouldn't there be something else with which to wrap methods?

I expected there would be some other construct/type, say, MethodContainer which wraps methods. Then the syntax for adding methods to a delegate would be

classMyClass{voidMethod(string s){}}MyClass c =newMyClass();MethodContainer container =newMethodContainer(c.Method);delegatevoidMyDelegate(string s);MyDelegate d =newMyDelegate();

d.Add(container);

d.GetInvocationList();// returns array of MethodContainer

Class hierarchy question - do you implement separate classes for the same behavior?

$
0
0

I am currently working on a 'The Quest' mingame where there is a player and some enemies. My design so far involves a base abstract class called 'Mover' and an interface called 'IAttacker', since the Player object and the Enemy object(s) both move and attack, albeit in different ways. However I also think this may be unnecessary because I could just create one big combination interface, 'IMoveAttack' or something like that. Moreover, my friend who gave me the challenge recommeded that the Weapon class (the player can pick up weapons along the way which are lying on the floor) to be a subclass of Mover, even though the Weapons don't really need to move, they just need to spawn at random locations at every level.

What is the best design principle in this case?

How to Authenticate with Active Directory Using C#

$
0
0

Hi All,

I'd like to write a C# application that takes asks a user for their username and password and then authenticates them using Active Directory.

How can this be done?

Is there any sample code on how to do this?

Force delete folder and subfolder

$
0
0

Hi all,

I'm able to delete folder and all subfolder using File.Delete() and Directory.Delete(); however, I would like to know if it is possible that we could force to delete folder and subfolder even they are opened via network share access.

For example, I want to delete FolderA; however, FolderASub is currently opened by other user via network share access, and I got access denied or something similar error message. Just want to know if it is possible that I could delete FolderA without ask other user to close the access to FolderASub?

Please advise.


Best Regards,

Andy Pham


Best Regards, Andy Pham


How do I write my BLL to make it re-usable?

$
0
0

Most of it was written 4-5 years ago. Our teams long term objectives are to use Entity Framework. Though we aren't gonna do it right away as our deadlines aren't allowing us to do so. Now we have our own framework. I want to be able to segregate the Business logic layer in such a way that it need not be re-written when we move to EF. Please guide us with best practices, advise us in this direction.

Our business logic layer is very fragmented today (UI Code Behind + Stored Procedures/functions SqlServer/ C# persistent classes) : What if I want to segregate it totally and draw a very prominent line between Storage | DAL | Business Logic | UI

  1. I want to know if it's ok to move the BLL totally in SQl stored Procedures or does it have to be totally C# classes?

  2. Also to avoid re-writing the BLL as we are going to move to EF eventually. What steps should I take so that I can readily use the entire BLL with EF without changing the code.

  3. A lot of the stored procedures (which have the BL) lie in the storage DB itself. Does segregating the BLL mean the SP's and functions should be in a different database altogether? or for all practical purposes it's ok for them to be in the same DB?

I've seen multiple questions on SO which were really helpful, but I just couldn't get a clear picture of the solution or advise I seek, so I put everything in one post.

Please correct me if I'm wrong. I'm a novice when it comes to system design. I wanna be able to foresee what I'm getting into before actually implementing it.

Error while inserting information along with images into database..

$
0
0

This is my User Interface:

This is My Error Page:

This is code which I've written under Add customer Info button Method:

private void btnaddinfo_Click(object sender, EventArgs e)
        {
            string scn = ConfigurationManager.ConnectionStrings["Myconn"].ConnectionString;
            using (SqlConnection cn = new SqlConnection(scn))
            {
                using (SqlCommand cmd = new SqlCommand("SP_Info", cn))
                {
                    try
                    {
                        byte[] img = null;
                        FileStream fs = new FileStream(imageloc, FileMode.Open, FileAccess.Read);
                        BinaryReader br = new BinaryReader(fs);
                        img = br.ReadBytes((int)fs.Length);

                        cmd.CommandType = CommandType.StoredProcedure;
                        if (cn.State != ConnectionState.Open)
                            cn.Open();

                        SqlParameter p1 = new SqlParameter("@Hp_Number", SqlDbType.NVarChar, 50);
                        SqlParameter p2 = new SqlParameter("@Customer_Name", SqlDbType.VarChar, 50);
                        SqlParameter p3 = new SqlParameter("@Customer_Contact_Number", SqlDbType.NVarChar, 15);
                        SqlParameter p4 = new SqlParameter("@Guarantor_Name", SqlDbType.VarChar, 50);
                        SqlParameter p5 = new SqlParameter("@Guarantor_Contact_Number", SqlDbType.NVarChar, 15);
                        SqlParameter p6 = new SqlParameter("@Hp_Date", SqlDbType.Date);
                        SqlParameter p7 = new SqlParameter("@Customer_Address", SqlDbType.NVarChar, Max);
                        SqlParameter p8 = new SqlParameter("@Vehicle", SqlDbType.VarChar, 50);
                        SqlParameter p9 = new SqlParameter("@Vehicle_Model", SqlDbType.VarChar, 50);
                        SqlParameter p10 = new SqlParameter("@Vehicle_Number", SqlDbType.NVarChar, 50);
                        SqlParameter p11 = new SqlParameter("@Chasis_Number", SqlDbType.NVarChar, 50);
                        SqlParameter p12 = new SqlParameter("@Engine_Number", SqlDbType.NVarChar, 50);
                        SqlParameter p13 = new SqlParameter("@FC_Date", SqlDbType.Date);
                        SqlParameter p14 = new SqlParameter("@Insurance_Date", SqlDbType.Date);
                        SqlParameter p15 = new SqlParameter("@Insurance_Amount", SqlDbType.Int);
                        SqlParameter p16 = new SqlParameter("@Paid_Amount", SqlDbType.Int);
                        SqlParameter p17 = new SqlParameter("@Vehicle_Pic", Image);
                        SqlParameter p18 = new SqlParameter("@Customer_Pic ", Image);
                        SqlParameter p19 = new SqlParameter("@Guarantor_Pic ", Image);
                        SqlParameter p20 = new SqlParameter("@Documents_Pic", Image);
                        SqlParameter p21 = new SqlParameter("@Insurance_Pic", Image);

                        p1.Value = tbhpnum.Text;
                        p2.Value = tbcusnam.Text;
                        p3.Value = tbcusmblno.Text;
                        p4.Value = tbguanam.Text;
                        p5.Value = tbguamblno.Text;
                        p6.Value = tbhpdat.Text;
                        p7.Value = tbcusadd.Text;
                        p8.Value = tbveh.SelectedItem;
                        p9.Value = tbvehmod.SelectedItem;
                        p10.Value = tbvehnum.Text;
                        p11.Value = tbchanum.Text;
                        p12.Value = tbengnum.Text;
                        p13.Value=tbfcdat.Text;
                        p14.Value=tbinsdat.Text;
                        p15.Value = Convert.ToInt32(tbinsamt.Text);
                        p16.Value=Convert.ToInt32(tbpaiamt.Text);
                        p17.Value = boxvehpic.Image;
                        p18.Value=boxcuspic.Image;
                        p19.Value=boxguapic.Image;
                        p20.Value=boxdocpic.Image;
                        p21.Value=boxinspic.Image;


                        cmd.Parameters.Add(p1);
                        cmd.Parameters.Add(p2);
                        cmd.Parameters.Add(p3);
                        cmd.Parameters.Add(p4);
                        cmd.Parameters.Add(p5);
                        cmd.Parameters.Add(p6);
                        cmd.Parameters.Add(p7);
                        cmd.Parameters.Add(p8);
                        cmd.Parameters.Add(p9);
                        cmd.Parameters.Add(p10);
                        cmd.Parameters.Add(p11);
                        cmd.Parameters.Add(p12);
                        cmd.Parameters.Add(p13);
                        cmd.Parameters.Add(p14);
                        cmd.Parameters.Add(p15);
                        cmd.Parameters.Add(p16);
                        cmd.Parameters.Add(p17);
                        cmd.Parameters.Add(p18);
                        cmd.Parameters.Add(p19);
                        cmd.Parameters.Add(p20);
                        cmd.Parameters.Add(p21);

                        int count = cmd.ExecuteNonQuery();
                        if (count == 1)
                        {
                            MessageBox.Show(count.ToString()+ "Record(s) Saved.");
                        }
                        else
                        {
                            MessageBox.Show("Please correct the error which you have entered and then click on addinformation button");
                        }
                    }
                    catch (SqlException ex)
                    {
                        MessageBox.Show(ex.ToString());

                    }
                    finally
                    {
                        if (cn.State == ConnectionState.Open)
                            cn.Close();
                    }
                }
            }
        }

Whats wrong on my code......


Thanks & Regards RAJENDRAN M


C# - Problem with assigning double

$
0
0

Hi! When I try to assign my double its value appears like an integer. Here is my source:

using System;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            decimal pi = 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9); //If you follow the pattern it will almost be pi

            Console.WriteLine(pi);

            Console.ReadKey();
        }
    }
}

The output is following:

4

I tried 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9) in calc.exe and the output was: 

3,3396825396825396825396825396825

Why doesn't my output appears like that and how can I solve it?

Thanks in advance.

Selecting right framework

$
0
0

I have got into a discussion about choosing a proper framework to use for developing a middle tier and a back end for a web based application. While an application itself is a generic enough program there are some specifics that drive a process of selecting a framework. Here are a few: Support for multiple databases like SQL and Oracle. also because of having clients that use different versions of the application SQL or Oracle scripts that are distributed to clients are not the same. In order to keep them generic between clients all updates to distributed scripts are kept in place. Another words, a script checks for an existence for a column before it adds it. So, if a table has been modified a number of times the scripts keep all previous validations. I think that is most important condition. Is out there a framework that can generate that kind of scripts?

Thanks

Selecting right framework

$
0
0

I have got into a discussion about choosing a proper framework to use for developing a middle tier and a back end for a web based application. While an application itself is a generic enough program there are some specifics that drive a process of selecting a framework. Here are a few: Support for multiple databases like SQL and Oracle. also because of having clients that use different versions of the application SQL or Oracle scripts that are distributed to clients are not the same. In order to keep them generic between clients all updates to distributed scripts are kept in place. Another words, a script checks for an existence for a column before it adds it. So, if a table has been modified a number of times the scripts keep all previous validations. I think that is most important condition. Is out there a framework that can generate that kind of scripts?

Thanks

Regarding Creation of c# exe File

$
0
0

I am using VS 2010 and SQL Server 2008, I have created EXE file of my c# project.

to install that project in client pc is it necessary to have SQL Server installed in client pc??

Also how to use Global ConnectionString, so that EXE file can run anywhere.??

Changing Key Values

$
0
0

Hello 

I have a question about changing the key strokes values within system.windows.input and I wonder if anyone could help, I was asked by a friend if you could change the value of a key or keys at the windows level for example instead you run the application so it would change the value of the "9" key to the value above it. So the "9" key would be changed "(" all the time to you close the application.

I try'd to import system.windows.input.Keys but I could only get access to the System.Windows.input level and i have try'd to add the reference to the form in the form properties.

Using System.Windows.Input; - Works
Using System.Windows.Input.Keys; - Doesn't Work i get a red line under the word "Keys"
Using System.Windows.Input.Keyboard; Doesn't Work i get a red line under the word "Keyboard"

So my question is can you change the keyboard key vales at the windows level by an application? 




Viewing all 31927 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>