Affichage des articles dont le libellé est Active questions tagged .net - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged .net - Stack Overflow. Afficher tous les articles

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