mardi 4 août 2015

Parse SQL INSERT-statement with RegEx

I need to parse SQL to get all:

  • Table names after INSERT clause,
  • Tables after FROM, JOINs (including CROSS JOIN as comma ',' operator) clauses,
  • The same with OPENQUERY or any other subqueries.

Each statement is one-liner SQL, without any extra spaces, comments, or new lines. Each query is INSERT-statement.

I have almost working regex: http://ift.tt/1HoUetJ.

But it has a problem: regex cathes only first FROM/JOIN statement. Or only last if I apply greedy quantificators.

Ideal result is syntax tree. But simple list of named group will be sufficient.



via Chebli Mohamed

DocumentDb write within a transactionscope

I am trying to use a DocumentDb write as a part of a transaction like below -

using (var scope = new TransactionScope)
{
//first transaction

//write to document db

//third transaction
}

I observed that if the third transaction fails, documentDb write is not rolled back and I still see the document in the collection. The first transaction (NEventStore in this case) rolls back perfectly. Does anyone know if DocumentDb supports TrnasactionScope. What if I have a nested transaction?

Thanks!



via Chebli Mohamed

Determine if anonymous type's property is a generic collection

I need a method to cycle through each object's properties and log the property name and value. On occasion, however, I hit a property that is a list object and the whole thing crashes. I've gather the condition below from various SO posts but it returns false every time. Wondering how to test if your method property is a generic collection type?

Class Definition

public class DtccProducer
{
    public string ProducerDateOfBirth { get; set; }
    public string ProducerGender { get; set; }
    public string TransactionType { get; set; }
    public List<BigAddress> Addresses { get; set; }
    public List<BigCommunicationItem> Communications { get; set; }
}

Method

    private static void ParseProducer(object obj)
    {
        StringBuilder s = new StringBuilder();
        Type objType = obj.GetType();

        foreach (PropertyInfo info in objType.GetProperties())
        {
            string key = info.Name;

            Type propType = info.PropertyType;

            if (propType.IsGenericType && typeof(ICollection<>).IsAssignableFrom(propType.GetGenericTypeDefinition()))
            {
                // This condition never passes - always evaluates to false
            }
            else
            {
                string value = (string) info.GetValue(obj, null);
                _sb.AppendLine(key + ": " + value);                    
            }
        }
    }



via Chebli Mohamed

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?



via Chebli Mohamed

C# reflection and Func

I have 3 classes, each have same function names:

class A {Func<sampleobject,bool> alpha = c=>c.some1 == something;Func<object,bool> beta= c=>c.some1 == something;}
class B {Func<sampleobject,bool> alpha = c=>c.some1 == something;Func<sampleobject,bool> beta= c=>c.some1 == something;}
class C{Func<sampleobject,bool> alpha = c=>c.some1 == something;Func<sampleobject,bool> beta= c=>c.some1 == something;}

I have a factory that will get me the proper class. there's also another property that will determine which function of the class gets called.

dbcontext.sampleobjects.where(Factory(class).ReflectionFunction(memberName));

I was able to use reflection to get the member name via:

var prop = this.GetType().GetMember("alpha");

I just don't know how to use this or what to call to be able to be used in the "WHERE" statement like if I would call it directly.

dbcontext.sampleobjects.where(instanceofA.alpha);



via Chebli Mohamed

Convert a literal improperly encoded string (e.g., "ñ") to ISO-8859-1 (Latin1) H

Without going into too much detail, I have a C# WCF application that is a wrapper for an XML based API I am calling. That API returns a string, which is really just an XML document. I then parse that XML, and return it. That returned information is displayed in the browser as JSON.

A bit confusing, but here is some sampled code:

[OperationContract]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Bare,
    ResponseFormat = WebMessageFormat.Json, UriTemplate = "/TestGetUser")]
TestGetUserResponse TestGetUser();

/* ... */

[DataContract(Namespace = "http://ift.tt/1P4PaB1", Name = "TestGetUser")]
public class TestGetUserResponse
{
    [DataMember]
    public User User { get; set; }
    [DataMember]
    public Error Error { get; set; }
}

And TestGetUser being:

public TestGetUserResponse TestGetUser() {
    WebClient client = getCredentials(domain); //Defined elsewhere

    string apiUrl = "http://ift.tt/1IWjVJs";
    string apiRequest = "<?xml version='1.0' encoding='utf-8' ?><test>My XML Request Lives Here</test>";

    string result = client.UploadString(apiUrl, apiRequest);

    XmlDocument user = new XmlDocument();
    user.LoadXml(result);

    userNode = user.SelectSingleNode("/my[1]/xpath[1]/user[1]");

    return new TestGetUserResponse {
        Error = new Error(),
        User = new User {
            Name = userNode.SelectSingleNode("name[1]").InnerText,
            Email = userNode.SelectSingleNode("email[1]").InnerText,
            ID = System.Convert.ToInt32(userNode.SelectSingleNode("id[1]").InnerText)
        }
    };
}

So, when I hit my URL from a browser, it returns a JSON string, like below:

{
    "Error": {
        "ErrorCode": 0,
        "ErrorDetail": null,
        "ErrorMessage":"Success"
    },
    "User": {
        "Name": "John Smith",
        "Email": "john.smith@example.com",
        "ID": 12345
    }
}

Now, my problem is, sometimes the string that is returned (directly from the API) is a badly encoded UTF-8 string (I think? I could be getting this a bit wrong). For example, I may get back:

{
    "Error": {
        "ErrorCode": 0,
        "ErrorDetail": null,
        "ErrorMessage":"Success"
    },
    "User": {
        "Name": "Jose Nuñez",
        "Email": "jose.nunez@example.com",
        "ID": 54321
    }
}

Notice the ñ in the Name property under the User object.

My question is, how can I convert this improperly encoded string to a ñ, which is what it should be?

I've found a bunch of posts

But none seem to be exactly what I need, or trying to borrow from those posts have failed.

So, to make my question as possible,

If I have a variable in a C# (.NET 3.5) application that when I write it out to the screen get's written as 'ñ', how can I "re-encode" (may be wrong word) so that it outputs as 'ñ'?

Thanks in advance.



via Chebli Mohamed

Fresh Install Visual Studio 2013

I am getting an error message that reads as follows when I try to create a new emty web project:

"Configuring IIS Express failed with the following error:

Unable to access the IIS metabase. You do not have sufficient privilege to access IIS web sites on your machine."

I am an Administrator account, and run VS2013 as administrator I tried the fix found at this link

Error - Unable to access the IIS metabase

I didn't understand the answer and don't have enough rep to comment and ask. When Altron suggests how to fix it, I clicked through the folders, and said continue, but I don't understand what he meant by "Changing the shortcut back to "Run as me"". This might not be my issue, but if it is can someone please clarify for me what he means or how to fix this? Thank you



via Chebli Mohamed

How do i strip a section of a folder in C

I have a script that reads email in Outlook for Web, generates the folder structure by parsing the subject line, then downloads the file into the folder it just created.

    foreach (Item myItem in findResults.Items)
            {
                if (myItem is EmailMessage)
                {
                    Console.WriteLine((myItem as EmailMessage).Subject);
                    string strSubject = (myItem as EmailMessage).Subject;
                    string[] strDelimiters = { " - ", " - " };
                    string []strTemp;
                    string []strFolders;
                    string strFileUrl;
                    strTemp = strSubject.Split(strDelimiters, StringSplitOptions.None);

                    strDelimiters[0] = " "; strDelimiters[1] = " ";
                    strFolders = strTemp[1].Split(strDelimiters, 2, StringSplitOptions.None);
                    strFolders[1] = strFolders[1].Replace('>', '_');

so when it parses a subject like this:

    Falcon - MCCP_1507_031_AA en-US>de-DE - **Task file uploaded** - 20178544 -  -  - 10213-022XX1 - FF

it produces a folder structure like this:

    \MCCP_1507_031_AA\en-US_de-DE\

My question is: what should I add to this to this code in order for it to drop the two letters after the last underscore (in this particular case _AA)? I would like the folder structure to look like:

    \MCCP_1507_031\en-US_de-DE\

This is my first post, I hope I did everything correctly. Thanks!



via Chebli Mohamed

saving records with text boxes combo boxes and datepicker and datagrid on the form

when i click save on a order entry form nothing is prompted and form closes as it should do but no record in the SQL server database so its so long thought i would post the whole code

 Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms
Imports System.Xml
Imports System.Configuration

Public Class purchaseorderinput

    Public Sub SELECTText(ctr As TextBox)
        ctr.SelectionStart = 0
        ctr.SelectionLength = Len(ctr.Text)
    End Sub
    Dim connectionString As String = "Data Source=.\SQLEXPRESS;Initial Catalog=StockMasterv5;Trusted_Connection=True"
    ' Dim connectionString As New SqlConnection(gstrDSN)
    Dim connection As New SqlConnection(connectionString)
    Dim cmd As SqlCommand
    Dim curDel As Decimal
    Dim curCom As Decimal
    Dim curFactor As Decimal
    Dim strSQL As String
    Dim strShop As String
    Dim strStock As String
    Dim strWarehouse As String
    Dim strStockCode As String
    Dim delid As Integer
    ' Create a DataSet
    Dim cbodata As New DataSet()
    Dim adata As New DataSet()
    Dim ddata As New DataSet()
    Dim pdata As New DataSet()
    Dim bdata As New DataSet()
    Dim cdata As New DataSet()
    Dim udata As New DataSet()
    Private detailsBindingSource As New BindingSource()
    Dim edata As New DataSet()
    Dim InsertCommand As New SqlCommand
    Dim UpdateCommand As New SqlCommand
    Dim DeleteCommand As New SqlCommand
    Dim StockDataAdapter As New SqlDataAdapter("SELECT * FROM tblStock WHERE StockCode='" & strStock & "') Like '" & strStock & "*'))", connection)
    Dim SuppliersDataAdapter As New SqlDataAdapter("SELECT * from tblSuppliers where SupplierRef ='" & strShop & "') LIKE '" & strShop & "*'))", connection)
    Dim WarehouseDataAdapter As New SqlDataAdapter("Select * from tblWarehouses WHERE WarehouseRef LIKE '%" & strWarehouse & "%'", connection)
    'Dim DeliveryDataAdapter As New SqlDataAdapter("SELECT * from tblDeliveries", connection)
    Dim DeliveryIDDA As New SqlDataAdapter("Select Max(DeliveryID) as MaxRef from tblDeliveries ", connection)

    Dim useridda As New SqlDataAdapter("SELECT LoginCode from tblEmployee where DefaultEmp = 1", connection)
    '  Dim SettingsDataAdapter As New SqlDataAdapter("SELECT * from tblCompanyDetails", connection)
    Dim SeasonDataAdapter As New SqlDataAdapter("SELECT SeasonName from tblSeasons", connection)

    Private Sub PurchaseOrderinput_Load(sender As Object, e As EventArgs) Handles Me.Load
        adata.Locale = System.Globalization.CultureInfo.InvariantCulture
        cbodata.Locale = System.Globalization.CultureInfo.InvariantCulture
        If Form1.txtMode.Text = "NEW" Then myNew()
        If Form1.txtMode.Text = "OLD" Then myOld()
        If Form1.txtMode.Text = "DELETE" Then myDelete()
        Try
            connection.Open()
            SeasonDataAdapter.Fill(cbodata, "tblSeasons")
            '  SettingsDataAdapter.Fill(adata, "tblCompanyDetails")
            ' cboCurrentSeason.DataSource = cbodata
            ' cboCurrentSeason.DisplayMember = "SeasonName"
            ' cboCurrentSeason.ValueMember = "SeasonName"
            For Each dRow As DataRow In cbodata.Tables("tblSeasons").Rows
                cboCurrentSeason.Items.Add(dRow.Item(0).ToString)
            Next

            connection.Close()

        Catch ex As SqlException
            Return
        End Try
    End Sub
    Private Sub myNew()
        cmdAdd.Text = "Add"
        cmdCancel.Text = "Cancel"
        cmdClear.Text = "Clear"
        ' Dim dt As DataTable
        Dim DeliveryDataAdapter As New SqlDataAdapter
        DataGridView1.ColumnCount = 7
        DataGridView1.Columns(0).Name = "LineID"
        DataGridView1.Columns(1).Name = "DeliveryID"
        DataGridView1.Columns(2).Name = "StockCode"
        DataGridView1.Columns(3).Name = "TotalGarments"
        DataGridView1.Columns(4).Name = "Totalhangers"
        DataGridView1.Columns(5).Name = "TotalBoxes"
        DataGridView1.Columns(6).Name = "NetAmount"

        DataGridView1.Columns.Item(0).Visible = False
        DataGridView1.Columns.Item(1).Visible = False
        DataGridView1.Columns.Item(2).HeaderText = "Stock Code"
        DataGridView1.Columns.Item(3).HeaderText = "Garments"
        DataGridView1.Columns.Item(4).HeaderText = "Hangers"
        DataGridView1.Columns.Item(5).HeaderText = "Boxes"
        DataGridView1.Columns.Item(6).HeaderText = "Cost"
        DataGridView1.Columns.Item(2).Width = "100"
        DataGridView1.Columns.Item(3).Width = "80"
        DataGridView1.Columns.Item(4).Width = "70"
        DataGridView1.Columns.Item(5).Width = "70"
        DataGridView1.Columns.Item(6).Width = "80"
    End Sub
    Private Sub myOld()
        Dim DeliveryDataAdapter As New SqlDataAdapter("SELECT * from tblDeliveries", connection)
        cmdAdd.Text = "OK"
        cmdClear.Visible = False
        cmdCancel.Text = "Cancel"
        OLDRecord()
    End Sub
    Private Sub myDelete()
        Dim i As Integer
        Dim a As String
        Dim b As String
        i = Form1.DataViewer.CurrentRow.Index
        '  a = Form1.DataViewer.Item(7, i).Value
        ' b = Form1.DataViewer.Item(8, i).Value
        a = Form1.DataViewer.Item(0, i).Value
        b = Form1.DataViewer.Item(0, i).Value
        DeleteCommand.Connection = connection
        DeleteCommand.Connection.Open()
        DeleteCommand.CommandType = CommandType.Text
        DeleteCommand.CommandText = "DELETE FROM tblStockMovements WHERE MovementType ='1' AND Reference='" & a & "'"
        DeleteCommand.ExecuteNonQuery()
        DeleteCommand.Connection.Close()
        DeleteCommand.Connection = connection
        DeleteCommand.Connection.Open()
        DeleteCommand.CommandType = CommandType.Text
        DeleteCommand.CommandText = "DELETE FROM tblDeliveries WHERE DeliveryID='" & b & "'"
        DeleteCommand.ExecuteNonQuery()
        DeleteCommand.Connection.Close()
        DeleteCommand.Connection.Open()
        DeleteCommand.CommandType = CommandType.Text
        DeleteCommand.CommandText = "DELETE FROM tblDeliveryLines WHERE DeliveryID='" & b & "'"
        DeleteCommand.ExecuteNonQuery()
        DeleteCommand.Connection.Close()
        Me.Close()
    End Sub
    Private Sub cmdAddItem_Click(sender As Object, e As EventArgs) Handles cmdAddItem.Click
        Dim rowNum As Integer = DataGridView1.Rows.Add()
        ' TextBox22.Text = FormatCurrency(TextBox22.Text, 2, TriState.True)
        With DataGridView1

            .Rows(rowNum).Cells(0).Value = TextBox24.Text
            .Rows(rowNum).Cells(1).Value = TextBox12.Text
            .Rows(rowNum).Cells(2).Value = TextBox18.Text
            .Rows(rowNum).Cells(3).Value = TextBox19.Text
            .Rows(rowNum).Cells(4).Value = TextBox20.Text
            .Rows(rowNum).Cells(5).Value = TextBox21.Text
            .Rows(rowNum).Cells(6).Value = TextBox22.Text
            curDel = CDec(textbox6.Text)
            curCom = CDec(textbox7.Text)
            curFactor = (curDel + curCom)
            CalculateTotals()
        End With
        TextBox24.Text = ""
        TextBox18.Text = ""
        TextBox19.Text = ""
        TextBox20.Text = ""
        TextBox21.Text = ""
        TextBox22.Text = ""
    End Sub

    Private Sub TextBox1_LostFocus(sender As Object, e As EventArgs) Handles TextBox1.LostFocus

    End Sub

    Private Sub txtCommission_LostFocus(sender As Object, e As EventArgs) Handles textbox7.LostFocus
        textbox7.Text = FormatCurrency(textbox7.Text, 2, TriState.True)
        CalculateTotals()
    End Sub

    Private Sub txtDeliveryCharge_LostFocus(sender As Object, e As EventArgs) Handles textbox6.LostFocus
        textbox6.Text = FormatCurrency(textbox6.Text, 2, TriState.True)
        CalculateTotals()
    End Sub

    Private Sub cmdFindSupplier_Click(sender As Object, e As EventArgs) Handles cmdFindSupplier.Click
        If TextBox13.Text = "" Then MsgBox("Please Enter a Supplier Reference", MsgBoxStyle.Information, "Stock Master V2")
        If TextBox13.Text <> "" Then FindShop()
    End Sub
    Public Sub FindShop()
        Dim sql As String = "Select * from tblSuppliers where SupplierRef='" & TextBox13.Text & "'"
        Dim zdataa As New SqlDataAdapter(sql, connection)
        Dim dt As New DataSet
        zdataa.Fill(dt, "tblSuppliers")
        Dim dr As DataRow = dt.Tables(0).Rows(0)
        Try
            If dr.Table.Rows.Count - 1 > 0 Then
                MsgBox("Please Enter a Supplier Reference", MsgBoxStyle.Critical, "Stock Master v2")

            Else
                DataGridView2.DataSource = dt.Tables(0)
                TextBox14.Text = dr("SupplierName").ToString
            End If
        Catch ex As SqlException
            MsgBox("Please Enter a Supplier Reference", MsgBoxStyle.Critical, "Stock Master v2")
        End Try

    End Sub
    Public Sub FindWarehouse()

        Dim sql As String = "Select * from tblWarehouses where WarehouseRef='" & TextBox15.Text & "'"
        Dim zdataa As New SqlDataAdapter(sql, connection)
        Dim dt As New DataSet
        If TextBox15.Text = "" Then
            sql = "Select * from tblWarehouses"
        End If
        zdataa.Fill(dt, "tblWarehouses")
        Dim dr As DataRow = dt.Tables(0).Rows(0)
        DataGridView2.DataSource = dt.Tables(0)
        TextBox17.Text = dr("WarehouseName").ToString

        If dr("WarehouseType").ToString = "False" Then TextBox16.Text = "Active"

        If dr("WarehouseType").ToString = "True" Then TextBox16.Text = "Long Term"



    End Sub
    Public Sub FindStock()
        Dim sql As String = "Select * from tblStock where SupplierRef='" & TextBox13.Text & "'"
        Dim zdataa As New SqlDataAdapter(sql, connection)
        Dim dt As New DataSet
        If TextBox13.Text = "" Then
            MsgBox("Select A Supplier", MsgBoxStyle.Exclamation, "Stock Master v2")
            TextBox13.Select()
        End If
        zdataa.Fill(dt, "tblStock")
        Dim dr As DataRow = dt.Tables(0).Rows(0)
        DataGridView2.DataSource = dt.Tables(0)
        If dr.Table.Rows.Count - 1 > 0 Then
            TextBox18.Text = dr("StockCode").ToString
        Else
            MsgBox("Please Create Stock Record", MsgBoxStyle.Exclamation, "Stock Master v2")
        End If

        '   If dr("WarehouseType").ToString = "False" Then TextBox16.Text = "Active"

        'If dr("WarehouseType").ToString = "True" Then TextBox16.Text = "Long Term"
    End Sub
    Private Sub getStock()
        strStock = TextBox18.Text
        If Trim(strStock) <> "" Then
            connection.Open()
            StockDataAdapter.Fill(cdata, "tblStock")
            TextBox18.Text = cdata.Tables("tblStock").Rows(0).Item("StockCode")
        Else
            Call FindStock()
        End If
    End Sub
    Private Sub getWarehouse()
        strWarehouse = TextBox15.Text
        If Trim(strWarehouse) <> "" Then
            connection.Open()
            ' Dim str As String = "Data Source=.;uid=sa;pwd=123;database=master"
            ' Dim con As New SqlConnection(str)
            ' Dim cmd As New SqlCommand("select * from logn where username like '%" + TextBox1.Text + "%'", con)
            ' Dim Adpt As New SqlDataAdapter(cmd)
            ' Dim ds As New DataSet()
            ' If (Adpt.Fill(ds, "logn")) Then
            'DataGridView1.DataSource = ds.Tables(0)

            'MessageBox.Show("match found")
            'Else
            '   MessageBox.Show("match not found")
            'End If
            WarehouseDataAdapter.Fill(bdata, "tblWarehouses")
            TextBox16.Text = bdata.Tables("tblWarehouses").Rows(0).Item("WarehouseName")
            connection.Close()
        Else
            Call FindWarehouse()
        End If
    End Sub
    Private Sub getshop()
        strShop = TextBox13.Text
        If Trim(strShop) <> "" Then

            connection.Open()
            SuppliersDataAdapter.Fill(adata, "tblSuppliers")
            TextBox14.Text = adata.Tables("tblSuppliers").Rows(0).Item("ShopName")
        Else
            Call FindShop()
        End If

    End Sub

    Private Sub TabPage2_Click(sender As Object, e As EventArgs) Handles TabPage2.Click

    End Sub

    Private Sub cmdFindWarehouse_Click(sender As Object, e As EventArgs) Handles cmdFindWarehouse.Click
        FindWarehouse()
    End Sub

    Private Sub cmdFindStockCode_Click(sender As Object, e As EventArgs) Handles cmdFindStockCode.Click
        FindStock()
    End Sub

    Private Sub TextBox13_LostFocus(sender As Object, e As EventArgs) Handles TextBox13.LostFocus
        FindShop()
    End Sub

    Private Sub TextBox15_LostFocus(sender As Object, e As EventArgs) Handles TextBox15.LostFocus
        FindWarehouse()
    End Sub

    Private Sub TextBox18_LostFocus(sender As Object, e As EventArgs) Handles TextBox18.LostFocus
        TextBox1.Text = TextBox18.Text
        FindStock()
    End Sub

    Private Sub cmdAdd_Click(sender As Object, e As EventArgs) Handles cmdAdd.Click
        If cmdAdd.Text = "Add" Then AddRecord()
        If cmdAdd.Text = "OK" Then Close()

    End Sub
    Private Function GetNextRef() As Integer
        On Error Resume Next
        Dim nextref As Integer

        DeliveryIDDA.Fill(ddata, "tblDeliveries")
        If ddata.Tables("tblDeliveries").Rows Is Nothing Then nextref = "1"
        If ddata.Tables("tblDeliveries").Rows.Count > 0 Then nextref = ddata.Tables("tblStockMovements").Rows(0).Item("MaxRef")
        TextBox12.Text = nextref + 1

    End Function
    Public Function AddRecord() As Boolean

        Dim blnTran As Boolean
        Dim lngNextRef As Integer
        AddRecord = False
        blnTran = True
        'Transfer Out 
        Dim username As String


        Dim stockcode As String
        Dim delgarm As String
        Dim delhang As String
        Dim delbox As String
        Dim delnet As String

        DeliveryIDDA.Fill(edata, "tblDeliveries")
        useridda.Fill(udata, "tblEmployee")
        username = udata.Tables(0).Rows(0).Item(0)
        Dim STR1 As String

        Try
            'Dim updatedb As String = " INSERT tblStock SET StockCode = @StockCode,SupplierRef = @SupplierRef,Season = @Season,DeadCode = @DeadCode,DeliveredQtyHangers = @DeliveredQtyHangers,RemoveFromClearance = @RemoveFromClearance,AmountTaken= @AmountTaken, CostValue = @CostValue,PCMarkUp = @PCMarkUp,ZeroQty= @ZeroQty,CreatedBy = @CreatedBy,CreatedDate= @CreatedDate WHERE StockCode = @StockCode"
            Dim insertdb As String = "INSERT INTO tblDeliveries(OurRef,SupplierRef,WarehouseRef,Season,TotalGarments,TotalBoxes,TotalHangers,NetAmount,DeliveryCharge,Commission,GrossAmount,DeliveryDate,DeliveryType,ConfirmedDate,Notes,Invoice,Shipper,ShipperInvoice,CreatedBy,CreatedDate) VALUES(@OurRef,@SupplierRef,@WarehouseRef,@Season, @TotalGarments, @TotalBoxes, @TotalHangers,@NetAmount,@DeliveryCharge,@Commission,@GrossAmount, @DeliveryDate,@DeliveryType,@ConfirmedDate, @Notes,@Invoice, @Shipper, @ShipperInvoice,@CreatedBy, @CreatedDate"


            Dim connection As New SqlConnection(connectionString)
            ' Create a DataSet
            Me.Validate()
            Dim com As New SqlCommand

            'Transfer Out
            lngNextRef = GetNextRef()
            com.Connection = connection
            com.Connection.Open()
            com.CommandType = CommandType.Text
            com.CommandText = insertdb
            com.Parameters.Add("@SupplierRef", SqlDbType.NVarChar)
            com.Parameters.Add("@OurRef", SqlDbType.NVarChar)
            com.Parameters.Add("@WarehouseRef", SqlDbType.NVarChar)
            com.Parameters.Add("@Season", SqlDbType.NVarChar)
            com.Parameters.Add("@TotalGarments", SqlDbType.Float)
            com.Parameters.Add("@TotalBoxes", SqlDbType.NVarChar)
            com.Parameters.Add("@TotalHangers", SqlDbType.NVarChar)
            com.Parameters.Add("@NetAmount", SqlDbType.NVarChar)
            com.Parameters.Add("@DeliveryCharge", SqlDbType.NVarChar)
            com.Parameters.Add("@Commission", SqlDbType.NVarChar)
            com.Parameters.Add("@GrossAmount", SqlDbType.NVarChar)
            com.Parameters.Add("@DeliveryDate", SqlDbType.NVarChar)
            com.Parameters.Add("@DeliveryType", SqlDbType.NVarChar)
            com.Parameters.Add("@ConfirmedDate", SqlDbType.Date)
            com.Parameters.Add("@Notes", SqlDbType.NVarChar)
            com.Parameters.Add(" @Invoice", SqlDbType.NVarChar)
            com.Parameters.Add("@Shipper", SqlDbType.NVarChar)
            com.Parameters.Add("@ShipperInvoice", SqlDbType.NVarChar)
            com.Parameters.Add("@CreatedBy", SqlDbType.NVarChar)
            com.Parameters.Add("@CreatedDate", SqlDbType.Date)
            com.Parameters.Add("@SupplierRef", SqlDbType.NVarChar).Value = TextBox13.Text
            com.Parameters("@OurRef").Value = TextBox1.Text
            com.Parameters("@WarehouseRef").Value = TextBox15.Text
            com.Parameters("@Season").Value = cboCurrentSeason.Text
            com.Parameters("@TotalGarments").Value = textbox9.Text
            com.Parameters("@TotalBoxes").Value = textbox10.Text
            com.Parameters("@TotalHangers").Value = textbox11.Text
            com.Parameters("@NetAmount").Value = textbox5.Text
            com.Parameters("@DeliveryCharge").Value = textbox6.Text
            com.Parameters("@Commission").Value = textbox7.Text
            com.Parameters("@GrossAmount").Value = textbox8.Text
            com.Parameters("@DeliveryDate").Value = DateTimePicker1.Value

            com.Parameters("@DeliveryType").Value = cboType.Text
            If cboType.Text = "Confirmed" Then
                com.Parameters("@ConfirmedDate").Value = Now
            Else
                com.Parameters("@ConfirmedDate").Value = ""
            End If
            com.Parameters("@Notes").Value = TextBox23.Text
            com.Parameters(" @Invoice").Value = TextBox4.Text
            com.Parameters("@Shipper").Value = TextBox2.Text
            com.Parameters("@ShipperInvoice").Value = TextBox3.Text
            com.Parameters("@CreatedBy").Value = username
            com.Parameters("@CreatedDate").Value = Now
            com.ExecuteNonQuery()
            com.Connection.Close()
            connection.Open()
            DeliveryIDDA.Fill(edata, "tblDeliveries")
            delid = edata.Tables("tblDeliveries").Rows(0).Item("DeliveryID")
            TextBox12.Text = delid
            connection.Close()
            'Transfer In
            com.Connection.Open()
            For x As Integer = 0 To DataGridView1.Rows.Count - 1
                'Copies1 = DataGridView1.Rows(x).Cells(1).Value
                delbox = DataGridView1.Rows(x).Cells(4).Value
                stockcode = DataGridView1.Rows(x).Cells(2).Value
                delnet = DataGridView1.Rows(x).Cells(6).Value
                delgarm = DataGridView1.Rows(x).Cells(3).Value
                delhang = DataGridView1.Rows(x).Cells(4).Value
                STR1 = "INSERT INTO DeliveryLines(DeliveryID,StockCode,DeliveredQtyGarments,DeliveredQtyBoxes,DeliveredQtyHangers,NetAmount) VALUES (@DeliveryID, @StockCode,@DeliveredQtyGarments,@DeliveredQtyBoxes,@DeliveredQtyHangers,@NetAmount)"
                Dim Comm As New SqlCommand(STR1, connection)

                Comm.Parameters.Add("@DeliveryID", SqlDbType.NVarChar).Value = delid
                Comm.Parameters.Add("@StockCode", SqlDbType.NVarChar).Value = stockcode
                Comm.Parameters.Add("@DeliveredQtyGarments", SqlDbType.NVarChar).Value = delgarm
                Comm.Parameters.Add("@DeliveredQtyHangers", SqlDbType.Float).Value = delhang
                Comm.Parameters.Add("@NetAmount", SqlDbType.Float).Value = delnet
                Comm.ExecuteNonQuery()
                '  DeliveryDataAdapter.Update(Me.edata)
            Next
            connection.Close()
            'Dim updatedb As String = " INSERT tblStock SET StockCode = @StockCode,SupplierRef = @SupplierRef,Season = @Season,DeadCode = @DeadCode,DeliveredQtyHangers = @DeliveredQtyHangers,RemoveFromClearance = @RemoveFromClearance,AmountTaken= @AmountTaken, CostValue = @CostValue,PCMarkUp = @PCMarkUp,ZeroQty= @ZeroQty,CreatedBy = @CreatedBy,CreatedDate= @CreatedDate WHERE StockCode = @StockCode"
            Dim insertstocmove As String = " INSERT INTO tblStockMovements (StockCode,SupplierRef,Location,LocationType,MovementQtyHangers,MovementQtyBoxes,MovementDate,MovementValue,Reference,TransferReference,CreatedBy,CreatedDate)VALUES(@StockCode,@SupplierRef,@Location,@LocationType,@MovementQtyHangers,@MovementQtyBoxes,@MovementDate,@MovementValue,@Reference,@TransferReference,@CreatedBy,@CreatedDate)"
            ' Create a DataSet
            Me.Validate()
            Dim com4 As New SqlCommand(insertstocmove, connection)
            'Transfer Out
            lngNextRef = GetNextRef()
            com4.Connection.Open()
            ' com.Parameters.AddWithValue("@StockmovementID", lngNextRef)
            com4.Parameters.AddWithValue("@StockCode", TextBox1.Text)
            com4.Parameters.AddWithValue("@SupplierRef", TextBox13.Text)
            com4.Parameters.AddWithValue("@Location", TextBox15.Text)
            com4.Parameters.AddWithValue("@LocationType", TextBox16.Text)
            com4.Parameters.AddWithValue("@MovementType", "1")
            com4.Parameters.AddWithValue("@MovementQtyHangers", textbox10.Text)
            com4.Parameters.AddWithValue("@MovementQtyBoxes", textbox11.Text)
            com4.Parameters.AddWithValue("@MovementValue", textbox8.Text)
            com4.Parameters.AddWithValue("@Reference", TextBox12.Text)
            com4.Parameters.AddWithValue("@TransferReference", TextBox12.Text)
            com4.Parameters.AddWithValue("@MovementDate", DateTimePicker1.Value)
            com4.Parameters.AddWithValue("@CreatedBy", username)
            com4.Parameters.AddWithValue("@CreatedDate", Now)
            com4.ExecuteNonQuery()
            com4.Connection.Close()
        Catch ex As Exception

        End Try

        AddRecord = True
        Exit Function
    End Function

    Public Sub OLDRecord()


        Dim i As Integer
        i = Form1.DataViewer.CurrentRow.Index
        TextBox12.Text = Form1.DataViewer.Item(0, i).Value
        TextBox1.Text = Form1.DataViewer.Item(1, i).Value
        TextBox13.Text = Form1.DataViewer.Item(2, i).Value
        TextBox14.Text = Form1.DataViewer.Item(3, i).Value
        cboCurrentSeason.Text = Form1.DataViewer.Item(3, i).Value.ToString
        TextBox15.Text = Form1.DataViewer.Item(5, i).Value
        textbox9.Text = Form1.DataViewer.Item(6, i).Value
        textbox10.Text = Form1.DataViewer.Item(7, i).Value
        textbox11.Text = Form1.DataViewer.Item(8, i).Value
        textbox5.Text = Form1.DataViewer.Item(9, i).Value
        textbox6.Text = Form1.DataViewer.Item(10, i).Value
        textbox7.Text = Form1.DataViewer.Item(11, i).Value
        textbox8.Text = Form1.DataViewer.Item(12, i).Value
        '    DateTimePicker1.Text = Form1.DataViewer.Item(13, i).Value
        cboType.Text = Form1.DataViewer.Item(14, i).Value
        Label28.Text = Form1.DataViewer.Item(13, i).Value
        '    TextBox23.Text = Form1.DataViewer.Item(16, i).Value
        ' TextBox4.Text = Form1.DataViewer.Item(17, i).Value
        ' TextBox2.Text = Form1.DataViewer.Item(18, i).Value
        ' TextBox3.Text = Form1.DataViewer.Item(19, i).Value
        Try

            ' Create a DataSet.
            Dim data2 As New DataSet()
            data2.Locale = System.Globalization.CultureInfo.InvariantCulture

            ' Add data from the Customers table to the DataSet.

            ' Add data from the Orders table to the DataSet.
            Dim detailsDataAdapter As _
                New SqlDataAdapter("SELECT * from tblDeliveryLines Where DeliveryID='" & Form1.txtWatchId.Text & "'", connection)
            connection.Open()
            detailsDataAdapter.Fill(data2, "tblDeliveryLines")

            ' Establish a relationship between the two tables.
            '   Dim relation As New DataRelation("PurchaseOrders", _
            '     data.Tables("tblDeliveries").Columns("DeliveryID"), _
            '      data.Tables("tblDeliveryLines").Columns("DeliveryID"))
            '  data.Relations.Add(relation)

            ' Bind the master data connector to the Customers table.
            '   masterBindingSource.DataSource = data
            '  masterBindingSource.DataMember = "tblDeliveries"

            ' Bind the details data connector to the master data connector,
            ' using the DataRelation name to filter the information in the 
            ' details table based on the current row in the master table. 
            detailsBindingSource.DataSource = data2
            detailsBindingSource.DataMember = "tblDeliveryLines"
            connection.Close()

            ' com.Connection.Open()
            '  For x As Integer = 0 To DataGridView1.Rows.Count - 1
            ' STR1 = "SELECT * from tblDeliveryLines Where DeliveryID = '" & TextBox12.Text & "'"
            'Dim Comm As New SqlDataAdapter(STR1, connection)

            ' Delivery.Fill(edata, "tblDeliverylines")

            DataGridView1.DataSource = data2
            DataGridView1.DataMember = "tblDeliveryLines"
            DataGridView1.AutoGenerateColumns = True
            DataGridView1.Columns.Item(0).Visible = False
            DataGridView1.Columns.Item(1).Visible = False
            DataGridView1.Columns.Item(2).HeaderText = "Stock Code"
            DataGridView1.Columns.Item(3).HeaderText = "Garments"
            DataGridView1.Columns.Item(4).HeaderText = "Hangers"
            DataGridView1.Columns.Item(5).HeaderText = "Boxes"
            DataGridView1.Columns.Item(6).HeaderText = "Cost"
            DataGridView1.Columns.Item(2).Width = "100"
            DataGridView1.Columns.Item(3).Width = "80"
            DataGridView1.Columns.Item(4).Width = "70"
            DataGridView1.Columns.Item(5).Width = "70"
            DataGridView1.Columns.Item(6).Width = "80"

            '   Next
            '    connection.Close()
        Catch ex As Exception

        End Try

    End Sub
End Class

Not sure what is going on and how to fix this



via Chebli Mohamed

How to get the data of the query after the insertion of parameters?

How can I get a String with the SQL query, once parameters inserted in C# with oledb ?

Here is my code:

var c = new OleDbConnection(@"blahba");

c.Open();

var q = new OleDbCommand(@"
    SELECT *
    FROM @table
    WHERE created = @creation
", c);

q.Parameters.AddRange(new[]{
    new OleDbParameter{
        ParameterName = "@creation",
        Value = "2007-05-13",
        OleDbType = OleDbType.Date,
    },
    new OleDbParameter{
        ParameterName = "@table",
        Value = "table",
        OleDbType = OleDbType.IUnknown,
    }
});

// ... ?



via Chebli Mohamed

Modify app settings used by external DLL at runtime

I'm trying to build a simple client for testing an internal authentication service. The main idea is to just have a simple tool for testing to ensure that this service is callable (and successfully authenticates) in each environment.
In any client application that calls this service, a few settings need to be defined in App.config. The primary one that is used is AuthenticationService which contains a value that is a URL to this remote auth service, which is read by a DLL that is included in the client. This URL is different for each environment (Dev, QA, Prod).

For Example:

  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=12345" >
      <section name="Authenticator.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=12345" requirePermission="false"/>
      <section name="RemoteAuthenticator.TokenCache.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=12345" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <applicationSettings>
    <RemoteAuthenticator.Properties.Settings>
      <setting name="AuthenticationService" serializeAs="String">
        <value>https://environment-url</value>
      </setting>
    </RemoteAuthenticator.TokenCache.Properties.Settings>
  </applicationSettings>

The problem I'm running into is building a client that is able to call the service in different environments for testing. The value for the URL in the setting AuthenticationService needs to be changed at runtime when the user makes requests to different environemnts, but I have been unable to find a way to do this.

The client DLL used to call this service provides the following way to add an auth token to an HttpClient:

new AuthorizationHelper().AddAuthorization(httpClient);

These methods from the DLL call the service (at the URL specified within the client App.config, and add the returned auth token to a header within the provided HttpClient.

That is the extent of how this service is called, as the target environment URL from App.config is read by the DLL when this is called. These methods in the DLL are basically a blackbox for me, as I have no way to modify how the URL is retrieved.

So far I have tried accessing this setting directly and via a ConfigurationManager, but both ways show zero settings. After messing around with that for awhile, I tried creating multiple App.config files, one for each environment, and attempted to re-load them at runtime as needed (as outlined in this post: http://ift.tt/1M9G7QX). This last solution somewhat works, but only for the first call. Any successive calls to a different environement do not use the URL from the reloaded config, just the URL from the config loaded before the first call to the service.

Is there any way I can modify this setting at runtime in order to call different environments with this tool as needed?



via Chebli Mohamed

Dotnet.Highcharts error in export image

I am using ASP.NET MVC website using Highcharts for graph, when i use export image as PNG,JPEG,... export looks like this enter image description here

With this labels cut in image, when should looks like is showing in website enter image description here

I've tryed to set .SetExporting with different properties, but no success This is my code

var chart = new Highcharts("chart")
            .InitChart(new Chart { PlotShadow = false })
            .SetTitle(new Title { Text = String.Empty })
            .SetCredits(new Credits { Enabled = false })
            .SetTooltip(new Tooltip { Formatter = "function() { return '<b>'+ this.point.name +'</b>: '+ this.y; }" })
            //.SetExporting(new Exporting() { Width = 2000, Enabled = true, Filename = "Teste" })
            .SetPlotOptions(new PlotOptions
            {
                Pie = new PlotOptionsPie
                {
                    AllowPointSelect = true,
                    Cursor = Cursors.Pointer,
                    DataLabels = new PlotOptionsPieDataLabels
                    {
                        Color = ColorTranslator.FromHtml("#000000"),
                        ConnectorColor = ColorTranslator.FromHtml("#000000"),
                        Formatter = "function() { return '<b>'+ this.point.name +'</b>: '+ this.percentage.toFixed(2) +' %'; }"
                    }
                }
            })
            .SetSeries(new Series
            {
                Type = ChartTypes.Pie,
                Name = String.Empty,
                Data = new Data((from o in data
                                 select new DotNet.Highcharts.Options.Point
                                 {
                                     Name = o.Key.Name,
                                     Y = o.count
                                 }).ToArray())
            });



via Chebli Mohamed

Custom conversions when writing CSV files using CsvHelper

I've been doing some CSV reading and writing lately, and ran across CsvHelper which is fantastic so far. I've ran into one small problem; I use a custom converter when reading the files, but when I write them back out, that format is lost. My CSV format looks like this:

67,1234-1,20150115,750,20150115,1340,549,549,406,0,FRG

The fields 20150115,750 map to a single DateTime field called Start (So, 01/15/2015 7:50 AM). My class map looks like this:

public sealed class DutyMap : CsvClassMap<Duty>
{
    static readonly CultureInfo enUS = new CultureInfo("en-US");

    public DutyMap()
    {
        Map(m => m.PersonId).Index(0);
        Map(m => m.DutyName).Index(1);
        Map(m => m.Start).ConvertUsing(row => ParseDate(row.GetField<String>(2), row.GetField<String>(3)));
        Map(m => m.End).ConvertUsing(row => ParseDate(row.GetField<String>(4), row.GetField<String>(5)));
        Map(m => m.DutyTime1).Index(6);
        Map(m => m.DutyTime2).Index(7);
        Map(m => m.FlightTime).Index(8);
        Map(m => m.CreditHours).Index(9);
        Map(m => m.DutyType).Index(10);
    }

    private static DateTime ParseDate(string date, string time)
    {
        DateTime ret;

        if (time.Length < 4)
            time = new String('0', 4 - time.Length) + time;

        if (!DateTime.TryParseExact(date + time, "yyyyMMddHHmm", enUS, DateTimeStyles.None, out ret))
            throw new FormatException(String.Format("Could not parse DateTime.  Date: {0} Time: {1}", date, time));

        return ret;
    }
}

This works great, and I can now call parse an entire file like so:

var csv = new CsvReader(sr);
csv.Configuration.HasHeaderRecord = false;
csv.Configuration.RegisterClassMap<DutyMap>();

Data = csv.GetRecords<Duty>().ToList();

However, when I write the file:

csv.WriteRecords(Data);

The file is written out like so:

67,7454-1,1/15/2015 7:50:00 AM,1/15/2015 1:40:00 PM,549,549,406,0,FPG

Looking through the documentation, I don't see a way to specify a conversation function upon writing, only reading. The only solution I've found so far is to manually write each record by hand:

var csv = new CsvWriter(sw);
foreach (var item in Data)
{
    csv.WriteField(item.PersonId);
    csv.WriteField(item.DutyName);
    csv.WriteField(item.Start.ToString("yyyyMMdd"));
    csv.WriteField(item.Start.ToString("Hmm"));
    csv.WriteField(item.End.ToString("yyyyMMdd"));
    csv.WriteField(item.End.ToString("Hmm"));
    csv.WriteField(item.DutyTime1);
    csv.WriteField(item.DutyTime2);
    csv.WriteField(item.FlightTime);
    csv.WriteField(item.CreditHours);
    csv.WriteField(item.DutyType);

    csv.NextRecord();
}

Is there a better way to do this? Thanks!



via Chebli Mohamed

The documentation for EventHandler<TEventArgs> says:

The second parameter is a type derived from EventArgs and supplies any fields or properties needed to hold the event data.

and it seems to be generally recommended throughout the .Net documentation.

However it turns out that I can do the following which works just fine:

public event EventHandler<int> Panned;

and invoke the event handler as:

int value = 10;
if (Panned != null)
{
    Panned(this, value);
}

and on the observer side:

subject.Panned += (sender, e) =>
{
    Console.WriteLine(e);
};

To me this seems better than littering the code with little classes that inherit from EventArgs or having a generic EventArgs as proposed by Does .NET have a built-in EventArgs<T>?

So why is it required that I inherit the EventHandler generic argument from EventArgs?



via Chebli Mohamed

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?



via Chebli Mohamed

When selecting a dropdown item how do I get a specific list of questions to appear .net / html

Please don't give me the outright answer, I'm a newb and I'm stuck - just need pointed in the right direction.

I have a dropdown with 4 values (in html) and I would like a list of questions to pop up for each of the values in the drop down.e.g dropdown item 1 = question list 1; dropdown item 2 = question list 2.

My search keeps pointing me to a table pulled from sql, but I don't want that, I only want a form that is submitted to sql after the specific list of questions is answered.

I'm building this in visual studio so will need .net help

Thank you so much smart people!



via Chebli Mohamed

Match sequences of n-tuples

My following C# code returns the following:

{(a,b,c),(d,e,f),(r,s,t),(u,v,y)}

{(a,b),(c,d,e)}

{(a,b),(c,d)}

But I don't want {(a,b),(c,d,e)} to be matched since the tuples inside are of different orders (2 and 3 respectively).

private void testwest()
{
    string st = "abc+{(a,b,c),(d,e,f),(r,s,t),(u,v,y)}+test-{(a,b),(c,d,e)}+rst+{(a,b),(c,d)}";
    Regex oRegex = new Regex(@"{(\(.*?\),\(.*?\))}");

    foreach (Match mt in oRegex.Matches(st))
    {
        Console.WriteLine(mt.Value);
    }
}



via Chebli Mohamed

Are the docs for the valid values of HashAlgorithm's Create() method deficient?

MSDN says "The following table shows the valid values for the hashName parameter". But

HashAlgorithm.Create("System.Security.Cryptography.SHA1CryptoServiceProvider");

succeeds even though it's not on the list.

(As does SHA1Cng that is not on the list either.)

Are the docs incomplete, or am I misunderstanding them?



via Chebli Mohamed

Why does the Create() method of SHA-1 behave differently than that of SHA-256?

Why does SHA1Cng.Create() return a SHA1CryptoServiceProvider, while SHA256Cng.Create() returns a SHA256Managed?

If you can explain why SHA256Cng.Create was implemented to create a SHA256Managed instead of a SHA256Cng, I'd be interesting in that too. Currently, to create a SHA256Cng we need to use SHA256.Create("System.Security.Cryptography.SHA256Cng").



via Chebli Mohamed

What is this thingy called in .net?

I remember a while back, I was working on a web page based on C# razor. There was a response property that served as a kind of pipeline between the controller and the page. I don't know what it was called but it had an interesting property -

basically it works like a dictionary(of string, object) so that you can dump anything in there by any name except you would use it like this:

ThingNameIDontRemember.name = whatever

After adding the stuff I wanted, I think they even showed up in intellisense autocomplete on the other side (unlike what you'd expect from a generic object)

What is that type called and is it also available outside the mvc bundle? I coul'd really use something like that in my current vb.net project.



via Chebli Mohamed

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!



via Chebli Mohamed

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.



via Chebli Mohamed

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?



via Chebli Mohamed

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?



via Chebli Mohamed

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.



via Chebli Mohamed

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 ?



via Chebli Mohamed

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"



via Chebli Mohamed

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?



via Chebli Mohamed

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.



via Chebli Mohamed

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



via Chebli Mohamed

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];


    }
}
}



via Chebli Mohamed

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.



via Chebli Mohamed

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 ?



via Chebli Mohamed

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



via Chebli Mohamed

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.



via Chebli Mohamed

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();       
    }
}



via Chebli Mohamed

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



via Chebli Mohamed

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.



via Chebli Mohamed

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.



via Chebli Mohamed

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?



via Chebli Mohamed

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?



via Chebli Mohamed

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?



via Chebli Mohamed

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!



via Chebli Mohamed

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?



via Chebli Mohamed

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?



via Chebli Mohamed