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

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