mardi 4 août 2015

How to direct an .aspx response into a controller method

Hello Ladies and Gentlemen,

I was wondering if someone could give me some guidance. I am sending a request to a service which prompts a form. In my request I am sendint an XML object that looks like this:

<PaymentRequest>
<ClientKey>CJOFSTEXFILE</ClientKey>
<TransactionID>TESTTESTTEST1</TransactionID>
<RedirectURL>http://localhost:44300/efile/GeneratingXMLFormResponse</RedirectURL>
<Amount>-1</Amount>
<GetToken>1</GetToken>
</PaymentRequest>

The XML works fine and I get the desired response form. However my issue is that whenever i fill out the response and send the post request the redirect URL is this one:

https://localhost:44300/efile/EPayment.aspx

this is the feed:

POST https://localhost:44300/efile/EPayment.aspx HTTP/1.1
Host: localhost:44300
Connection: keep-alive
Content-Length: 3349
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: https://localhost:44300
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: https://localhost:44300/efile/GeneratingXMLFormRequest
Accept-Encoding: gzip, deflate
Accept-Language: es,en-US;q=0.8,en;q=0.6

A couple of questions:

1) How can I direct this POST request to a controller method within my Efile controller? Right now I am getting an error since I do not have a method called Epayment.aspx I tried creating a method called exactly this but that does not work properly.

2) Is it possible for the service to send the POST request to the Referer URL? That's the URL i provided in the XML however the service is using a different one and I am not 100% sure where is it getting that from.

Thanks for all the help!

Neo4jClient HTTPS Support

i can't seem to make Neo4jclient to work with neo4j when HTTPS is enabled. Error happens at connect.

var client = new GraphClient(new Uri("https://localhost:7473/db/data"));
                client.Connect();

It works perfectly fine when it's only HTTP.

This is what i am getting.

An exception of type 'System.AggregateException' occurred in Neo4jClient.dll but was not handled in user code 

Has anyone ever tried to make Neo4jClient work with HTTPS support enabled. Thanks in Advance.

Using CAML Queries NOT for SharePoint

I have like how I can get data from SharePoint with CAML queries. I had built restful service on SP with searching method which get CAML query string as argument (caml was coming from client, where it was builder with camlJS library). So now I am trying to build rest API using entity framework, but I need some sort of dynamic query. Could anybody to advice to me something about that?

Column "columnName" does not belong to table "tableName"

I have a .NET console application deployed to an Azure VM. The utility is pretty simple, it just looks at a table and sends emails. However, we randomly get errors on this line:

foreach (DataRow bcemail in BCEmails.Tables[0].Rows)
{
email.Subject = bcemail["subject"].ToString(); 
//other stuff
}

The error we received says: column 'subject' does not belong to table Table. I have checked that the stored proc always returns only 1 table and always has "subject" as a column. Keep in mind it works more than half the times, giving error only randomly. It works totally fine in my local environment. The Azure VM also has several other apps. Researching this problem, I found this link: http://ift.tt/1K2hgIF Which talks about corrupted database connection pool and recommends that you make sure the connection is closed properly. I have done this throughout the application. The link also mentions that we use 'iisreset' every time we stop the IIS server. So I tried doing an IISReset and running the app again and it works fine. If I do an IISReset every time before it's scheduled to run, it works fine.

My questions are this: 1. This is a console app, not a web app, in fact there are no web sites configured on IIS on this VM. So why does IISReset work? 2. Can anyone recommend any other approach to solve this problem other than to do IISReset every time?

NuGet command in VS : can install package but not added to packaged.config & project

I am having a problem with a package in a private repository, running install-package "PackageName" just install the package in "packages" folder, but the file packages.config doesn't contain this package, also the project file (*.csproj) is not being updated to have reference to this package.

enter image description here

Normally, it should have a line saying that "Added package to project successfully", but not in this case.

Could anyone please help? Thank you for any idea.

How to install ngen dependencies?

I'm using ngen to install native image of an exe but i need also to install their dependencies when i try

ngen install c:\myfiles\MyLib.dll /ExeConfig:c:\myapps\MyApp.exe

I get the following errors

Could not load file or assembly xxx  or one of its dependencies. The located assembly's manifest definition does not match the assembly reference.

I'm using theses dll with Assembly.load

How i can resolve this problem ?

UWP SplitView DisplayMode="Overlay" doesn't work

I have a SplitView in WIn10 C# application. I set SplitVIew DisplayMode to Overlay but it still used the Inline. Here's my XAML:

<Page x:Name="Root"
  x:Class="NavigationMenuSample.AppShell"
  xmlns="http://ift.tt/o66D3f"
  xmlns:x="http://ift.tt/mPTqtT"
  xmlns:local="using:NavigationMenuSample"
  xmlns:controls="using:NavigationMenuSample.Controls"
  xmlns:d="http://ift.tt/pHvyf2"
  xmlns:mc="http://ift.tt/pzd6Lm"
  Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
  KeyDown="AppShell_KeyDown"
  TabNavigation="Cycle"
  mc:Ignorable="d">

<!-- Using a Page as the root for the app provides a design time experience as well as ensures that
     when it runs on Mobile the app content won't appear under the system's StatusBar which is visible 
     by default with a transparent background.  It will also take into account the presence of software
     navigation buttons if they appear on a device.  An app can opt-out by switching to UseCoreWindow.
-->

<Page.Resources>
    <DataTemplate x:Key="NavMenuItemTemplate" x:DataType="local:NavMenuItem">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="48" />
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <!-- Showing a ToolTip and the Label is redundant.  We put the ToolTip on the icon.
                 It appears when the user hovers over the icon, but not the label which provides
                 value when the SplitView is 'Compact' while reducing the likelihood of showing
                 redundant information when the label is shown.-->
            <FontIcon x:Name="Glyph" FontSize="16" Glyph="{x:Bind SymbolAsChar}" VerticalAlignment="Center" HorizontalAlignment="Center" ToolTipService.ToolTip="{x:Bind Label}"/>
            <TextBlock x:Name="Text" Grid.Column="1" Text="{x:Bind Label}" />
        </Grid>
    </DataTemplate>
</Page.Resources>

<Grid>
    <!-- Adaptive triggers -->
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup>
            <VisualState>
                <VisualState.StateTriggers>
                    <AdaptiveTrigger MinWindowWidth="720" />
                </VisualState.StateTriggers>
                <VisualState.Setters>
                    <Setter Target="RootSplitView.DisplayMode" Value="CompactInline"/>
                    <Setter Target="RootSplitView.IsPaneOpen" Value="True"/>
                </VisualState.Setters>
            </VisualState>
            <VisualState>
                <VisualState.StateTriggers>
                    <AdaptiveTrigger MinWindowWidth="0" />
                </VisualState.StateTriggers>
                <VisualState.Setters>
                    <Setter Target="RootSplitView.DisplayMode" Value="Overlay"/>
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>

    <!-- Top-level navigation menu + app content -->
    <SplitView x:Name="RootSplitView"
               DisplayMode="Overlay"
               OpenPaneLength="256"
               IsTabStop="False">
        <SplitView.Pane>
            <!-- A custom ListView to display the items in the pane.  The automation Name is set in the ContainerContentChanging event. -->
            <controls:NavMenuListView x:Name="NavMenuList"
                                      TabIndex="3"
                                      Margin="0,48,0,0"
                                      ContainerContentChanging="NavMenuItemContainerContentChanging"
                                      ItemContainerStyle="{StaticResource NavMenuItemContainerStyle}"
                                      ItemTemplate="{StaticResource NavMenuItemTemplate}"
                                      ItemInvoked="NavMenuList_ItemInvoked">
                <controls:NavMenuListView.Header>
                    <!-- Using this custom back navigation button until the system-provided back button is enabled. -->
                    <Button x:Name="BackButton"
                            TabIndex="2"
                            Style="{StaticResource NavigationBackButtonStyle}"
                            IsEnabled="{Binding AppFrame.CanGoBack, ElementName=Root}"
                            Width="{Binding ItemsPanelRoot.Width, ElementName=NavMenuList}"
                            HorizontalAlignment="{Binding ItemsPanelRoot.HorizontalAlignment, ElementName=NavMenuList}"
                            Click="BackButton_Click"/>
                </controls:NavMenuListView.Header>
            </controls:NavMenuListView>
        </SplitView.Pane>

        <!-- OnNavigatingToPage we synchronize the selected item in the nav menu with the current page.
             OnNavigatedToPage we move keyboard focus to the first item on the page after it's loaded. -->
        <Frame x:Name="frame"
               Navigating="OnNavigatingToPage"
               Navigated="OnNavigatedToPage">
            <Frame.ContentTransitions>
                <TransitionCollection>
                    <NavigationThemeTransition>
                        <NavigationThemeTransition.DefaultNavigationTransitionInfo>
                            <EntranceNavigationTransitionInfo/>
                        </NavigationThemeTransition.DefaultNavigationTransitionInfo>
                    </NavigationThemeTransition>
                </TransitionCollection>
            </Frame.ContentTransitions>
        </Frame>
    </SplitView>

    <!-- Declared last to have it rendered above everything else, but it needs to be the first item in the tab sequence. -->
    <ToggleButton x:Name="TogglePaneButton"
                  TabIndex="1"
                  Style="{StaticResource SplitViewTogglePaneButtonStyle}"
                  IsChecked="{Binding IsPaneOpen, ElementName=RootSplitView, Mode=TwoWay}"
                  Unchecked="TogglePaneButton_Checked"
                  AutomationProperties.Name="Menu"
                  ToolTipService.ToolTip="Menu" />
</Grid>

I got this from XAMLNavigationSample from Win 10 github samples. And here's the .cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Metadata;
using Windows.UI.Xaml.Automation;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using NavigationMenuSample.Controls;
using NavigationMenuSample.Views;

namespace NavigationMenuSample
{
    /// <summary>
    /// The "chrome" layer of the app that provides top-level navigation with
    /// proper keyboarding navigation.
    /// </summary>
    public sealed partial class AppShell : Page
    {
        // Declare the top level nav items
        private List<NavMenuItem> navlist = new List<NavMenuItem>(
            new[]
            {
                new NavMenuItem()
                {
                    Symbol = Symbol.Contact,
                    Label = "Basic Page",
                    DestPage = typeof(BasicPage)
                },
                new NavMenuItem()
                {
                    Symbol = Symbol.Edit,
                    Label = "CommandBar Page",
                    DestPage = typeof(CommandBarPage)
                },
                new NavMenuItem()
                {
                    Symbol = Symbol.Favorite,
                    Label = "Drill In Page",
                    DestPage = typeof(DrillInPage)
                },
            });

        public static AppShell Current = null;

        /// <summary>
        /// Initializes a new instance of the AppShell, sets the static 'Current' reference,
        /// adds callbacks for Back requests and changes in the SplitView's DisplayMode, and
        /// provide the nav menu list with the data to display.
        /// </summary>
        public AppShell()
        {
            this.InitializeComponent();

            this.Loaded += (sender, args) =>
            {
                Current = this;

                this.TogglePaneButton.Focus(FocusState.Programmatic);
            };

            SystemNavigationManager.GetForCurrentView().BackRequested += SystemNavigationManager_BackRequested;

            // If on a phone device that has hardware buttons then we hide the app's back button.
            if (ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
            {
                this.BackButton.Visibility = Visibility.Collapsed;
            }

            NavMenuList.ItemsSource = navlist;
        }

        public Frame AppFrame { get { return this.frame; } }

        /// <summary>
        /// Default keyboard focus movement for any unhandled keyboarding
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AppShell_KeyDown(object sender, KeyRoutedEventArgs e)
        {
            FocusNavigationDirection direction = FocusNavigationDirection.None;
            switch (e.Key)
            {
                case Windows.System.VirtualKey.Left:
                case Windows.System.VirtualKey.GamepadDPadLeft:
                case Windows.System.VirtualKey.GamepadLeftThumbstickLeft:
                case Windows.System.VirtualKey.NavigationLeft:
                    direction = FocusNavigationDirection.Left;
                    break;
                case Windows.System.VirtualKey.Right:
                case Windows.System.VirtualKey.GamepadDPadRight:
                case Windows.System.VirtualKey.GamepadLeftThumbstickRight:
                case Windows.System.VirtualKey.NavigationRight:
                    direction = FocusNavigationDirection.Right;
                    break;

                case Windows.System.VirtualKey.Up:
                case Windows.System.VirtualKey.GamepadDPadUp:
                case Windows.System.VirtualKey.GamepadLeftThumbstickUp:
                case Windows.System.VirtualKey.NavigationUp:
                    direction = FocusNavigationDirection.Up;
                    break;

                case Windows.System.VirtualKey.Down:
                case Windows.System.VirtualKey.GamepadDPadDown:
                case Windows.System.VirtualKey.GamepadLeftThumbstickDown:
                case Windows.System.VirtualKey.NavigationDown:
                    direction = FocusNavigationDirection.Down;
                    break;
            }

            if (direction != FocusNavigationDirection.None)
            {
                var control = FocusManager.FindNextFocusableElement(direction) as Control;
                if (control != null)
                {
                    control.Focus(FocusState.Programmatic);
                    e.Handled = true;
                }
            }
        }

        #region BackRequested Handlers

        private void SystemNavigationManager_BackRequested(object sender, BackRequestedEventArgs e)
        {
            bool handled = e.Handled;
            this.BackRequested(ref handled);
            e.Handled = handled;
        }

        private void BackButton_Click(object sender, RoutedEventArgs e)
        {
            bool ignored = false;
            this.BackRequested(ref ignored);
        }

        private void BackRequested(ref bool handled)
        {
            // Get a hold of the current frame so that we can inspect the app back stack.

            if (this.AppFrame == null)
                return;

            // Check to see if this is the top-most page on the app back stack.
            if (this.AppFrame.CanGoBack && !handled)
            {
                // If not, set the event to handled and go back to the previous page in the app.
                handled = true;
                this.AppFrame.GoBack();
            }
        }

        #endregion

        #region Navigation

        /// <summary>
        /// Navigate to the Page for the selected <paramref name="listViewItem"/>.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="listViewItem"></param>
        private void NavMenuList_ItemInvoked(object sender, ListViewItem listViewItem)
        {
            var item = (NavMenuItem)((NavMenuListView)sender).ItemFromContainer(listViewItem);

            if (item != null)
            {
                if (item.DestPage != null &&
                    item.DestPage != this.AppFrame.CurrentSourcePageType)
                {
                    this.AppFrame.Navigate(item.DestPage, item.Arguments);
                }
            }
        }

        /// <summary>
        /// Ensures the nav menu reflects reality when navigation is triggered outside of
        /// the nav menu buttons.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnNavigatingToPage(object sender, NavigatingCancelEventArgs e)
        {
            if (e.NavigationMode == NavigationMode.Back)
            {
                var item = (from p in this.navlist where p.DestPage == e.SourcePageType select p).SingleOrDefault();
                if (item == null && this.AppFrame.BackStackDepth > 0)
                {
                    // In cases where a page drills into sub-pages then we'll highlight the most recent
                    // navigation menu item that appears in the BackStack
                    foreach (var entry in this.AppFrame.BackStack.Reverse())
                    {
                        item = (from p in this.navlist where p.DestPage == entry.SourcePageType select p).SingleOrDefault();
                        if (item != null)
                            break;
                    }
                }

                var container = (ListViewItem)NavMenuList.ContainerFromItem(item);

                // While updating the selection state of the item prevent it from taking keyboard focus.  If a
                // user is invoking the back button via the keyboard causing the selected nav menu item to change
                // then focus will remain on the back button.
                if (container != null) container.IsTabStop = false;
                NavMenuList.SetSelectedItem(container);
                if (container != null) container.IsTabStop = true;
            }
        }

        private void OnNavigatedToPage(object sender, NavigationEventArgs e)
        {
            // After a successful navigation set keyboard focus to the loaded page
            if (e.Content is Page && e.Content != null)
            {
                var control = (Page)e.Content;
                control.Loaded += Page_Loaded;
            }
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            ((Page)sender).Focus(FocusState.Programmatic);
            ((Page)sender).Loaded -= Page_Loaded;
        }

        #endregion

        public Rect TogglePaneButtonRect
        {
            get;
            private set;
        }

        /// <summary>
        /// An event to notify listeners when the hamburger button may occlude other content in the app.
        /// The custom "PageHeader" user control is using this.
        /// </summary>
        public event TypedEventHandler<AppShell, Rect> TogglePaneButtonRectChanged;

        /// <summary>
        /// Callback when the SplitView's Pane is toggled open or close.  When the Pane is not visible
        /// then the floating hamburger may be occluding other content in the app unless it is aware.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TogglePaneButton_Checked(object sender, RoutedEventArgs e)
        {
            this.CheckTogglePaneButtonSizeChanged();
        }

        /// <summary>
        /// Check for the conditions where the navigation pane does not occupy the space under the floating
        /// hamburger button and trigger the event.
        /// </summary>
        private void CheckTogglePaneButtonSizeChanged()
        {
            if (this.RootSplitView.DisplayMode == SplitViewDisplayMode.Inline ||
                this.RootSplitView.DisplayMode == SplitViewDisplayMode.Overlay)
            {
                var transform = this.TogglePaneButton.TransformToVisual(this);
                var rect = transform.TransformBounds(new Rect(0, 0, this.TogglePaneButton.ActualWidth, this.TogglePaneButton.ActualHeight));
                this.TogglePaneButtonRect = rect;
            }
            else
            {
                this.TogglePaneButtonRect = new Rect();
            }

            var handler = this.TogglePaneButtonRectChanged;
            if (handler != null)
            {
                // handler(this, this.TogglePaneButtonRect);
                handler.DynamicInvoke(this, this.TogglePaneButtonRect);
            }
        }

        /// <summary>
        /// Enable accessibility on each nav menu item by setting the AutomationProperties.Name on each container
        /// using the associated Label of each item.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void NavMenuItemContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args)
        {
            if (!args.InRecycleQueue && args.Item != null && args.Item is NavMenuItem)
            {
                args.ItemContainer.SetValue(AutomationProperties.NameProperty, ((NavMenuItem)args.Item).Label);
            }
            else
            {
                args.ItemContainer.ClearValue(AutomationProperties.NameProperty);
            }
        }
    }
}

What I want to achieve: (also I want to make Pane transparent, but I think this is possible easily. enter image description here

What I have: enter image description here

There is another problem with this sample: The Pane is ALWAYS open on the startup even if I do IsPaneOpen="False"

Getting Clickonce to use more recent .NET framework

I have a Clickonce application that is targeting .NET 3.5. When I install on a Windows machine with .NET 3.5 installed, it works fine. However, if I remove .NET 3.5 via Add/Remove Windows Features, and install .NET 4.5 manually, my Clickonce application gives an error: "Unable to install or run the application. The application requires that assembly WindowsBase version 3.0.0.0 be installed in the Global Assembly Cache (GAC) first." Even though the ClickOnce is targeting 3.5, shouldn't it be able to run against the .NET 4.5 Runtime if it exists? How can I configure my Clickonce application to run in this environment?

barcode scanner sdk for C# on Windows OS

I have been trying to get information about any barcode scanner with support for .Net (using c#) for a desktop application. suggestions are welcome on barcode scanners you have worked with that supports .Net and not via COM. Thanks in advance.

Assigning a value to ComboBox Items

I'm currently trying to make a drop box (Combobox) for currencies for a winform. Here's what I have so far:

Screen grab of combobox input

But I noticed that there is a special option for the Databound version of a drop down box. So I was wondering if it was possible to create something similar to this without resorting to do a comparison against the entire string or creating a table in a database.

Screen shot of combobox tasks

In C# how do I store data from list box to an database table?

I trying to get the data from my listbox and store it in a database. This program is supposed to roll 2 sets of dice 100 times. I want to store the rolls in a table so that I can sort the data using LINQ.

Please Help,

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

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

    private void button1_Click(object sender, EventArgs e)
    {
        listBoxRolls0.Items.Clear();
        listBoxRolls1.Items.Clear();

        Random rdom0 = new Random();

        int dice0;
        int dice1;

        for (int i=1;i<=100;i++)
        {
            dice0 = rdom0.Next(6)+1;
            dice1 = rdom0.Next(6)+1;

            listBoxRolls0.Items.Add(" Dice One - " + dice0 + "  Dice Two - " + dice1);
        }

        Random rdom1 = new Random();

        for (int i = 1; i < 100; i++)
        {
            dice0 = rdom1.Next(6) + 1;
            dice1 = rdom1.Next(6) + 1;

            listBoxRolls1.Items.Add(" Dice One - " + dice0 + "  Dice Two - " + dice1);
        }

        int[,] DiceRolls = new int[2,100];


    }
}
}

How to form dependency between 2 windows services

I have 2 windows services, ServiceA and ServiceB.

I would like to know how can I start ServiceA first and then start ServiceB when ServiceA is on interval.

Bind model property to resource string without adding Display(Name="")

I'm involved in ASP.NET MVC project which requires me to complete on it. Since I'm totally new to MVC approach I found something which I couldn't understand I tried to search for it but nothing been found I even don't know how to ask the question properly so excuse me.

I want to bind a model's Property to a resource string so when using @HTML.LabelFor(model => model.Property) it got rendered with the right resource string. I know that it can be binded using data anotations by adding this line in the model:

[Display(Name = "ResourceStringName", ResourceType = typeof(MyResource))]
string CompanyName {get; set;};

This approach isn't good because when I want to update my model from database it will be overwritten. But in the project that I'm working on the properties got binded to the right resource string without adding data annotations in the model but I can't figure out how to do this for a newly added property from database. Do anyone know how to bind a resource string to model property without adding data annotations ?

SignalR WebApp.Start(url) doesn't like other exe's in folder?

My WebApp.Start method throws a System.IO.FileLoadException when other exe's are in the same folder. I have no clue why this is happening and its driving me nuts. Any help is appreciated.

//Calling webapp.start
string url = "http://*:8080/";
SignalRServer = WebApp.Start(url);


//My Owin Startup Class
class Startup
{
    public void Configuration(IAppBuilder app)
    {            
        // Branch the pipeline here for requests that start with "/signalr"
        app.Map("/signalr", map =>
        {               
            map.UseCors(CorsOptions.AllowAll);
            var hubConfiguration = new HubConfiguration
            {                    
                EnableJSONP = false,                   
                EnableDetailedErrors = true,
                EnableJavaScriptProxies = true
            };                              
            map.RunSignalR(hubConfiguration);
        });
    }
}

This was working fine until I threw the service into testing for a production rollout and now it gives the following error.

System.IO.FileLoadException: Could not load file or assembly 'AutoServiceController, Version=1.0.5270.19403, Culture=neutral, PublicKeyToken=null' or one of its dependencies. Attempt to load an unverifiable executable with fixups (IAT with more than 2 sections or a TLS section.) (Exception from HRESULT: 0x80131019) File name: 'AutoServiceController, Version=1.0.5270.19403, Culture=neutral, PublicKeyToken=null' ---> System.IO.FileLoadException: Attempt to load an unverifiable executable with fixups (IAT with more than 2 sections or a TLS section.) (Exception from HRESULT: 0x80131019) at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.Assembly.Load(AssemblyName assemblyRef) at Owin.Loader.DefaultLoader.AssemblyDirScanner.d__1e.MoveNext() at Owin.Loader.DefaultLoader.SearchForStartupAttribute(String friendlyName, IList1 errors, Boolean& conflict) at Owin.Loader.DefaultLoader.GetDefaultConfiguration(String friendlyName, IList1 errors) at Owin.Loader.DefaultLoader.LoadImplementation(String startupName, IList1 errorDetails) at Owin.Loader.DefaultLoader.Load(String startupName, IList1 errorDetails) at Microsoft.Owin.Hosting.Loader.AppLoader.Load(String appName, IList`1 errors) at Microsoft.Owin.Hosting.Engine.HostingEngine.ResolveApp(StartContext context) at Microsoft.Owin.Hosting.Engine.HostingEngine.Start(StartContext context) at Microsoft.Owin.Hosting.Starter.DirectHostingStarter.Start(StartOptions options) at Microsoft.Owin.Hosting.Starter.HostingStarter.Start(StartOptions options) at Microsoft.Owin.Hosting.WebApp.StartImplementation(IServiceProvider services, StartOptions options) at Microsoft.Owin.Hosting.WebApp.Start(StartOptions options) at Microsoft.Owin.Hosting.WebApp.Start(String url) at PvValuationController.PvValuationController.OnStart(String[] args) in c:\Users\ahardy\Documents\Visual Studio 2013\Projects\PvValuationController\PvValuationController\PvValuationController.cs:line 156

FederationMetadata.xml tags generation

I'm building my FederationMetadata.xml using the great tool by Shawn Cicoria (http://ift.tt/1Ho6Ykg) and with some tweaks I'm near my correct solution.

I need to set:

  <system.identityModel.services>
    <federationConfiguration>
      <cookieHandler requireSsl="false" />
      <wsFederation passiveRedirectEnabled="true" issuer="<issuer>" realm="<realm>" requireHttps="false" />
    </federationConfiguration>
  </system.identityModel.services>

Using the tool I can't se programmatically requireSsl="false" and requireHttps="false" I get true for both of them.

And:

  <certificateValidation certificateValidationMode="PeerTrust" />
    <trustedIssuers>
      <add thumbprint="<thumbprint>" name="<cn>" />
    </trustedIssuers>
  </issuerNameRegistry>

But I can't fin a way to set certificateValidationMode="PeerTrust" and trustedIssuers section I got certificateValidationMode="None" and authority section-

Now I'm stucked because I need to se these tags on client's web.config that use my FederationMetadata, but I can't find any way to set them.

Incorrect syntax near 'Name'

I getting errors:

Incorrect syntax near 'nvarchar'.
Incorrect syntax near 'Name'.

Please help to get from this.

I also added scalar to the names (@) but I am not getting anything.

public partial class Form1 : Form
{
    SqlCommand cmd;
    SqlConnection con;

    private void button1_Click(object sender, EventArgs e)
    {
        con = new SqlConnection(@"Data Source=DELL_LAPTOP\sqlexpress;Integrated Security=True");
        con.Open();

        cmd = new SqlCommand("Insert Into newproj (Name,Designation,Gender,Age,Address,Date,Staff Name,Shift,ST,ET,Hours) Values (@Name,@Designation,@Gender,@Age,@Address,@Date,@Staff Name,@Shift,@ST,@ET,@Hours)", con);
        cmd.Parameters.Add("@Name", textBox4.Text);
        cmd.Parameters.Add("@Designation", textBox2.Text);
        cmd.Parameters.Add("@Gender", comboBox1.SelectedItem.ToString ());
        cmd.Parameters.Add("@Age", textBox3.Text);
        cmd.Parameters.Add("@Address", textBox5.Text);
        cmd.Parameters.Add("@Date", dateTimePicker1.Text);
        cmd.Parameters.Add ("@Staff Name", textBox1.Text);
        cmd.Parameters.Add ("@Shift", comboBox2.SelectedItem.ToString());
        cmd.Parameters.Add("@ST", textBox7.Text);
        cmd.Parameters.Add("@ET", textBox8.Text);
        cmd.Parameters.Add("@Hours", textBox6.Text);

        cmd.ExecuteNonQuery();       
    }
}

Integrate Okta to my project

I want to add to my api login via Okta. Unfortunately I can't seem to find any tutorial or instruction on how to do it,

Can anyone help me?

thank you very much

How to access OPC.NET 3.0 (formerly known as OPC Xi)

I want to communicate with KepServerEx using the OPC.NET WCF service.

I have configured the server as described at http://ift.tt/1MKE8BE, with all bindings enabled. Everything seems OK : the service is running, no errors are displayed in the event log, the configured ports are open (tested with telnet, netstat).

The problem is that I don’t know how to reference the service. The configuration window displays the following information:

I have tried different URI combinations to no avail. I have located the configuration file (xi_server_runtime.exe.config) , but it contains no serviceModel tag, hence no base address or endpoint information. I tried to configure a MEX endpoint as follows:

   <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="OPCNET">
                    <serviceMetadata httpGetEnabled="true"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>

        <services>
            <service behaviorConfiguration="OPCNET" name="KEPServerEXV5_OPCNET">
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
            </service>
        </services>
    </system.serviceModel>

but nothing has changed.

C# trying to open remote file location but windows not passing credentials

So, basically what I'm doing is trying to open up \\whatever\c$ on a remote workstation. I'll start by saying that the application is executed using <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> now when someone executes the application they actually use a different domain and username/password than what is used to sign onto the workstation. from within the application I can do whatever I want. but right now what I'm trying to accomplish is have a button link to \whatever\c$ and just open that up in explorer so I can look at some files, however I don't want to type in a password each time. especially considering it's the same credentials I used to open the app. any help would be appreciated. here's the current code I'm using.

            string startlocation = @"\\" + textBox1.Text + @"\C$";
            System.Diagnostics.ProcessStartInfo pcsi = new System.Diagnostics.ProcessStartInfo();
            pcsi.FileName = "explorer.exe";
            pcsi.Arguments = startlocation;
            System.Diagnostics.Process.Start(pcsi);

from what I can tell this should automatically pass the credentials used when the application was opened. but it still opens up the UAC asking for credentials. I'm stuck.

p.s. when I was looking for a similar situation on SO I noticed a lot of other people were asking how to open it with other credentials or impersonate that's not what I want to do. I want to use the credentials used for opening the app.

Validating user against AD group, throws an exception when group contains deleted object

I have some code that looks to see if a user belongs to an AD group. This code works unless a user from a foreign domain belongs to the group and has been deleted. When this happens the code will throw a PrincipalOperationException.

An error (1301) occurred while enumerating the groups. The group's SID could not be resolved.

public static bool IsGroupMember(string userName, string domain, string groupName)
{
    using (var pc = new PrincipalContext(ContextType.Domain, domain))
    {
        // Find a user
        UserPrincipal user = UserPrincipal.FindByIdentity(pc, userName);

        if (user == null)
            throw new InvalidUserException("User '" + userName + "' does not exist.");

        // Create MyDomain domain context
        using (var ctx = new PrincipalContext(ContextType.Domain, "MyDomain"))
        {
            // Find the group in question
            GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName);

            if (group == null)
                throw new InvalidGroupException("Group '" + groupName + "' does not exist.");

            // Check if user is member of that group
            if (group.GetMembers(true).Contains(user))
                return true;
            else
                return false;
        }
    }
}

What are my options. I was hoping to filter GetMembers to remove deleted objects prior to doing the Contains but have not been successful. Do I need to back away from AccountManagement and do something more manual?

What's the difference between .NET Core and PCLs?

I was writing up the supported platforms for my PCL recently, one of which is other PCLs. I was confused if my library (which targets .NET Framework 4.5 and Windows/Phone 8.1) can be used in .NET Core projects as well.

As I understand it, PCLs allow you to share code across multiple platforms without recompilation, while .NET Core does that as well. The only difference is that .NET Core targets a few more platforms, i.e. OS X and Linux, and is open source.

So essentially, I don't see how .NET Core is any different than Microsoft rebranding the PCL and going "PAY ATTENTION we're going open source and targeting non-Windows platforms!" (Someone please correct me.)

So the bottom line is, are PCLs compatible with .NET Core, and vice versa? What's the difference between them?

How to get value from textBox by it name?

I am try to get value from textBox by it's name using Control class? There is my code:

Control ctl = FindControl(this, "B1"); if (ctl is TextBox) listBox1.Items.Add(((TextBox)ctl).Text); //"B1" - it's textBox name

public static Control FindControl(Control parent, string ctlName)
    {
        foreach (Control ctl in parent.Controls)
        {
            if (ctl.Name.Equals(ctlName))
            {
                return ctl;
            }

            FindControl(ctl, ctlName);
        }
        return null;
    }

The problem is that the compiler does not go into the function. What could be the problem?

Step-by-Step ILMerge.Config.xml & MSBuild usage

I'm using ILMerge via an in-line script in my Post-Build event, in order to merge Satellite dll's and preserve all available cultures in single dlls

"C:\Program Files (x86)\Microsoft\ILMerge\ilmerge.exe" /t:library  /wildcards /targetplatform:"v4,C:\Windows\Microsoft.NET\Framework\v4.0.30319" /lib:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5" "$(OutDir)en-us\Satellite.dll"  "$(ProjectDir)bin\$(ConfigurationName)\$(TargetFileName)" /out:"$(OutDir)Merged\$(TargetFileName)"

Initially, I ran into issues merging multiple Satellite Dlls with the same name (like en-us\Satellite.dll and fr\Satellite.dll) in a single ILMerge command, but thanks to help here: Single-assembly multi-language Windows Forms deployment (ILMerge and satellite assemblies / localization) - possible?

I have found this is only an error with ILMerge, and can be circumvented by merging each Satellite DLL in a seperate merge statement.

Moving forward, you can imagine that there are currently 38 available cultures and languages in my base DLL, and managing these via 38 copies of that line of command line is overkill. On top of that, I have multiple build paths, which merge upwards into platform-specific Device Dll's, which means I have to do the same in at least 3 more places. 152 copies of that single command line (all in that tiny Post-Build popup window).

I understand looking at this page: http://ift.tt/1MKAkAu that I can create an xml configuration file for my merges and it would look something like this:

<?xml version ="1.0"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<requiredRuntime safemode="true" imageVersion="v4.0.30319" version="v4.0.30319"/>
</startup>
</configuration>

but I'm not sure how to implement it. I assume I can move ALL of the configuration parameters (like target and wildcard, lib and paths) to the ILMerge.config file and I hope I'm not wrong, though according to this page you would add it to the .csproj file: http://ift.tt/1UkYPWZ

I'd like to know: What is the command line for referencing an ILMerge.config.xml settings file in the PostBuild command?

Is the 'configuration' element enumerable? (ie, can I define multiple merges in the same config file?)

Does the config file support conditions, like Condition="'$(Configuration)' == 'Release'"?

Thanks in advance!

AutoMapper: Map null source object to decimal

I need to map an object of type PriceValue to a decimal value and I have the following mapping configured:

public class PriceValue
{
    public decimal Value { get; set; }
    ...
}

...

Mapper.CreateMap<PriceValue, decimal>()
    .ConvertUsing(src => src.Value);

The problem is when src is null an exception is thrown.

What's the best way to configure the mapping so a default(decimal) is returned instead?

Select data from 3 tables with Linq to SQL

I have 3 tables. Orders, OrderItems and OrderItemServices. Each order can contain multiple OrderItems and each OrderItem can contain multiple OrderItemServices. I want to get a list of data of all orders from these tables in Linq. I could write a join but how do I make an anonymous data type to in select clasue which can give me Order list in this hierarchy?

If I use navigation properties and then select OrderItemServices in side select clause shown below it would fire individual select query for each OrderItemService which I want to avoid.

from order in Orders
select new
{
    ActiveOrders = order,
    ActiveOrderItems =order.OrderItems,
    ActiveServices = order.OrderItems.Select(o => o.OrderItemServices)
}

Is it possible to group each order with a structure of multiple items inside it and multiple services inside items?

Internal Webservice IIS .NET

We have two sites on one IIS 7.5 server. Site B needs to talk to Site A through a SOAP service (Site B used to be external hence using SOAP, but now they are on the same server).

How can I reference Site A in Site B's web config without having a roundtrip through the absolute path http://ift.tt/1Dqg84B?

Essentially I want

      <endpoint address="foolocalhost/webservice/endpoint.asmx"
    binding="basicHttpBinding" bindingConfiguration="WebServiceSoap"
    contract="Reference.WebServiceSoap" name="WebServiceSoap" />

Rather than

      <endpoint address="http://ift.tt/1Dqg84B"
    binding="basicHttpBinding" bindingConfiguration="WebServiceSoap"
    contract="Reference.WebServiceSoap" name="WebServiceSoap" />

Would I need to change my host file to set foolocalhost up as a binding? Or is there an easier way around it using just the IIS GUI?

Given a string with day of week, return integer

Is there a way to have something like:

string day = "Sunday";
int num = getDayOfWeek(day); //returns 0

I understand we could something like, and I wanted the reverse:

int num = 0;

//returns "Sunday"
System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.DayNames[(int)i] 

The easiest way would probably be to implement a dictionary that does what I am asking, but I wonder if there is something in C# DateTime functions that already does so for me.

Implementing Tracing in VB .Net App

This is my fist attempt to get tracing up and running in a multi-class application. The examples I've followed and had success with aren't translating to the app I need to trace. I've read up on SO, MSDN and elsewhere, still missing something. Here's a snip of the code that's not generating anything in logs:

Imports System.Windows.Forms
Imports Inventor
Imports System.Runtime.InteropServices
Imports tankBuilder.MainForm
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System

Namespace tankBuilder
    <ProgIdAttribute("singleCourseMasterTank.StandardAddInServer"), _
    GuidAttribute("70f8dedc-4ae1-4bb9-be6b-c275afcd1333")> _
    Public Class StandardAddInServer
    Implements Inventor.ApplicationAddInServer
    Friend Shared PI As Double = 3.14159
    Friend Shared Tracer As New TraceSource("TraceSource1")
    ... logic...
Tracer.TraceInformation("Informational message.")
Tracer.TraceEvent(TraceEventType.Error, 1, "Error message.")
Tracer.TraceEvent(TraceEventType.Warning, 2, "Warning message.")

Here's the corresponding section from app.config

<system.diagnostics>
   <sources>
     <source name="TraceSource1"
       switchName="sourceSwitch"
       switchType="System.Diagnostics.SourceSwitch">
       <listeners>
         <add name="console"
           type="System.Diagnostics.ConsoleTraceListener">
           <filter type="System.Diagnostics.EventTypeFilter"
             initializeData="Error"/>
         </add>
         <add name="prodListener"
           type="System.Diagnostics.TextWriterTraceListener"
           initializeData="C:\Data\Projects\trace.log">
         </add>
         <remove name="Default"/>
       </listeners>
     </source>
   </sources>
   <switches>
     <add name="sourceSwitch" value="4"/>
   </switches>
</system.diagnostics>

Thanks so much in advance!

Modifying a list from another form

I am trying to set up a list in C# and I want it so that when I press the an add button it will open a window with fields where I can enter data press and ok button and then have those text box fields transferred into the list. This is my code for the popup form.

public partial class addtoLibraryDialog : Form
{
    public addtoLibraryDialog()
    {
        InitializeComponent();
    }


    private void btnOK_Click(object sender, EventArgs e)
    {
        ListViewItem list = new ListViewItem("name");
        list.SubItems.Add("path");
        listView1.Items.Add(list);
    }
}

And I was wondering how I can make it so the listview1 is recognised. I have found information on this outline but as I am new to programming I can't really make heads of tails of them.

Regex to match repeating groups only capturing one group

I want to match the string

6 cakes 5 donuts 12 muffins

into three groups viz. 6 cakes, 5 donuts, 12 muffins. To achieve this I've used the regex

([\d]{1}[\s]{1}[\w]*) 

But the problem is its only matching the first group 6 cakes and ignoring the rest. How can I change it to make the group repeating.

Scale while keep horizontal align

I have WPF control:

<UserControl x:Class="MyProject.LabelWithUnit"
             xmlns="http://ift.tt/o66D3f"
             xmlns:x="http://ift.tt/mPTqtT"
             xmlns:mc="http://ift.tt/pzd6Lm" 
             xmlns:d="http://ift.tt/pHvyf2" 
             mc:Ignorable="d" 
             d:DesignHeight="30" d:DesignWidth="150">
       <Viewbox StretchDirection="Both" Stretch="Uniform">
            <Grid Width="150">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="Auto" />
                </Grid.ColumnDefinitions>
                <Label x:Name="ValueLabel" Grid.Column="0" Content="1013.0" Margin="0" VerticalAlignment="Center" HorizontalAlignment="Center" FontWeight="Bold" FontSize="18"/>
                <Label x:Name="UnitLabel" Grid.Column="1" Content="m/s" Margin="1" FontSize="10" />
            </Grid>
        </Viewbox>
</UserControl>

Now my control behave like this: enter image description here

I want it to look like this instead, when i change width: enter image description here

So, "m/s" part should always stick to top-right corner and numeric part should stay somehow near middle. When i increase Height of my control, it should scale both Labels.

How to convert a list of tuples into a parrallel array

I am new to the functional programming and F#

I'm trying to convert a list of tuples into parallel lists, for example

let results = [("foo",3);("bar", 4)};("bazz", 8)]
// do something to convert it
// output = ["foo";"bar";"bazz"], output2 = [3;4;8]

What I attempted to was this

let issue = []
let count = []

for tpl in results do
    fst tpl |> issue
    snd tpl |> count

But obviously this wont compile.

I am getting the list of tuples from the statement

let results = IssueData |> Seq.countBy id |> Seq.toList 

How would I go about doing this?

How to measure the accruate memory usage for a code or process?

I'm trying to measure the memory usage for a code and process using Process.privateBytes and Process.workingSet but if i run the application several time, each time i have different values ?

What is the accurate way to have ~same values each times ?

Web service on IIS 7.5 suddenly ceases to work

I have developed a SOAP Service on basis of C# and .NET 4.0 (service.dll). The service internally loads a C++ DLL (cpp.dll) and does stuff. I deployed that on an IIS 7.5 running on Windows 7 and it all worked well. However, recently the service stopped working.

If I now try to create a service using the wcftestclient application shipped with Visual Studio, I get following error message:

Warning: There were errors loading types in an assembly loaded from 'C:\Windows\assembly\GAC_MSIL\System.ServiceModel\3.0.0.0__b77a5c561934e089\System.ServiceModel.dll' some types in the assembly could not be loaded and will not be available to the tool.Error: An error occurred in the tool.Error: Object reference not set to an instance of an object.

I did not touch any of the DLLs or so. Googling the error message didn't lead me anywhere, so I'm desperate now and would appreciate some help with this. What does the message mean and what should I investigate?

I can open http://myserver/myservice/service.svc?wsdl and it shows me the correct WSDL. Also, I have a command line tool which itself loads the cpp.dll and this works too, so the problem cannot be there. It has to be something with the service.dll or with the settings in IIS or with a recent Windows update screwing up my .NET environment... right?

How to get distinct items from Microsoft.Office.Interop.PowerPoint.Hyperlinks

Hi can somebody help to get distinct items from Microsoft.Office.Interop.PowerPoint.Hyperlinks using LINQ on the basis of Hyperlink.TextToDisplay and Hyperlink.Address. I want to have items with distinct values for Address and TextToDisplay.

This is what I have tried

Microsoft.Office.Interop.PowerPoint.Hyperlinks links = links.Cast<Microsoft.Office.Interop.PowerPoint.Hyperlink>().Select(p=>p.TextToDisplay).Distinct().ToList();

Thanks in Advance.

MSI is not able to access registry when I update OS

I have created a MSI project. My purpose is to create registries and assigned some values to them while installing. I am creating registry under HKEY_CURRENT_USER\Software. I have some default set of registries that I have created using Registry Editor from solution explorer. Also I have an installer class using which I have created some more registries based on some conditions. Here is my code snipet for the same:

If Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\ABCD\DB").GetValue(RegName) Is Nothing Then
                Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\ABCD\DB", True).SetValue(RegName, RegVal)
End If

Here RegName is the Registry name to be created and RegVal is the value to be set for RegName Registry.

When I am installing this MSI, Registries, which I have created at the design time by using Registry Editor using Solution Explorer, create and assign values to them successfully. But the issue is registries those are created by installer class, is not creating. It throws an exception when I tried to check weather RegName is nothing or not. Thrown exception is : "Object is not set to instance of an object". Actually it works fine for all the machine which are not having Windows update. This behaviour occurs when machine OS is updated. I dont know what is an exact issue. Why does it fail for updated machine? I have tried a lot but cant get any proper solution. Also one thing, the issue is occurs on Windows 10. When I set MSI to run for the "All user" it will give this exception. MSI will work fine if I select run MSI for "Just me" option. Waiting for appropriate suggestions. Quick response are highly appriciable.

Thanks, Ankit

X509Certificate2 PublicKey can't get the right value

hope you can help me. i'm using X509Certificate2 and X509Store to write a certificate (.pfx) into X509Store. Then i go to the dns and request the publicKey token from it, once it reply i see the publicKey i get is in Base64 wheres when i find the proper X509Certificate2 from the X509Store i cant find any way to represent publicKey to match the one i get from the dns.

how can i get the base64 representation of the public key to look like dns?!

I have already tried to use: byte[] arrBytes = certificate2.GetPublicKey(); and byte[] arrBytes = certificate2.PublicKey.EncodedKeyValue.RawData

both are not giving me the same base64 as the one i get from dns, or am i missing some thing?!

Thanks for the help :)

How not to set DatabaseGeneratedOption.Identity for Seed entities

We had BaseEntity defined as following:

public abstract class BaseEntity
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid Id { get; set; }
        ...
}

As a result of Ids were genereated by DB. However, now we are going to add Seed data. I added the following Seed code:

            Country c = new Country()
            {
                Id = new Guid("251D06A5-E864-4B9F-803B-00E409B0F5AB"),
                Name = "Oceania",
                RegionType = RegionTypeEnum.Region,
                ParentCountryId = worldId
            };
            AddOrUpdate(c);

In this case my "Id" was ignored and new Id was generated. Thus Seeds always created new countries.

Thus I do not need database to generate Id (but I want to use BaseEntity as base class). How do you suggest to deal with this?

WCF project not starting in Visual Studio, throwing "Object reference not set to an instance of an object"

When I try to run my WCF project starting from the .svc file either in Debug or Release, it just shows an alert "Object reference not set to an instance of an object". This is no error in my code, this is definitely a Visual Studio error.

The build succeeds, no errors or warnings.

I ran devenv.exe with the /log option, but the log shows nothing interesting. There are no new log entries created after the error appears.

Originally I was working in Visual Studio 2013 on Windows 8.1, but running the project in Visual Studio 2015 showed the same error. Even after reinstalling my system completely from scratch the error is still there (formatted, now running Windows 10).

I can resolve the issue when I create a new WCF project in the same solution, then copy all files into the new project and replace the namespace of the old project with the new one. Web.config settings are also identical (except for project namespace).

This error happened 3 times now and I always resolved it by copying code into a new project, which is not really an elegant solution especially as the project grows. I'm hoping to find a solution before it happens again.

Entity Framework 4.1 dont generate Id when save data

I'm trying to do something simple, but this dont work in EF 4.1,it does in EF 6, but I cant update version because I need this application in an old server and doesnt support it.

This is my code:

               chat = new Chat()
                        {
                            AdminId = 99
                        };

                        db.Chat.Add(chat);
                        db.SaveChanges();

                var cp = new List<ChatPeople>();
                        foreach (int user in usersids)
                        {
                            cp.Add(new ChatPeople
                            {
                                ChatId = chat.Id,
                                UserId = user
                            });
                        }
                        cp.ForEach(c => db.ChatPeople.Add(c));

and this is the model:

[Table("CHATS", Schema = "SCHEMA")]
    public class Chat
    {     

        [Column("ID")]
        public decimal Id { get; set; }       

        [Column("ADMINID")]
        public decimal AdminId { get; set; }

        public virtual ICollection<ChatPeople> ChatPeople { get; set; }

        public virtual ICollection<ChatHistory> ChatHistory { get; set; }
    }

(I need decimal Id because int dont work in Oracle.)

My problem is when I save Chat, this dont return the current Id of this registry in database and when in ChatPeople try to do this ChatId = chat.Id, I dont have the value. In DB Chat are saving ok with AdminId = 99 and Id = (Autonumeric-Identity)

What can I do to get Id of registry that are being saved?

Is it possible to remove a user control (.ascx) present in master page (.master) from content (.aspx) page?

I have a master page which is being inherited to a lot of content page. I have one particular page in which I do NOT want one of the user controls present in the master page. I do NOT want to create a separate master page for this. I want to know if there's any way to prevent the user control present in master page being inherited to child / content page. Appreciate your help. thanks !

Difference between .NET's System.Type.GenericTypeArguments and System.Type.GetGenericArguments()

Why does the .NET Framework provide both

System.Type.GenericTypeArguments

and

System.Type.GetGenericArguments()

which both return the type arguments (both as a Type[]) of a given generic type ?

Seems the property and the method expose the very same functionality, meaning the API's interface has redundant/duplicate functionalities ?

Razor views - @if statement compilation error

Razor views scaffolded by Visual Studio contains an "actions" element with links separated by pipe character (|)

<td>
   @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
   @Html.ActionLink("Details", "Details", new { id = item.Id }) |
   @Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>

I would like to render those links conditionally:

<td>
    @if (item.IsSuccess)
    {
        @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
        @Html.ActionLink("Details", "Details", new { id = item.Id }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.Id })
    }
</td>

The code above seems correct in Visual Studio, however execution results in an Compilation Error

Compilation Error
Description: An error occurred during the compilation of a resource required    
to service this request. Please review the following specific error details and
modify your source code appropriately.

Compiler Error Message: CS1513: Expected sign }.

Source Error:


Line 491:        }
Line 492:    }
Line 493:}

Can you please point me where is the problem? The code seems syntactially correct.

Http post and get for json -C#

How can I make an HTTP request and send Json data with Headers and read the response?

The third party had provided some credentials to use their API. Using those credentials I need to invoke the API and read the response. I need to send a header named SIGNATURE along with the request data. The value of the signature is the Encrypted Request data.

I can do the POST request but have no idea how to add the Header.

My code is like this

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("URL");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("SIGNATURE", sEncrypteddata)
using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = "{\"id\":\"2423432432\"," +
                  "\"uid\":\"id123\","+
                  "\"pwd\":\"pass\","+
                  "\"apiKey\":\"2423432432\","+
                  "\"paymentCategory\":0"+
                   "\"paymentType\":0}";

    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}
System.Net.ServicePointManager.Expect100Continue = false;
HttpWebResponse  httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    string result = streamReader.ReadToEnd();
}

is this is the correct way ?

Trying to map (AutoMapper) result of DataAccessor method causes "The ObjectContext instance has been disposed" error

This is the method that should get company types from data accessor. The result should be mapped (using AutoMapper). However, I get {"The ObjectContext instance has been disposed and can no longer be used for operations that require a connection."} during mapping. Also when I debug and look into Watch section, I see that companyTypeData has DynmaicProxies instead of List<CompanyType> ({System.Data.Entity.DynamicProxies.CompanyType_3FC9CC368D973CAD3E480E71CC0925070C9DAA04B4D2FDEA1AE8E2018EA52EE4} NNN.BO.Entities.CompanyType ...

I believe that this is related to lazyloading in EntityFramework. But I am using the architecture that was not created by me and I am not expert of EF, so I am not sure how to fix it correctly.

Here is Bll method:

public class CompanyTypeBll
    {
        private readonly ICompanyTypeAccessor _companyTypeAccessor;            
        public CompanyTypeBll()
        {
            _companyTypeAccessor = new CompanyTypeAccessor();
        }        

        public List<CompanyTypeViewModel> GetTwoLevelCompanyTypeStructure()
        {
            List<CompanyType> companyTypeData = _companyTypeAccessor.GetByFilter(x => x.ParentTypeId == null).ToList();              

            return Mapper.Map<List<CompanyTypeViewModel>>(companyTypeData);
        }
    }

Here is definition of DataAccess method "GetByFilter":

 public virtual IEnumerable<T> GetByFilter(Expression<Func<T, bool>> filter)
        {
            using (NnnDbContext context = new NnnDbContext())
            {
                return IncludeRefObjects(context.Set<T>()).Where(filter).ToList();
            }
        }     

And this is definition of CompanyType object:

public class CompanyType : BaseEntity //BaseEntity has Id and CreationDate
    {
        public string Name { get; set; }    
        public Guid? ParentTypeId { get; set; }

        #region Navigation properties    
        public virtual CompanyType ParentType { get; set; }            
        public virtual List<CompanyType> CompanySubTypes { get; set; }    
        public virtual List<Company> Companies { get; set; }    
        #endregion
    }

The ViewModel to which I am trying to map:

public class CompanyTypeViewModel
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public Guid? ParentTypeId { get; set; }
        public virtual List<CompanyTypeViewModel> CompanySubTypes { get; set; }
    }

Find Master Page Dropdown control on other Master Page ASP.net

I have two master page one is User.Master and Other is Account.Master I want to find User.Master Dropdown selected value on Account.Master Page . Please give me suggestion and help me.

how can i define "DisplayErrorMessage" in this case?

this is a code that i wrote for my open button...but i have error on "DisplayErrorMessage" part...what should i write instead? or how can i define it in order to don't error again

protected void btnOpen_Click(object sender, EventArgs e)
{
    txtFileName.Text = txtFileName.Text.Trim();
    if (txtFileName.Text == string.Empty)
    {
        string strErrorMessage = "you did Not specify file for opening!";
        DisplayErrorMessage(strErrorMessage);
    }

    string strFileName = txtFileName.Text;
    string strRootRelativePath = "~/app_data/pageContent";
    string strRootRelativePathName =
    string.Format("{0}/{1}", strRootRelativePath, strFileName);
    string strPathName = Server.MapPath(strRootRelativePathName);

    System.IO.StreamReader ostreamReader = null;

    try
    {
        ostreamReader = new System.IO.StreamReader(strPathName, System.Text.Encoding.UTF8);
        litPageMessages.Text = ostreamReader.ReadToEnd();
    }
    catch (Exception ex)
    {
        litPageMessages.Text = ex.Message;
    }
    finally
    {
        if (ostreamReader != null)
        {
            ostreamReader.Dispose();
            ostreamReader= null;
        }

    }
}

Azure Web App switches server automatically?

We have a website running in azure as a Web App. Only 1 instance of the site is running. We are seeing regular downtimes for the site, and wondering why.

We use Elmah to log exceptions, and before a downtime occurs we can't see any relevant or critical errors. What we do see however, is that AFTER the downtime, the site is back up but on another server. (We can see this because the hostname of the server changes, and when an exception is thrown we can see in Elmah from which server it originated.) Small example:

Server: X
Some small Exception thrown on server X, shows up in Elmah
site goes down
Site comes back up
Server: Y
Some small exception thrown on server Y, shows up in Elmah

Now I know that azure has Rapid Fail Protection and Auto Healing, but in our scenario, I cant tell the difference between our site

a) moving to another server and going down (because there is only 1 instance)

b) rapid fail protection or auto healing kicking in

If it's option a: does anyone know based on what azure moves sites?

if it's option b: does anyone know how I can determine why/how something triggered a rapid fail protection or auto healing kick in?

C# return before await - without starting a new Task

This is for an iOS app written in Xamarin. All my application code runs in the main thread (i.e. the UI thread).

The UI code does something as follows:

public async void ButtonClicked()
{
    StartSpinner();
    var data = await UpdateData();
    StopSpinner();
    UpdateScreen(data);
}

The UpdateData function does something as follows:

public Task<Data> UpdateData()
{
   var data = await FetchFromServer();
   TriggerCacheUpdate();
   return data;
}

TriggerCacheUpdate ends up calling the following function defined below

public Task RefreshCache()
{
    var data = await FetchMoreDataFromServer();
    UpdateInternalDataStructures();
}

My question is how should TriggerCacheUpdate be written? The requirements are:

  1. Can't be async, I don't want UpdateData and consequently ButtonClicked to wait for RefreshCache to complete before continuing.
  2. UpdateInternalDataStructures needs to execute on the main (UI) thread, i.e. the thread that all the other code shown above executes on.

Here are a few alternatives I came up with:

public void TriggerCacheUpdate()
{
    RefreshCache();
}

The above works but generates a compiler warning. Moreover exception handling from RefreshCache doesn't work.

public void TriggerCacheUpdate()
{
    Task.Run(async() =>
    {
        await RefreshCache();
    });
}

The above violates requirement 2 as UpdateInternalDataStructures is not executed on the same thread as everything else.

A possible alternative that I believe works is:

private event EventHandler Done; 
public void TriggerCacheUpdate()
{
    this.task = RefreshCache();
    Done += async(sender, e) => await this.task;
}

Task RefreshCache() {
    var data = await FetchMoreDataFromServer();
    UpdateInternalDataStructures();
    if (Done != null) {
       Done(this, EventArgs.Empty);
    }
}

Does the above work? I haven't ran into any problems thus far with my limited testing. Is there a better way to write TriggerCacheUpdate?

Log4net rolling daily - Format of filename with date

I want My log file something like this date.filename.txt. which rolls out new file everyday.

i am able to generate file in this format filename.date.txt. By using the below configuration

 <appender name="SLSILogFileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" >
  <converter>
    <name value="logfilename" />
    <type
   value="FilenamePatternConverter" />
  </converter>

  <conversionPattern
    value="%property{TestURL}%logfilename{LocalApplicationData}" />
</file>
<appendToFile value="true" />
<rollingStyle value="Date" />
<staticLogFileName value="false" />
<datePattern value="'.'yyyy.MM.dd'.log'" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
</appender>

I've tried a lot of things but nothing helps.