vendredi 14 août 2015

Ef6 dot notation; Join on colums with condition like ,not equals

I am trying to join two tables based on column ID on Table2 to be like column ID on Table1

me.dbSet.Join(me.context.Table2, p => p.ID, e => e.ID, 
(p, e) => new { p, e }).Where(z => z.e.ID== uid)

the sql output :

 SELECT 
    1 AS [C1]  
    FROM  [NG].[T1] AS [Extent1]
    INNER JOIN [NG].[T2] AS [Extent2] ON [Extent1].[ID] = [Extent2].[ID] 
    WHERE [Extent2].[ID] = 'f520f7b3-215d-4dfe-9787-1eb6864fb335'

The sql i am trying to write with linq :

 SELECT 
    1 AS [C1]  
    FROM  [NG].[T1] AS [Extent1]
    INNER JOIN [NG].[T2] AS [Extent2] ON [Extent1].[ID] Like [Extent2].[ID] + '%'
    WHERE [Extent2].[ID] = 'f520f7b3-215d-4dfe-9787-1eb6864fb335'



via Chebli Mohamed

Re-usable C# test code that waits for IO

I'm experimenting with using async/await on WCF exposed methods/services. Everything works fine but I'd like to simulate the service method actually waiting for IO so that the service call will be registered with an IO completion port, and the thread put back into the thread pool.

To clarify, I'm just experimenting to confirm usage of IO completion ports and to get a better understanding of the mechanics of what's actually going on.

So e.g. my test service currently looks like this:

[ServiceContract]
public interface IHelloWorldService
{
    [OperationContract]
    string SayHello(string firstName, string lastName);


    [OperationContract]
    Task<string> SayHello2(string firstName, string lastName);
}


public class HelloWorldService : IHelloWorldService
{
    public string SayHello(string firstName, string lastName)
    {
        return string.Format("Hello {0} {1}", firstName, lastName);
    }

    public async Task<string> SayHello2(string firstName, string lastName)
    {
        string str = string.Format("Hello {0} {1}", firstName, lastName);
        return await Task.Factory.StartNew(() => str);
    }
}

I'd like to do something in SayHello2() to cause that code to wait for some IO, ideally a code pattern I can copy/paste to use in generally when I want to simulate waiting for IO.

Typically Thread.Sleep() is used to simulate a long running task, but I'm pretty sure that will put the thread pool thread to sleep and not trigger usage of an IO completion port .



via Chebli Mohamed

use using to dispose or resources

I am just starting to use "using" to make sure resources are disposed regardless of what happens.

Below is an example of some code that I have written to retrieve some data. My question is are all the "using" required or would it be enough to just have the first one?

        SomeMethod()
        {
            using (SqlConnection cn = new SqlConnection("myConnection"))
            {
                cn.Open();

                using (SqlCommand cmd = cn.CreateCommand())
                {
                    cmd.CommandText = "myQuery";
                    using (SqlDataReader rdr = cmd.ExecuteReader())
                    {
                        if(rdr.HasRows)
                        {
                            while (rdr.Read())
                                // do something
                        }
                    }
                }
            }
        }



via Chebli Mohamed

Set type of a variable using a condition

How to set type of a variable using a condition?
If I do like example below, my variable x is no more existing after the end if, here is my problem.

    If RequestedType = "Integer" Then
        Dim x As Integer
    Else
        Dim x As String
    End If



via Chebli Mohamed

Windows 10 requires .NET 3.5 on demand

I'm executing my .NET application in a clean Windows 10. As far as I know, it has installed .NET Framkework 4.0 or 4.5 by default.

My application is compiled with .NET 4.0. When I execute it, windows shows up a popup saying that I need to install .NET 3.5.

enter image description here

Do you know why? Maybe I have dependencies to .NET 2.0. What you suggest to do?



via Chebli Mohamed

Microsoft Edge: Get Window URL and Title

Previously I was using ShellWindows() API for IE to get the window Title and URL for my application Now with new development, Microsoft Edge is new and has many features under development.

I want to know how I can get the URL and Title of all the pages opened in MS-Edge. As none of the shell APIs are working with MS-Edge. I tried also with UI Automation but it does not return all the UI elements

I am using MS Visual Studio 2010 for development. Do I need new version of Visual Studio? Can anybody help me about how to access the Title and URL? Or Does MS-Edge not allow such an access due to security? thanks



via Chebli Mohamed

Can "legacy" .NET projects also use the new NuGet 3 features?

The new NuGet version fixes lots of problems (e.g. transitive dependency capabilities, dependency resolution at build time, single packages repository cache, etc.).

However I could only test it with the ASP.NET vNext and UWP projects.

Will these new features also be available for "legacy" projects (e.g. full .NET 4.5/4.6 projects, WPF, etc.)?



via Chebli Mohamed

How to put dots(...) if record length is too long than the column width and how to keep all columns in same size

This is a table in my view.

<table>
@{var counter = 1; }
<tr>
    @foreach (var item in Model)
{
        <td>
            <div class="tdWidthFixed">
            <h4 class="m0" style="color:deepskyblue">@Html.DisplayFor(modelItem => item.courseName)</h4>
            @Html.DisplayFor(modelItem => item.courseSubject)<br>
            @Html.DisplayFor(modelItem => item.institute)
                </div>
        </td>
        if (counter % 3 == 0)  //Display 3 courses at a row
    {
            @:</tr><tr> 
    }
    counter++;
}
</tr>

There are three lines in a one sell. But when displaying lengthy result lines breaks to new line. what i need to know is how to put dots(...) at the end of the line, if records are too long than the column width. And also how to make all the columns are in same size.



via Chebli Mohamed

install UCMA 3.0 and create a trusted application pool

I am following the tutorial

.As explained in the tutorial, I have installed UCMA 3.0 SDK Next is, I ran Run Bootstrapper.exe /BootstrapLocalMgmt /MinCache successfully. In the third step, I am trying to run the command Run Get-CsSite to get the SiteId, but I am getting an error as:

"Cannot find information about the local domain".

I am not sure about this error. Can somebody help me out with this. I am doing this on an azure machine.



via Chebli Mohamed

IdentityServer: requesting resource scopes in ImplicitFlow

If I'm using client with implicit flow is it possible to request resource scopes along with identity scopes?

I tried creating OpenIdConnectAuthenticationOptions as below:

new OpenIdConnectAuthenticationOptions
{
  ClientId = "implicitclient",
  Authority = ...,
  RedirectUri = ...,
  ResponseType = "id_token token",
  Scope = "identity_scope resource_scope",
  ...

Still when authenticated getting back only identity_scope.

Any help and comments appreciated.



via Chebli Mohamed

Map lists of nested objects with Dapper

I'm using Dapper and I have classes like this:

public class Article{
   public int Id { get; set; }
   public string Description{get;set;}
   public Group Group { get; set; }
   public List<Barcode> Barcode {get;set;}
   ...
}

public class Group{
   public int Id { get; set; }
   public string Description {get;set;}
}

public class Barcode{
   public int Id { get; set; }
   public string Code{get;set;}
   public int IdArticle { get; set; }
   ...
}

I can get all information about Article but I would like to know if is possible with one query get also the list of barcodes for each article. Actually what I do is this:

string query = "SELECT * FROM Article a " +
"LEFT JOIN Groups g ON a.IdGroup = g.Id ";

arts = connection.Query<Article, Group, Article>(query,
    (art, gr) =>
    { art.Group = gr;  return art; }
    , null, transaction).AsList();

I also found a good explanation here but I don't understand how to use it in my case, because I have also the Group class. How should I do this with Dapper, is it possible or the only way is to do different steps? Thanks



via Chebli Mohamed

adding reference to class library

I have a class library lets call it UtilityLibrary.

I have a console application. So I right clicked on my solution and added an existing project (UtilityLibrary). I noticed that I can change the code of UtilityLibrary from within my console application.

The issue is if I had added UtilityLibrary to another application and the code had been changed it could causes issues. I was trying to avoid adding a dll reference so thought I would add a reference to my project however I am worried about the code being edited.

Have I added the reference to my project incorrectly?



via Chebli Mohamed

Simultaneous output in the console and to a file

Is there a way in .NET to write the output stream Stream two at once?

That is, do Console.SetOut() for Console.Out and for StringWriter for example. To all that is written in the console at the same time it was written in the file.



via Chebli Mohamed

Sessions are killed after short time in 64bit application pool

We have a .net web application hosted on IIS 7.5. Earlier this application was running on a 32bit application pool but some time ago we've switched to 64 bit application pool.

Recently users have started to complain that after 1-2 minutes of idling their session is being killed which we have confirmed today.

In the web.config file the session timeout is set to 60 minutes. Also we have noticed in task manager that the w3wp process for this application consumes about 2-2,4GB of memory so maybe the problem is that the application pool is trying to recycle some memory?

The recycling is set to limited time periods 21:00 and 4:00

What could be the reason for this problems with sessions?



via Chebli Mohamed

mvc input one to many

I'd like to get some help with this :

<table>
<tr>
    <td>
        <select id="specieName" name="specieName">
            foreach(var item in Model)
            {
                <option>@item.potatoSpecie</option>
            }
        </select>
    </td>
    <td><input size=25 type="text" id="potatoName" name="potatoName"/></td>
    <td><input size=25 type="text" id="potatoSize" name="potatoSize"/></td>
</tr>

public class potato
{
    public potato()
    {
        category - new HashSet<category>();
    }
    public string name name { get; set; }
    public virtual ICollection<Category> Category { get; set; }
    public int IdPotato { get; set; }
}

public class category
{
    [Key]
    public int IdPotato { get; set; }
    public int potatoSize { get; set; }
    public virtual potatoSpecie potatoSpecie { get; set; }
}

public class specie
{
    public string specieName { get; set; }
    public int specieId { get; set; }
}
public ActionResult Potato(string submit)
{
    var new hotPotato = new potato();
    {
        hotPotato.category.potatoSize = int.Parse(Request.Form["potatoSize"]);
        hotPotato.name = Request.Form["potatoName"];
        hotpotato.category.specie.specieName - Request.Form["specieName"];
    }
    using(potatoesContext context - new potatoesContext())
    {
        context.potato.add(potato)
        context.SaveChanges();
    }
    return View(potato);
}

From here, there's a few things I'd like to understand, can I retrieve both razor and regular fields with one action ? is there a better way to do it than Request.Form? The biggest problem from here is that I don't exactly know where to go after that, I'm trying to put these potatoes in my database and I'd like to at least be sure if I'm on the right direction, thanks beforehand.



via Chebli Mohamed

Cannot find named event when created in Windows Service

I am developing a Windows Service in C# to centrally manage some application connectivity. It's a sleeper service in general, which performs some actions when awoken by an external executable. To this end I'm using named events, specifically the .NET EventWaitHandle. My code boils down to, at the service end:

        EventWaitHandleSecurity sec = new EventWaitHandleSecurity();
        sec.AddAccessRule(new EventWaitHandleAccessRule(
                  new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                  EventWaitHandleRights.FullControl,
                  AccessControlType.Allow));
        evh = new EventWaitHandle(false, EventResetMode.AutoReset, EVENT_NAME, 
                                  out created, sec);

        Log(created ? "Event created" : "Event already existed?");

As it's an internal application on trusted servers I don't mind that granting 'Full Control' to 'World' in general wouldn't be smart.

At the client end I have:

EventWaitHandle.TryOpenExisting(EVENT_NAME, EventWaitHandleRights.Modify, out evh)

The code above works perfectly when I run my service in console-based interactive mode. The event is found on both ends, the client can set, and the service kicks to work. Everybody's happy.

When installing the service however it doesn't work. The logging still reports that the event was created anew, but the client cannot find the event. As I thought it was security-related I added the World Full Control Allow access rule, but it didn't change anything. I changed the service to run as Local Admin, even as my own user account, but nothing - the client cannot find the event even though logs show the service is happily polling away on it. If I change the TryOpenExisting to OpenExisting I get an explicit exception:

System.Threading.WaitHandleCannotBeOpenedException: No handle of the given name exists.

What am I missing?



via Chebli Mohamed

App that monitors changes in a folder and reacts to them C#

I'm new to C# programming and I need some help. I have to write an app that, after an authentication phase, monitors the changes of a folder and when something happens (a file is added/deleted/updated) reacts by sending a notification to a server. What is the best way to do that? A windows service launched after the authentication? Please note that this monitoring activity should be performed while in parallel the user is navigating the ui.

Thank you all!



via Chebli Mohamed

JSON.NET(NewtonSoft.dll) changed my proxy class while updating my wcf service reference

i am working on HealthCare project. i have been given task to convert JSON format to HL7 format. to make it happen, i import Newtonsoft.dll to my project.after adding the reference to my project. while updating the wcf service reference, i found my whole proxy class get changed because of the added newtonsoft reference.i come up with more then 200 syntex issues in my wpf application.most of issues related to data type conversion. issues like: -Cannot implicitly convert type 'System.Xml.XmlElement' to 'System.Xml.Linq.XElement'
-Cannot implicitly convert type 'string[]' to 'System.Collections.Generic.List'

if i am removing the newtonsoft dll and updating the wcf service once again.everything comes perfect. please do help me out.......... thanks .net software engineer



via Chebli Mohamed

Execute remotely a command and get result

i am a newbie at c# somebody could help me for a program that runs on remote pc and get the result.

ManagementScope wmiScope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", "pc"));
        wmiScope.Connect();


        var wmiProcess = new ManagementClass(wmiScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());

        ManagementBaseObject inParams = wmiProcess.GetMethodParameters("Create");
        //inParams["CommandLine"] = "notepadd.exe" + " \"" + "dir"+ "\"";
        inParams["CommandLine"] = "cmd.exe " + " \"" + " ipconfig /all " + "\"";
        inParams["CurrentDirectory"] = @"c:\windows\system32";

        ManagementBaseObject result = wmiProcess.InvokeMethod("Create", inParams,null);

        Debug.WriteLine(result["returnValue"]);
        Debug.WriteLine(result["processId"]);

        return Json(result, JsonRequestBehavior.AllowGet);

I'm getting a JSON dictionary but there are nothing that i want.



via Chebli Mohamed

Connecting to HIVE using a .Net application

I am trying to create a POC for one of my projects which would allow me to connect to HIVE using an ODBC connection string.

I have been successful in using a DSN method to connect to HIVE. But this doesnt work for me cause I would need to allow create connections during run time where the connection source can be changed from one host to another.

I am using the following connection string (using the Microsoft ODBC driver) which I took from http://ift.tt/1hGpqvN

var conn = new OdbcConnection {
    ConnectionString = @
    "DRIVER={Microsoft Hive ODBC Driver};
Host=<IP>;
Port=10000;
User Name=root;Password=<PWD>;
Database=default;
HiveServerType=2;
ApplySSPWithQueries=1;
TrustedCerts=C:\Program Files\Microsoft Hive ODBC Driver\lib\cacerts.pem;
AsyncExecPollInterval=100;
AuthMech=0;
CAIssuedCertNamesMismatch=0;"
}

using(conn) {
    conn.Open();
    DataTable dt = new DataTable();
    OdbcCommand cmd = conn.CreateCommand();
    cmd.CommandText =
        "SELECT * FROM categories;";

    int k = 0;
    DbDataReader dr = await cmd.ExecuteReaderAsync();
    dt.Load(dr);
}

When I try to open the connection, I get a network timeout.

ERROR [HY000] [Microsoft][HiveODBC] (34) Error from Hive: ETIMEDOUT.

I am not sure how to fix this up.



via Chebli Mohamed

M2Mqtt client side certification

I am using the m2mqtt .NET library, and I am currently having an issue validating the client side cert. I understand that this is not currently available with this library, how can I validate the server side. The website says that I should enter a valid cert using the Resources dir. .der/.crt/.cer are not valid resource types... how can add them as valid certs (I know that I don't need them all, I have just tries to add them).



via Chebli Mohamed

How to get the property value of a class based on property number

I tried to search for an already posted answer, but was unable to find any, although some threads provided some hints.

What I normally do to set the same property across numbered instances of controls is something like:

  DirectCast(Me.Controls.Item("Picturebox" & port), PictureBox).Tag = "some tag"

Is there a similar approach if I want to loop around numbered properties class1.property1 to class1.property99 of a class?



via Chebli Mohamed

Sabre PassengerDetailsRQ API Payload

What is the issue in my Sabre PassengerDetailsRQ

PassengerDetailsRQ

<PassengerDetailsRQ version="3.1.0" xmlns="sp/pd/v3_1" IgnoreOnError="true"> <MiscSegmentSellRQ> <MiscSegment DepartureDateTime="10-10" NumberInParty="3" Status="NN" Type="OTH"> <OriginLocation LocationCode="ISB"/> <Text>RETENTION SEGMENT</Text> <VendorPrefs> <Airline Code="PK"/> </VendorPrefs> </MiscSegment> </MiscSegmentSellRQ> <PostProcessing RedisplayReservation="true" UnmaskCreditCard="true"> <EndTransactionRQ> <EndTransaction Ind="true"/> <Source ReceivedFrom="YATANGO TESTING"/> </EndTransactionRQ> </PostProcessing> <PriceQuoteInfo> <Link NameNumber="1.1" Record="1"/> <Link NameNumber="2.1" Record="1"/> <Link NameNumber="3.1" Record="1"/> <Link NameNumber="4.1" Record="1"/> </PriceQuoteInfo> <SpecialReqDetails> <AddRemarkRQ> <RemarkInfo> <FOP_Remark Type="CASH"/> </RemarkInfo> </AddRemarkRQ> <SpecialServiceRQ> <SpecialServiceInfo> <SecureFlight SegmentNumber="A" SSR_Code="DOCS"> <PersonName DateOfBirth="1975-07-25" Gender="M" NameNumber="1.1"> <GivenName>CHAN</GivenName> <Surname>JOHN</Surname> </PersonName> <VendorPrefs> <Airline Hosted="true"/> </VendorPrefs> </SecureFlight>
<SecureFlight SegmentNumber="A" SSR_Code="DOCS"> <PersonName DateOfBirth="1987-07-21" Gender="F" NameNumber="2.1"> <GivenName>CHAN</GivenName> <Surname>WIFE</Surname> </PersonName> <VendorPrefs> <Airline Hosted="true"/> </VendorPrefs> </SecureFlight>
<SecureFlight SegmentNumber="A" SSR_Code="DOCS"> <PersonName DateOfBirth="2015-06-25" Gender="M" NameNumber="3.1"> <GivenName>CHAN</GivenName> <Surname>INFANT</Surname> </PersonName> <VendorPrefs> <Airline Hosted="true"/> </VendorPrefs> </SecureFlight>
<SecureFlight SegmentNumber="A" SSR_Code="INFT"> <PersonName DateOfBirth="2015-06-25" Gender="M" NameNumber="3.1"> <GivenName>CHAN</GivenName> <Surname>INFANT</Surname> </PersonName> <VendorPrefs> <Airline Hosted="true"/> </VendorPrefs> </SecureFlight>
<SecureFlight SegmentNumber="A" SSR_Code="DOCS"> <PersonName DateOfBirth="2010-09-08" Gender="M" NameNumber="4.1"> <GivenName>CHAN</GivenName> <Surname>CHILD</Surname> </PersonName> <VendorPrefs> <Airline Hosted="true"/> </VendorPrefs> </SecureFlight>
</SpecialServiceInfo> </SpecialServiceRQ> </SpecialReqDetails> <TravelItineraryAddInfoRQ> <AgencyInfo> <Address> <AddressLine>SABRE TRAVEL</AddressLine> <CityName>DSD</CityName> <CountryCode>US</CountryCode> <PostalCode>76092</PostalCode> <StateCountyProv StateCode="TX"/> <StreetNmbr>3150 DDDD DRIVE</StreetNmbr> </Address>
<Ticketing TicketType="7T-"/> </AgencyInfo> <CustomerInfo> <ContactNumbers> <ContactNumber LocationCode="SYD" NameNumber="1.1" Phone="817-555-1212" PhoneUseType="A"/> <ContactNumber LocationCode="SYD" NameNumber="1.1" Phone="972-555-1212" PhoneUseType="H"/> </ContactNumbers> <Email Address="SABRE@gmail.com" NameNumber="1.1"/> <PersonName NameNumber="1.1" > <GivenName>CHAN</GivenName> <Surname>JOHN</Surname> </PersonName> <PersonName NameNumber="2.1" > <GivenName>CHAN</GivenName> <Surname>WIFE</Surname> </PersonName> <PersonName NameNumber="3.1" Infant="true" NameReference="I01"> <GivenName>CHAN</GivenName> <Surname>INFANT</Surname> </PersonName> <PersonName NameNumber="4.1" NameReference="C07"> <GivenName>CHAN</GivenName> <Surname>CHILD</Surname> </PersonName> </CustomerInfo> </TravelItineraryAddInfoRQ> </PassengerDetailsRQ>

PassengerDetailsRS

<PassengerDetailsRS xmlns="sp/pd/v3_1"> <ns2:ApplicationResults xmlns:ns2="/STL_Payload/v02_01" status="Complete"> <ns2:Success timeStamp="2015-08-13T23:47:22.138-05:00"/> <ns2:Warning type="BusinessLogic" timeStamp="2015-08-13T23:47:21.549-05:00"> <ns2:SystemSpecificResults> <ns2:Message code="WARN.SWS.HOST.ERROR_IN_RESPONSE">CHECK ITINERARY</ns2:Message> </ns2:SystemSpecificResults> </ns2:Warning> <ns2:Warning type="BusinessLogic" timeStamp="2015-08-13T23:47:21.792-05:00"> <ns2:SystemSpecificResults> <ns2:Message code="WARN.SP.PROVIDER_ERROR">ÂINVALID PSGR TYPEÂ</ns2:Message> </ns2:SystemSpecificResults> </ns2:Warning> <ns2:Warning type="BusinessLogic" timeStamp="2015-08-13T23:47:21.918-05:00"> <ns2:SystemSpecificResults> <ns2:Message code="WARN.SWS.HOST.ERROR_IN_RESPONSE">INFANT DETAILS REQUIRED IN SSR - ENTER 3INFT/...</ns2:Message> </ns2:SystemSpecificResults> </ns2:Warning> </ns2:ApplicationResults> <TravelItineraryReadRS> <TravelItinerary> <CustomerInfo> <Address> <AddressLine>SABRE TRAVEL</AddressLine> <AddressLine>3150 DDDD DRIVE</AddressLine> <AddressLine>DSD, TX US</AddressLine> <AddressLine>76092</AddressLine> </Address> <ContactNumbers> <ContactNumber LocationCode="SYD" Phone="817-555-1212-A-1.1" RPH="001"/> <ContactNumber LocationCode="SYD" Phone="972-555-1212-H-1.1" RPH="002"/> </ContactNumbers> <PaymentInfo> <Payment> <Form RPH="001"> <Text>CASH</Text> </Form> </Payment> </PaymentInfo> <PersonName NameNumber="01.01" PassengerType="ADT" RPH="1" WithInfant="false"> <Email>SABRE@GMAIL.COM1.1</Email> <GivenName>CHAN</GivenName> <Surname>JOHN</Surname> </PersonName> <PersonName NameNumber="02.01" PassengerType="ADT" RPH="2" WithInfant="false"> <Email>SABRE@GMAIL.COM1.1</Email> <GivenName>CHAN</GivenName> <Surname>WIFE</Surname> </PersonName> <PersonName NameNumber="03.01" NameReference="I01" PassengerType="INF" RPH="3" WithInfant="true"> <Email>SABRE@GMAIL.COM1.1</Email> <GivenName>CHAN</GivenName> <Surname>INFANT</Surname> </PersonName> <PersonName NameNumber="04.01" NameReference="C07" PassengerType="ADT" RPH="4" WithInfant="false"> <Email>SABRE@GMAIL.COM1.1</Email> <GivenName>CHAN</GivenName> <Surname>CHILD</Surname> </PersonName> </CustomerInfo> <ItineraryInfo> <ReservationItems> <Item RPH="1"> <FlightSegment AirMilesFlown="3778" ArrivalDateTime="10-10T15:00" DayOfWeekInd="6" DepartureDateTime="2015-10-10T10:45" ElapsedTime="08.15" FlightNumber="0785" NumberInParty="03" ResBookDesigCode="V" SegmentNumber="0001" SmokingAllowed="false" SpecialMeal="false" Status="SS" StopQuantity="00" eTicket="true"> <DestinationLocation LocationCode="LHR"/> <Equipment AirEquipType="773"/> <MarketingAirline Code="PK" FlightNumber="0785"/> <OriginLocation LocationCode="ISB"/> <SupplierRef ID="DCPK"/> <UpdatedArrivalTime>10-10T15:00</UpdatedArrivalTime> <UpdatedDepartureTime>10-10T10:45</UpdatedDepartureTime> </FlightSegment> </Item> <Item RPH="2"> <MiscSegment DayOfWeekInd="6" DepartureDateTime="10-10" NumberInParty="03" SegmentNumber="0002" Status="NN" Type="OTH"> <OriginLocation LocationCode="ISB"/> <Text>RETENTION SEGMENT</Text> <Vendor Code="PK"/> </MiscSegment> </Item> </ReservationItems> <Ticketing RPH="01" TicketTimeLimit="T-"/> </ItineraryInfo> <ItineraryRef AirExtras="false" InhibitCode="U" PartitionID="AA" PrimeHostID="1S"> <Source PseudoCityCode="4VHH" ReceivedFrom="SABRE TESTING"/> </ItineraryRef> <RemarkInfo/> <SpecialServiceInfo RPH="001" Type="AFX"> <Service SSR_Code="OSI"> <PersonName NameNumber="03.01">I/INFANT/CHAN</PersonName> <Text>AA INF</Text> </Service> </SpecialServiceInfo> <OpenReservationElements/> </TravelItinerary> </TravelItineraryReadRS> </PassengerDetailsRS>



via Chebli Mohamed

(vs2015)I can link to server in debug mode,but when I use release mode,it can't work

Stream newStream = request.GetRequestStream();

When I run the code in debug mode.It works well and I can get information from server.But when I use release mode, it crashes.

The warning infomation: An unhandled exception of type 'System.Net.WebException' occurred in System.dll

Additional information: Unable to connect to the remote server



via Chebli Mohamed

string variable name Date acts weird in debugger

Can someone tell me why is the debugger handles my string variable named Date as a DateTime object?

Code:

public class HourRegistration
{
    public string Date { get; set; }
}

See screen capture:

enter image description here

Using .NET framework 4.5, VS-2015

Thanks!



via Chebli Mohamed

How to do Cron Job in Console Application and How to trigger Weekly?

I want to create a cron job to send email to particular email id's from database.

Brief overview : This is time management system. So, users can enter the working hours daily. I need to check the time sheet by weekly basis. If the team member(users) enters working hours below 40(for 5 days in a week) it should send the automatic email to the particular team leader. Similarly for greater than 60 hours(Maximum hours) also it should send email to particular team leader. I need to do this with cron job in console application.

So, How to do this and and how to get the particular team leader for team member when sending automatic email.

Help me to achieve this. Any knowledge transfer is appreciable. Thanks in Advance



via Chebli Mohamed

WPF application does not run on some PCs

My WPF application runs fine on some PCs, on others it crashes before log4net starts logging. The Error is

  Problem signature:
  Problem Event Name:   CLR20r3
  Problem Signature 01: gui.exe
  Problem Signature 02: 1.0.0.0
  Problem Signature 03: 55cd97ed
  Problem Signature 04: PresentationFramework
  Problem Signature 05: 4.0.30319.18408
  Problem Signature 06: 52312f13
  Problem Signature 07: 7fe8
  Problem Signature 08: ee
  Problem Signature 09: System.Windows.Markup.XamlParse

The PC has .NET-Framework 4.5.1 installed, my 32-bit application is .NET-Framework 4.5. I have noticed that, on another pc where it did not work, the application worked after installing Visual Studio 2013.

I'd be very thankful for a tipp on what I might be missing.



via Chebli Mohamed

Unable to access a registered COM component dll from IIS 8 server on 64 bit

I have registered a COM component dll in the windows server 2012 which is 64 bit but not able to access it through IIS server 8 hosted WCF service (Error: Class not registered whereas properly working in windows application .exe)



via Chebli Mohamed

asp.net vnext and XDocument

I'm having a problem with the latest beta-version of .net and the Xdocument library.

My project.json looks like this:

 "dependencies": {
    "Microsoft.AspNet.Mvc": "6.0.0-beta4",
    "Microsoft.AspNet.Server.IIS": "1.0.0-beta4",
    "Microsoft.AspNet.Server.WebListener": "1.0.0-beta4",
    "Microsoft.AspNet.StaticFiles": "1.0.0-beta4",
    "System.Xml.XDocument": "4.0.10-beta-23109"
  },

  "commands": {
    "web": "Microsoft.AspNet.Hosting --config hosting.ini"
  },

  "frameworks": {
    "dnx451": { }   
  },

And my code like this:

var xd = XDocument.Parse(str);

But I receive the error-message:

Severity    Code    Description Project File    Line
Error   CS0433  The type 'XDocument' exists in both 'System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' and 'System.Xml.XDocument, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' WebApplication2.DNX 4.5.1   ValuesController.cs 23

Simply trying to solve it with using System.Xml.Linq.XDocument xd = or System.Xml.XDocument xd = does not seem to be working, what else could I try?



via Chebli Mohamed

parameterized insertion of data half selected from other column gives invalid pseudocolum

I have the following query

     "INSERT INTO t1 select $v1,c2 FROM t2 WHERE c3= $v2";

which is executed as

    SqlCommand cmd= new SqlCommand(query, conn);
    cmd.Parameters.AddWithValue("$v2", data);
    foreach (string value in list)
    {
        cmd.Parameters.AddWithValue("$v1", value);
        cmd.ExecuteNonQuery();
    }

however this results in an error:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Invalid pseudocolumn "$v1".

This is based on the following question: SQL Insert into ... values ( SELECT ... FROM ... ) I suspect that it's not understanding where the were clause goes or that $v1 is not the name of a column but an actual value, but does anybody know how to fix this (t1 only has 2 columns both ints c2 is an int and c3 is also an int).



via Chebli Mohamed

C# Associativity math: (a + b) + c != a + (b + c)

Recently I was going through an old blog post by Eric Lippert in which, while writing about associativity he mentions that in C#, (a + b) + c is not equivalent to a + (b + c) for certain values of a, b, c. I am not able to figure out for what arithmetic values might that hold true and why.



via Chebli Mohamed

Orient db .NET Client- Crearing Database pool issue

OClient.CreateDatabasePool("127.0.0.1", 2480, "GreatfulDeadConcerts", ODatabaseType.Graph, "root", "hello", 10, "myTestDatabaseAlias");

Gives an exception:

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

Index was outside the bounds of the array.



via Chebli Mohamed

C# WinForms - Custom UserControl - Design-Time support for control repainting

I have created my custom UserControl with some custom properties for it. For example:

[Description("Example Description"), Category("CustomSettings"), DefaultValue("Transmedicom")]
public string DatabaseAddress
{
    get; set;
}

Everythink works fine. I can change custom property in code and in design-time.

What I'm looking for (and cannot find anything) now is: How could I reapint (reacreate) my UserControl in design-time when my custom property change in design-time. Let's say when DatabaseName will be changed to localhost UserControl will add and display some Label on my UserControl. It's important to work in Design-Time.



via Chebli Mohamed

C# Dictionary inside IDeserializationCallback OnDeserialization not working

I deserialize a Dictionary like this:

public class StaticClass
{
  public static StaticClass instance;
  public Dictionary<string, ObjectSettings> objectSettingsDict;

  void ReadSettings()
  {
  IFormatter formatter = new BinaryFormatter();
  FileStream stream = new FileStream( fileName, FileMode.Open );
  objectSettingsDict = formatter.Deserialize( stream ) as Dictionary<string, ObjectSettings>;
  stream.Close();
  }
}

inside the ObjectSettings class i have:

public class ObjectSettings : ISerializable, IDeserializationCallback
{
   string otherObjectName;
   ObjectSettings otherObject;

   public ObjectSettings(SerializationInfo info, StreamingContext context)
   {
      otherObjectName = (string)info.GetValue( "otherObjectName", typeof( string ) );
   }

   public void GetObjectData(SerializationInfo info, StreamingContext context)
   {
      info.AddValue( "otherObjectName", otherObjectName, typeof( string ) );
   }

   void IDeserializationCallback.OnDeserialization(object sender)
   {
      // my problem: objectSettingsDict is null here:
      otherObject = StaticClass.instance.objectSettingsDict[otherObjectName];
   }
}

my real code is much more complicated...

in this simplified version i can clearly see that objectSettingsDict is null in the OnDeserialization.

i know that in this simplified version the problem could be solved by serializing otherObject instead of otherObjectName and let the .NET resolve the references.

my question is:

what would be the correct way to use a dictionary in the IDeserializationCallback.OnDeserialization function of the object that is serialized in this dictionary?



via Chebli Mohamed

What are the actual (correct) versions of the .Net Framework?

What are the correct version numbers for the .NET Framework? What came out when?

This question is primarily to aid those who are searching for an answer using an incorrect version number, e.g. ".NET 4.5.5". The hope is that anyone failing to find an answer with the wrong version number will find this question and then search again with the right version number.



via Chebli Mohamed

C# MVC Control Newtonsoft.json serialization

Let's imagine, that I have a class

public class Foo
{
  public int Prop1 { get; set; }
  public int Prop2 { get; set; }
  public int Prop3 { get; set; }
}

And imagine, that in some controller FooController I'm creating a List<> of such classes Foo, populating it with data, serializing it with Newtonsoft.Json and sending to client.

It's okay, there is no problems.

But, also I have per-user permissions system, which says that User1 can't see data of Prop1 and User2 can't see data of Prop3. And I have a lot of such classes Foo and a lot of permissions for different users of my system. And, to disallow users to see data from not allowed columns I decided to interrupt json serialization and exclude not allowed for user colums from JSON serialization.

For the moment it is already written custom JsonConverter, which allow me to do so. But, it is complicated (input class scan, dynamic accessor compilation, recursion and etc) and comparably to native newtonsoft's, slow.

Concerning above facts I want to ask if there is a easier way to achive the desired result? I mean, without creating custom JsonConverter remove any column from any serialized with json class.

Thanks for the answers!



via Chebli Mohamed

jeudi 13 août 2015

how to implement MVCin c# tutorial in empty project

I have done simple projects by on MVC architecture by using the template in .net framework , Now I am trying to implement same architecture by creating an empty project. I searched to get tutorials or helping code but all in vain. Please guide me how can I Implement Model view control architecture in .NET framework C# by creating the empty project



via Chebli Mohamed

IEnumerable.Except in listview in C# [duplicate]

This question is an exact duplicate of:

I got 3 listViews 2 textbox and 2 buttons in WinForm.

Program Description: The program adds numbers to the listview by typing in numbers in the textbox and clicking the add button

Goal: I want to be able to use the IEnumerable.Except method to output only the unique numbers in listView3, for example in the picture below the unique numbers are 3 and 7 in listView1 and listView2.

 ListViewItem lvi = new ListViewItem(textBox1.Text);
 listView1.Items.Add(lvi);

 ListViewItem lv = new ListViewItem(textBox2.Text);
 listView2.Items.Add(lv);

 //im doing somthing wrong here...
 var nonintersect = listView1.Except(listView2).Union(listView2.Except(listView1));

//populate listview3 with the unique numbers...
// foreach (item )
// {

// }

Error Message:

System.Windows.Forms.ListView' does not contain a definition for 'Except' and no extension method 'Except' accepting a first argument of type 'System.Windows.Forms.ListView' could be found (are you missing a using directive or an assembly reference?)

enter image description here



via Chebli Mohamed

Changing the dataset on a server executed SSRS Report

I'm trying to narrow down the results returned from a server generated SSRS report, but the customer is requesting too many fields to do be able to do it easily with parameters into a predefined SQL statement.

Is it possible to pass a statement into the reporting server from .NET that the server will execute as its datasource, instead of the preconfigured one? Either the complete statement or the WHERE clause would be fine.

If not, is it possible to eval a parameter sent into a stored procedure? I'm aware of the security implications.



via Chebli Mohamed

c# create object for .show() and .hide()

Is there a way to create a method that goes like this in c#:

public void showHide(string shOne, string shTwo, string shThree) {
     button1.shOne();
     button2.shTwo();
     button3.shThree();
}

private void discountButton_Click(object sender, EventArgs e) {
    showHide("Show", "Hide", "Hide")
    // I was thinking that this should be the same as
    // button1.Show();
    // button2.Hide();
    // button3.Hide();
}

Is this possible ? I'm designing a c# application for thesis and I need to show and hide buttons (lots of buttons and labels and stuff).

I'm using this code as of now but I keep getting error "'Panel' does not contain a definition for 'shOne'".



via Chebli Mohamed

No file chosen even when file is chosen - mvc

I'm updating record so I'm viewing an Edit page that I created, when I change the values and choose another file to be uploaded rather than previous and press update button, the error I see is "no file chosen" below the choose file control. Why is it so when I'm choosing the file.

I'm using the following code for the file upload:

   <div class="form-group">
        @Html.LabelFor(model => model.File, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.File, new { type = "file", accept = "image/*" })
            @Html.ValidationMessageFor(model => model.File)
        </div>
    </div>

While creating this record same code is used and it works fine, then what could be the problem when trying to update a record?



via Chebli Mohamed

How do I use lazy with an initializer?

I have an array where I initialize its value at declaration time, like this:

Foo[] f = Foo[] { new Foo { y = 1 }, new Foo { y = 3 } };

How do I use lazy in this?

imaginary code

Lazy<Foo[]> f = new Lazy<Foo[]> { new Foo { y = 1 }, new Foo { y = 3 } };



via Chebli Mohamed

Impersonate remote user account with WUApiLib

I'm trying to search for updates on a remote machine and all my attempts to do so with impersonation have failed stating that the username/password was not correct.

Here is a sample of my code. I've tried every LogonType available from SimpleImpersonation. 'System.UnauthorizedAccessException' is what is thrown whenever I try to call CreateInstance and my impersonated user never matches what it should.

I will state that I CAN impersonate local PC accounts and domain accounts but I cannot impersonate accounts that exist solely on other machines which is something I need.

Any help is appreciated!

    Console.WriteLine(@"Original User: " + WindowsIdentity.GetCurrent().Name);
    try
    {
        using (Impersonation.LogonUser("IP_ADDRESS", "USERNAME", "PASSWORD", LogonType.Interactive))
        {
            Console.WriteLine(@"Impersonating User: " + WindowsIdentity.GetCurrent().Name);
            var type = Type.GetTypeFromProgID(@"Microsoft.Update.Session", target);
            var session = (UpdateSession)Activator.CreateInstance(type);
        }                
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }
    Console.WriteLine(@"Current User: " + WindowsIdentity.GetCurrent().Name);



via Chebli Mohamed

Access Class Libary from Universal Shared App

i have an Universal Shared Application which contains some Javascript/Html Code. See project structure here:

http://ift.tt/1J1lwr3

Now I want to access some native functionality which should be shared among the both projects. I tried to create a "Class Libary (Universal Windows)" and "Class Library Portal for Universal Windows 8.1" but i can't neither of them reference to the Shared App.

"One or more selected items is not a valid reference for this type of project"

What am I missing? What are the restrictions for my intend?



via Chebli Mohamed

How to configure .net native in Visual Studio 2015?

I read this guide for .net native, but I can't found 'Enable for .net native' in popup menu. Should I install some extra plugin for VS2015 for compile with .net native?



via Chebli Mohamed

DllNotFoundException with CLEyeMulticam.dll after .NET target version change

I am using the CLEye framework to interface with a PS3 Eye Camera and have had it working just fine for a while now. I recently tried changing my Target Framework in the properties menu from 4.5 to 4.0 and found that doing so causes the error System.DllNotFoundException: Unable to load DLL 'CLEyeMulticam.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E) to happen whenever I attempt to call a function from that DLL. Now any framework that I select (4.0, 4.5, 4.5.1) all show the same error.

I have previous gotten this error before I installed the CLEye SDK but haven't seen in since then.

Based on other SO questions this is usually caused by the DLL having unresolved dependencies. It is hard to imagine that this is the case here as I don't think I could have changed this dependency since it had been working. Is there something related to changing my target framework that could have broken a dependency? Should changing back to my original target framework fix the issue?



via Chebli Mohamed

PCL Reflection get properties with BindingFlags

I have the code below.

    public static IEnumerable<PropertyInfo> GetAllPublicInstanceDeclaredOnlyProperties(this Type type)
    {
        var result =
            from PropertyInfo pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
            select pi;

        return result;
    }

I am trying to convert this to a PCL library but I can not figure it out. I have tried

type.GetTypeInfo().DeclaredProperties.Where(x => x.BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)

But BindingFlags doesn't exist.

What am I missing?



via Chebli Mohamed

Connecting to FTP server with a "ftps" prefix

I've exhausted all my resources at this point, so I come asking for help.

I have a client that has given me a username and password to their ftp site. However, to access it on the web uses http://ift.tt/1hAG9ER

To access on FileZilla, I can either use ftps:// or sftp://

My problem is that I have no idea what I need to do to access it inside my program.

Right now I have this code:

var ftpFilePath = @"http://ift.tt/1L9TxJP";
var request = (FtpWebRequest)WebRequest.Create(ftpFilePath);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredentials(username, pass);
// enable SSL?

var response = (FtpWebResponse)request.GetResponse();
// Other code

It's currently failing on GetResponse with the error that it cannot connect to the remote server. If I use "ftps://ftps.sitename.com" then I get an error complaining about the prefix.

This is my first time dealing with this type of problem, and I must have missed something small. Any help is greatly appreciated.

EDIT:

I ended up using the WinSCP package and followed this tutorial: http://ift.tt/1L9TxJR

Two problem I ran into is that I don't have a ssh key, so I am temporarily setting

GiveUpSecurityAndAcceptAnySshHostKey = true

And then I ran into a small issue of making sure the process that runs VS had access to the path I was attempting to write the file to.



via Chebli Mohamed

WP8.1 - Loading Https Uri's to UI Components ignoring the SSL certificate

I have a requirement where I need to ignore SSL cerificate(Https) and get the Videos and Photos data from our Network attached Device which has got Invalid SSL Certificate.

I used HttpClient to Ignore SSL certificate and got the data, but when I load the Thumbnail Url's and Video Url's to BitmapImage and VideoPlayer respectively, the BitmapImage is not loaded to Image and Video Player fails to play the video.

Please let me know is there any way to achieve this, If yes please help me to understand.

PS: The project is Windows Universal 8.1



via Chebli Mohamed

Error compiling Csproj in teamcity

My company has tasked me with implementing continuous integration in our software department. I have decided to go with Team-city for this and everything was going smooth until I tried to build one of our major projects. I am completely new to the setup of continuous integration so I don't discredit the fact that I've probably set it up wrong somewhere. Here is the issue:

I've setup the build configuration to build my project through visual studio 2013 hitting the .sln. The project has no outside dependencies and compiles in release mode and debug mode just find on my desktop. I keep ending up with the build failing with error CS0246. Mainly, it can't compile two proj files within the solution.

why aren't those proj files compiling when they can do so just fine on my P.C.? Any help on the matter would be awesome.



via Chebli Mohamed