Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
E

eddieangel

@eddieangel
About
Posts
193
Topics
78
Shares
0
Groups
0
Followers
0
Following
0

Posts

Recent Best Controversial

  • split method bug
    E eddieangel

    It was a bit of hyperbole. Any time you are parsing string data you want to understand what possible user inputs could cause you problems and make sure your string is scrubbed before you split it. If there is a possibility of newline characters, carriage returns, or inconsistent tabs you want to address those. The simple solution is a string replace, there are more advanced strategies using regular expressions and such. But in favor of simplicity try something like this:

    class Program
    {
    static void Main(string[] args)
    {
    string CurrentLine; // Remove this, it isn't necessary
    string FilePath = "C:\\12837.SDF.txt"; // Change this to filePath, it is the generally correct way of naming method level variables
    using (StreamReader sr = new StreamReader(FilePath)) // change to filePath also
    {
    while(!sr.EndOfStream)
    {
    string currentLine = sr.ReadLine();
    GetSplit(currentLine.Replace("\t","").Replace("\r","").Replace("\n","");
    // Console.WriteLine(array.Length.ToString());

                }
            }
        }
    
        private static void GetSplit(string CurrentLine)
        {
            string\[\] array = CurrentLine.Split(';');
            string first = array\[0\];
            string second = array\[1\];
            string third = array\[2\];
            string four = array\[3\];
          //  string five = array\[4\];
           // string six = array\[5\];
          //  string seven = array\[6\];
           // string eight = array\[7\];
            Console.WriteLine(first + " " + second + " " + third + " " + four);
        }
    }
    

    }

    That is just a general idea on how to handle it. One thing you always want to be wary of is bad input, and the best way to deal with it is to aggressively control your strings by stripping out troublesome characters.

    C# help database com tutorial question

  • split method bug
    E eddieangel

    If there is some kind of invisible character you can always scrub your string first.

    while(!sr.EndOfStream)
    {
    CurrentLine = sr.ReadLine();
    GetSplit(CurrentLine.Replace("\t", "");
    // Console.WriteLine(array.Length.ToString());

                }
    

    And you should always be careful accessing an array like, you might try defensive coding (try - catch) or iterating through the array using a foreach() that way you will not end up out of bounds. If you need certain indexed members of the array to print, wrap the code and catch out of bounds exceptions.

    C# help database com tutorial question

  • How to handle multiple exceptions(Try..Catch)
    E eddieangel

    Select is a Linq statement. Try adding the proper using statement to the top of your class. using System.Linq; using System.Xml.Linq; If those do not work you may need to cast your object to something else.

    C# sysadmin debugging xml json help

  • How to handle multiple exceptions(Try..Catch)
    E eddieangel

    Your model class already exists, it is the Data.General.Shipment object. All of this is really outside the scope of your original question of multiple try... catch... blocks, though. If you are able it is always good to step back and ask yourself if this is the right approach. DO you really need XML? It is super wordy and a pain to work with, JSON is way better, but again, outside the scope. To put an easy stamp on your original question, you can have many try catch blocks but it is going to be a very iterative process for you to figure them out and consider all of the permutations. So you have to ask yourself what the goal is. Is there a recovery path through these exceptions or are you trying to send different error messages to the user? Or maybe just log more detail? Either way if your try/catch is at the point of building out the XML all you are likely to get is XML formatting exceptions, which do not encapsulate your business rules. A couple notes on generally being defensive in the code you have written: 1. Do not use decimal.Parse. Since you are using the null check operator getting the tracking number, you expose the possibility of errors there. Try this:

    var prc = new Data.General.Shipment();
    var node = mainNode.SelectSingleNode("TrackingNumber");

                    if (node == null)
                    {
                        return; // If your method is not void return the appropriate data type, null, false, etc...
                    }
    
                    decimal trackingNumber;
    
                    if (!decimal.TryParse(node.InnertText, out trackingNumber))
                    {
                        return; // Same as above with return type
                    }
    
                    prc.GetByProNumber(trackingNumber);
    
                    try
                    {
                        rspxml.Root.Add(new XElement("API", "4.0"));
                        rspxml.Root.Add(new XElement("PackageTrackingInfo"));
                        rspxml.Root.Element("PackageTrackingInfo").Add(new XElement("TrackingNumber", prc.ProNumber.ToString())); // These ToString calls are dangerous without first validating the data
                        rspxml.Root.Add(new XElement("PackageDestinationLocation"));
                        rspxml.Root.Element("PackageDestinationLocation").Add(new XElement("City", prc.Consignee.ToString()));
                        rspxml.Root.Element("PackageDestinationLocation").Add(new XElement("StateProvince", prc.
    
    C# sysadmin debugging xml json help

  • How to handle multiple exceptions(Try..Catch)
    E eddieangel

    I am not sure what the validation looks like for your situation, but there are a couple of methods. The most simple is to validate to see if the string exists.

    if (string.isNullOrEmpty(apiVariableName)) { return ; }

    Since the first two bold items are static text there really isn't anything to validate there unless there is something else we aren't seeing. That said, one of the best methods to validate your data is to set validation attributes on your model class (Data.General.Shipment() and write a method that validates that. For example:

    internal class Shipment {
    [Required]
    [StringLength(12)]
    public string ShippingNumber { get; set; }

        \[Required(ErrorMessage = "City cannot be empty.")\]
        public string City { get; set; }
    
        \[Required(ErrorMessage = "Zip is Required")\]
        \[RegularExpression(@"^\\d{5}(-\\d{4})?$", ErrorMessage = "Invalid Zip")\]
        public string PostalCode { get; set; }
    }
    

    The trick here is that you really want to leave your model validating to the model or validator class and not be trying to validate when you are building the XML. It is good defensive programming to cover null possibilities and such, but you really want to uncomplicate things as much as possible if you are crafting an XML by hand.

    C# sysadmin debugging xml json help

  • How to handle multiple exceptions(Try..Catch)
    E eddieangel

    The old adage Exceptions should be Exceptional applies here. Rather than using multiple try ... catch blocks, my advice is to validate your known inputs up front. While I personally find it ugly to use a series of If (!x) { return; } it is a solid method of keeping your code simple and implicit. I am not sure what the bold issue is because you are using static values so I don't know what you would catch there. Starting at the third element, though, I would advocate writing a validator of some sort to validate the Shipment object. And to possibly save you some grief, might I suggest cutting out some of the craziness and just using a serializer to serialize the shipment object? IT can save you a TON of grief trying to validate the XML> If you can't serialize the Shipment directly because of schema differences, try creating a DTO that matches the XML you want and serializing that. Working with raw XML like this should be a last resort. That is my 2c

    C# sysadmin debugging xml json help

  • Style User Control
    E eddieangel

    In this WPF can be a real pain. I wanted to create a textbox that had a browse button inside of it to match some other controls and it was quite the hassle. Basically, the flow is this: 1. Create your user control, hopefully it is based off of other controls so you can use the existing dependency properties 2. In your resources.xaml file, add a reference to the xmlns of your control 3. Add style in resources.xaml For me, my control is called a BrowseTextBox. The style looks like this:

        <Setter Property="BorderThickness"
                Value="1" />
        <Setter Property="Background"
                Value="#FFFFFF" />
        <Setter Property="Foreground"
                Value="#000000" />
        <Setter Property="Padding"
                Value="5,3" />
        <Setter Property="VerticalContentAlignment"
                Value="Center" />
        <Setter Property="HorizontalContentAlignment"
                Value="Stretch" />
        <Setter Property="FocusVisualStyle"
                Value="{x:Null}" />
        <Setter Property="SnapsToDevicePixels"
                Value="True" />
        <Setter Property="KeyboardNavigation.TabNavigation"
                Value="Once" />
        <Setter Property="KeyboardNavigation.ControlTabNavigation"
                Value="Cycle" />
        <Setter Property="IsTabStop"
                Value="False" />
        <Setter Property="Validation.ErrorTemplate">
            <Setter.Value>
                <ControlTemplate />
            </Setter.Value>
        </Setter>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type cont:BrowseTextBox}">
                    <Grid x:Name="LayoutGrid">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition x:Name="TextColumn"
                                              Width="\*" />
                            <ColumnDefinition x:Name="ButtonsColumn"
                                              Width="Auto" />
                        </Grid.ColumnDefinitions>
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal" />
                                <VisualState x:Name="MouseOver">
    </x-turndown>
    
    WPF database help tutorial question

  • How to set Datasource pointing to multiple Database at the time crystal report creation
    E eddieangel

    Multiple databases are really outside the scope of what CR is meant to do. That said, your best bet is to build and hydrate an object outside of Crystal Reports and set that as the datasource for the report. There are a lot of answers on the net about how to do this, just search for something along the lines of "Bind Crystal Report to object".

    C# csharp database testing beta-testing help

  • Telerik GridViewComboBoxColumn
    E eddieangel

    I realize that this is not a Telerik forum but I also poured through their forums to no avail. Long story short, I am using NHibernate to hydrate my viewmodels and exposing complex objects with their related objects to my view. The issue is that in my grid I have a combobox column that has a collection of objects from the viewmodel, the selectedvalue of which will update the object of the selected item. When I change the combobox everything is great, everything is talking back and forth, all is well. But when I close the control and reopen it, it does not select any value for the column. All code is cut for brevity: View:

    ViewModel:

        public ObservableCollection Clients { get; private set;}
    

    Entity:

    public class Claim : Entity
    {
    public virtual Client Client { get; set; }
    }

    NHibernate Mapping

    public ClaimMap()
    {
    Table("Claim");
    LazyLoad();
    Id(x => x.Id).GeneratedBy.Identity().Column("id");
    References(x => x.Client).Column("clientId").Not.Nullable();
    }
    }
    }

    I am sure I could just expose the id values on the Claim object and wire it up that way but it really is swimming against the current of NHibernate to do so. Thoughts? Cheers, --EA

    WPF css help question discussion announcement

  • What the Apple iCar will be like ?
    E eddieangel

    No more fixing your own car if you don't run iOS at home. If you are a Windows household you have to boot a VM of OS X to fix your iCar or take it to an overpriced mechanic who tells you that he can't fix your iCar because they don't do that, but if you purchased the extended service plan he can give you a new one. No service plan = purchase new iCar at full price. nJoy.

    The Lounge csharp tools question announcement learning

  • Which OS do you work primarily on ?
    E eddieangel

    This. I write Windows LOB software during the day, but when I don my cape and cowl at night I run OS X through VMWare on my Windows laptop. It was a gigantic pain in the rear end to get working and I wish that Apple better supported iOS developers developing in Windows. *sigh*

    The Lounge linux question

  • Variable Datasource Name
    E eddieangel

    Now THAT sounds promising. Thanks for the direction. Cheers, --EA

    C# css xml tutorial question discussion

  • Variable Datasource Name
    E eddieangel

    I should have explained better. The instructions are XML, but the datasource could be any number of things. It is either a List or just an Object. If it is an object I want to get at it's properties as in the c# code I posted below, if it is a List then I will loop through it and access it the same way. Just need to figure out how to access that data by name.

    C# css xml tutorial question discussion

  • Variable Datasource Name
    E eddieangel

    I am trying to make a fairly robust file writer. I want to specify the format of the file in an XML file. I need to be able to get the datasource name dynamically from the XML file, the XML will look something like this:

    I am not sure what that data will look like. It might be a list, it might be a single object, but I want to be able to enumerate it's properties in my class. Something like this:

    var data = data.GetType().GetProperty(fieldName).GetValue(data, null).ToString()

    I have most of the code ironed out, just not sure how to handle the data source. I could make it less generic and take the data source name out of the XML and just handle it code side, but I like the robustness of having the instructions all XML contained. Thoughts? Cheers, --EA

    C# css xml tutorial question discussion

  • Why future Robots are going to murder Humans
    E eddieangel

    I think the logic is flawed. Threat assessment says take out the most dangerous opponent first. If these machines are selfish and interested in resource acquisition they will war with each other before they war with mankind. I am calling this one in advance. Rednecks 1 Robots 0.

    The Lounge com sysadmin agentic-ai tools

  • MVVM Bound Radio Button Unexpected Behavior
    E eddieangel

    I have a boolean value to which radio buttons are bound, like so:

                    Yes
                
                No
    

    In VM property looks like this:

        private bool isChecked;
        public bool IsChecked
        {
            get { return isChecked; }
            set
            {
                if (isChecked!= value)
                {
                    isChecked = value;
                    OnPropertyChanged("IsChecked");
                }
            }
        }
    

    If the bound value is true, when I first open the screen the Yes checkbox is checked. I can select yes or no and they will display and save correctly. However, if I open the screen with a no value, nothing is checked. I believe the problem lies in the fact that when IsChecked is false, the converter converts that value to true in order to display the No box as checked, but in doing so it sets the IsChecked property to true, which then means that the No button should not be checked. The converter is the standard bool inverter all over the internet. I didnae write this code, just trying to debug it. Cheers, --EA

    WPF wpf debugging architecture help

  • MVVM Observe VM Command
    E eddieangel

    I am adapting a XAML Control to be MVVM compliant. Right now the XAML is actually not important, but there is one component that is giving me grief. The control is actually called from another view model on an event. Click here to add kind of thing. That command looks like this:

        private void OnAddItem()
        {
            SubItemViewModel subVM = new SubItemViewModel(Key, null, false);
            IDisposable ss = Observable.FromEventPattern(subVM.Save, "ExecuteEnd").Take(1).Subscribe(x => { LoadList(); });
            SubControl ctrl = new SubControl();
            ctrl.DataContext = subVM;
            WorkspaceUserControlWindow w = new WorkspaceUserControlWindow(ctrl);
            w.Title = subVM.DisplayTitle ?? Key.Value + " - Add Item";
            Observable.FromEventPattern(w, "Closed").Take(1).Subscribe(x => { if (ss != null) ss.Dispose(); });
            w.Show();
        }
    

    This worked fine in a non-MVVM model using a delegate command, click events, etc... Now that I have migrated the VM over to MVVM I need to understand how to publish the Save command so that the calling event can listen for the ExecuteEnd and reload the data list as shown here:

    IDisposable ss= Observable.FromEventPattern(subVM.Save, "ExecuteEnd").Take(1).Subscribe(x => { LoadList(); });

    I have always used relay commands within my view models as I have never needed to observe a command like this. Thoughts? Cheers, --EA

    C# wpf architecture tutorial question discussion

  • Painfully Slow Operation
    E eddieangel

    I ended up moving all the data access logic to a SQL SP using STUFF for that very reason. The data access from SQL is a snap, but loading the data into the model is time consuming. Frankly, I think that the nature of the design of the WPF screen is the issue. Each of the items is loaded into a list view and has two states, one editable state and one that is not editable. Any time you make a change to the property in the editable mode you have to fire the NotifyPropertyChanged event so that the UI will update it in the non-editable form. As a result, every single property of every row fires an OnPropertyChanged event during the initial load. I think this is likely the problem. I just don't know how to work around it. If I could avoid that initial event firing I think that things would be much quicker.

    C# csharp database linq

  • Painfully Slow Operation
    E eddieangel

    Unfortunately, the AsEnumerable is necessary as L2E does not recognize string.Join. So you have to present it as an IEnumerable in order to join the Doc strings. Regardless, I retooled the process to use a stored procedure but it is still a nightmare. The data access is fast, the stored procedure fills a list in less than a second, but assigning those items to the DocumentType model takes four or five seconds more. It looks like it is the model itself. I am wondering if the implementation of INPC on the model is not causing a lot of slow down. Each time a new document type is added to the list it fires the OnPropertyChanged event for every single property. Not sure that is the problem, but it is a lot of events.

    C# csharp database linq

  • Painfully Slow Operation
    E eddieangel

    I am trying to root out why this particular linq query is so expensive from a time standpoint, assuming it is the linq query that is causing it.

    public static List GetDocs()
    {
    List output;
    using (context = contextLogic())
    {
    output = (from d in context.DocumentTypes
    select d).AsEnumerable().Select (x => new DocumentType
    {
    Id = x.iD,
    Name = x.Name,
    FlagA = x.FlagA,
    IsActive = x.IsActive,
    UpdateDate = x.UpdateDate,
    CategoryName = x.DocumentCategory.Name,
    Associations = string.Join(",", x.DocumentAssociations.Select(g => g.ADocID.ToString()))
    }).ToList();
    }
    return output;
    }

    I tried flipping things around quite a bit. This was initially an observablecollection but it is a list right now as I try to tune it in different ways. Right now it is taking about 12 seconds to retrieve data from a table of 350 records. If I take out the CategoryName and the associations it times down to about six seconds, but that is still ridiculously slow.

    C# csharp database linq
  • Login

  • Don't have an account? Register

  • Login or register to search.
  • First post
    Last post
0
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups