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

vendredi 31 juillet 2015

How to log mysql queries of specific database - Linux

I have been looking at this post How can I log "show processlist" when there are more than n queries?

it is working fine by running this command

mysql -uroot -e "show full processlist" | tee plist-$date.log | wc -l

the problem it is overriding the file

i also want to run it in cronjob. i have added this command to the /var/spool/cron/root

* * * * * [ $(mysql -uroot -e "show full processlist" | tee plist-`date +%F-%H-%M`.log | wc -l) -lt 51 ] && rm plist-`date +%F-%H-%M`.log

but it is not working. or maybe it is saving the log file some place out of the root folder.

so my question is: How to temporary log all queries from specific database and specific table and save the whole queries in 1 file?

note. it is not slow/long quries log iam looking for, but just temp solution to read which queries are running for a database

Delete with a SUbquery MySQL

I'm trying to delele with a subquery that is the same table 'carretilla' This works in SQL Server

DELETE FROM carretilla WHERE carcod IN (SELECT carcod  FROM carretilla WHERE TIMESTAMPDIFF(MINUTE,carfch, NOW()) > 10 group BY carcod);

How can i do it? Thanks

Why BLToolkit inserts \0 instead of '@' symbol in generated queries?

I use BLToolkit with mysql and when I try to insert a record to a table, I am getting a query like this:

INSERT INTO `P`
(
    `Name`
)
VALUES
(
    \0Name
); 

As you can see, this not the best mysql query.

Classes:

public class P
{
    [PrimaryKey]
    [Identity]
    public int? ID  { get; set; }
    public string Name  { get; set; }
}

The code for inserting:

var p = new P();
p.Name = "asdf";
p.ID = (int) db.InsertWithIdentity(p);

Do you know, what is going on?

I'm the "data manager" for a small data-heavy business. What's a more official name for my role, and how can I find specific educational resources?

I'm in charge of the data for a small business. We have a large and growing body of data (customers, orders, suppliers, products, business rules, pricing structures, etc.), and my primary responsibility is to impose and maintain order over the chaos. Although I wear many hats as the resident nerd, my core job duty is to manage our ever-evolving data. To accomplish this, I spend most of day in MySQL, Excel, and Access.

Speaking both broadly and specifically, what is what I'm doing called? Is this rudimentary data quality assurance? Or data quality control? Or data integrity? Or information governance? Database management? Database administration?

I want to institute standards that are as robust as possible in the small business environment, and I'd like to pursue professional educational resources. But the vast majority of generic data/information resources I find are geared towards "big data", which is not my domain, and I'm struggling to find resources that specifically apply to my role when I'm not even sure what it's called.

Locked out of MySQL Database

I am working on a MySQL database that I eventually plan to add an API to. Today, I had a random problem with my regular (non-root) account. When I tried to login through PHPMyAdmin, it said Cannot log in to the MySQL server. So I tried to log in from the command line using mysql -umkaryadi -p and entered my password. I got back Access denied for user 'mkaryadi'@'localhost' (using password: YES). No big deal, I thought, so I logged into PHPMyAdmin and deleted and recreated my mkaryadi account.

Later, I was trying to login to with PHPMyAdmin with my root account and got the same Cannot log in to the MySQL server error. I tried to run mysqld_safe --skip-grant-tables and that let me log in. Then, I attempted to run UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root'; but I got an error to the effect that it couldn't find the Password column in the user table. I had read that you needed to run FLUSH PRIVILEGES; so I tried that before trying to change the password and got: You are logged in as an anonymous user, and anonymous users can't change passwords.

At this point, I tried to back up the databases with mysqldump but now that yields mysqldump: Got error: 2002: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) when trying to connect. Now, mysqld_safe --skip-grant-tables doesn't even let me login. I'm not entirely sure what to do here, I've reinstalled MySQL already.

Any help would be appreciated.

Computer: MacBook (13-inch, Aluminum, Late 2008) running OS X 10.10.2

MySQL version: 5.5.45

EDIT: I talked with @SteJ here and still have problems. I am still getting the The server quit without updating PID file error, but have done a fresh install of MySQL.

SELECT from table join

I have 3 tables:

users
  user_id
  first_name
forum_post
 post_id
 post_title
user_post_join
  id
  user_id
  post_id

The join table takes the user_id from users and post_id from forum_posts.

What I am trying to display is a list of posts from the forum_post table and the user who posted it. I am struggling to know where the join should be, here is my attempt so far...

function build_forum_posts(){

        global $dbc;

        $q = "SELECT users.user_id, forum_post.post_id, user_post_join.id 
            FROM users 
            INNER JOIN user_post_join ON users.user_id = forum_posts.post_id
             ";  

        $r = mysqli_query ($dbc, $q); // Run the query.

        // FETCH AND PRINT ALL THE RECORDS
        while ($row = mysqli_fetch_array($r)) {

        echo '
        <div class="post">
            <div class="col-group-2">
                <h3>'.$row["post_id"]. '</h3>
                <p>By: '.$row["user_id"]. '</p>
            </div>
            <div class="col-group-2">
                <div class="post_count">
                    <h3  class="answer">0</h3>
                    <p class="answer">Answers</p>
                </div>
            </div>  
        </div>
        ';

        } 

New To MySql Nested Query

I have 2 tables that I'm trying to pull data from:

  • USER
  • USER_NAME

USER has the following indexes:

  • ID
  • ORG_ID
  • DEFAULT_EMAIL_ID
  • STATUS
  • NAME
  • CREATED
  • UPDATED

USER_NAME has the following indexes:

  • ID
  • USER_ID
  • STATUS
  • TIMEZONE_ID
  • DST
  • LANG
  • USERNAME
  • PASSWD
  • BACKEND
  • REGISTERED

My goal is to get USERNAME from USER_NAME and NAME from USER. My background is more in DB2. I'm just learning MySQL. I tried the following with no luck.

select NAME from OST_USER where ID in (select ID, USERNAME from OST_USER_ACCOUNT where CREATED < '2015-07-09');

Any idea what I can do to get the info? Is it even possible with the given indexes? Any help is really appreciated!

Laravel use eloquent to fetch the first value on a column name

Hi I'm using Laravel and to build a task board. I have several models Project, Task, Status,AssignedStatus,TaskProgress. A basic table structure is below:

Project (table name: projects)

id|name|created_at|updated_at

Task (table name: tasks)

id|name|effort|created_at|updated_at

TaskProgress (table name: task_progresses)

id|project_id|task_id|assigned_status_id|created_at|updated_at

Status (order is assigned in this table as a user can choose a set of global or assign there own to a project)

id|name|order|created_at|updated_at

AssignedStatus (table name: assigned_stauses)

id|project_id|status_id|order|created_at|updated_at

Now to build the task board I need to know what the assigned statuses are for the project in question and then grab all of the task_progresses but I only want to grab the latest task_id on the task board so I can see where it is in the cycle. As it could have moved from open to in progress to review to open again as there may be something wrong with the task. i.e. I want to fetch the first task_id but I still want to be able to retrieve all of the tasks within a given status.

To do this I am doing the following:

AssignedStatus::where('project_id','1')->with(['status','taskprogress'])->orderBy('order','asc')->get();

This is my AssignedStatus model:

public function status() {
    return $this->belongsTo('Status', 'status_id');
}

public function taskprogress() {
    return $this->hasMany('TaskProgress', 'assigned_status_id');
}

However when I use the taskprogress function I get multiple task_id's which i don't want, I want to know what status it is in at the current moment in time

I'm not sure how I should structure why query to do this, does anyone have any solutions to the problem that they could perhaps share with me? Sorry bit of a newbie here. Can this be done with Eloquent? or do I need to loop through the nested objects and unset taskprogress by the created_at date? Hope somebody can help.

A var_dump is available here in my dropbox

Example data is below, i have timestamps in all tables, created_at and updated_at but not displayed below:

task_progresses table

id | user_id | project_id | task_id | assigned_status_id
1  | 2       | 3          |  1      |    4
2  | 3       | 3          |  2      |    3
3  | 3       | 3          |  2      |    2
4  | 2       | 3          |  2      |    1
5  | 1       | 3          |  2      |    4
6  | 2       | 3          |  2      |    3
8  | 2       | 3          |  1      |    2
8  | 2       | 3          |  1      |    1

assigned_statuses

id | project_id | status_id 
1  | 2          | 1
2  | 2          | 3
3  | 2          | 4
4  | 2          | 2

statuses

id | name        |order |global
1  | Backlog     |0     | 1    
2  | Closed      |4     | 1
3  | In Progress |2     | 1
4  | Complete    |5     | 1
5  | Done        |3     | 0
6  | Open        |1     | 0

XAMPP - how to expand a category list imported from MySQL

I have imported a set of different values from two different tables in phpMyAdmin, one from Category table (where cat_id is a PK) and another from Item table; where (cat_id is a FK).

<?php
require ('config.php');

$que = "SELECT * FROM category";
$run = mysql_query($que);
$j = 0;
while($row = mysql_fetch_array($run))
{
    $cat_idd[$j] = $row['cat_id'];
    $cat_namee[$j] = $row['cat_name'];
    $j++;
}
for($i = 0;  $i < count($cat_idd);  $i++)
{
    $que2 = "SELECT * FROM item WHERE cat_id = '$cat_idd[$i]' ";
    $result = mysql_query($que2);
    $run = mysql_num_rows($result);
    echo "<a href=''>".$cat_namee[$i]."(".$run.")</a><br>";
}
?>

Here is what I have so far:

Screenshot

Now how do I expand it? or for example, how do I show the two items that are stored in the category named Clothing on the same page or next? Since this code only helps me to view the number of items stored inside the database,

Here is my form:

    <form name = "view" method = "POST" action ="cart.php">
      <table align = 'center' width = '100%' border = '4'>
      <tr bgcolor = 'yellow'>
      <td colspan = '20' align = 'center'><h2> Viewing all the Products </td>
</tr>
      <tr align = 'center'>
      <th>Item ID</th>
      <th>Name</th>
      <th>Price</th>
      <th>Select</th>
      </tr>

      <tr  class = "odd">


      <?php
        require ('config.php');

        $que = "SELECT * FROM category";
        $run = mysql_query($que);
        $j = 0;
      while($row = mysql_fetch_array($run))
       {
         $cat_idd[$j] = $row['cat_id'];
         $cat_namee[$j] = $row['cat_name'];
         $j++;
       }

I thought of using an array function to store the value inside a category i.e Clothing(2) => 2.

       function array_insert(&$array, $position, $insert)
       {
         if (is_int($position)) {
          array_splice($array, $position, 0, $insert);
       } else {
          $pos   = array_search($position, array_keys($array));
          $array = array_merge(
             array_slice($array, 0, $pos),
             $insert,
            array_slice($array, $pos)
        );
       }
       }

      $arr = array();
      $arr[] = 2;


      for($i = 0;  $i < count($cat_idd);  $i++)
      {
       $que2 =  "SELECT * FROM item WHERE cat_id = '$cat_idd[$i]'";
       $result = mysql_query($que2);
       $run = mysql_num_rows($result);
       echo "<a href=''>".$cat_namee[$i]."(".$run.")</a><br>";
     array_insert($arr, 0, "$run");
     // echo $arr[0];
      }
        $que2 = "SELECT * FROM item WHERE cat_id = '1'";      //instead of using '1' i wish to use the one user clicks on!
        $res2 = mysql_query($que2);
       while($row = mysql_fetch_array($res2))
        {
          $i_id = $row['item_id'];
          $i_namee = $row['item_name'];
          $i_price = $row['item_price'];


       ?>
       <td><?php echo $i_id; ?></td>
       <td><?php echo $i_namee; ?></td>
       <td><?php echo $i_price; ?></td>
       <td><input type="checkbox" name="addcart" value="<?php echo $item; ?>" onClick="return KeepCount()" />Tick</td>
</tr>
       <?php }  ?>    
       <br><br>
       </table>
       <input type = "hidden" name = "check">
       <button type=  "submit" onclick = "location.href = 'cart.php';" id = "cart" style="float:right; margin-top: 30px; margin-right: 10px;">Add to Cart</button>

The above image is the result what I want, this one is specific for Clothing(2) only. I want it to change as the user clicks on something else for example, Shoes(1).

Django unique_together but only for filtering

Is there a way to filter a django model, where two fields are unique together?

For example, I have this model:

class Sequence(models.Model):
    id       = models.CharField(max_length=25, primary_key=True)
    taxonomy = models.CharField(max_length=25)
    sequence = models.TextField()

There can be multiple Sequence objects that have the same the sequence and taxonomy. I want to have a unique subset of Sequence objects where no taxonomy has multiple sequences that are identical, and only pick one object if there are multiple.

So far I have tried iterating over the results:

def unique(query_set):
    used_taxa = {}
    for seq in query_set.all():
        if not seq.sequence in used_taxa:
            used_taxa[seq.sequence] = [seq.taxonomy]
            yield seq
        elif seq.sequence in used_taxa and not seq.taxonomy in used_taxa[seq.sequence]:
            used_taxa[seq.sequence].append(seq.taxonomy)
            yield seq
        else:
            pass

This gets me the correct result, but I need the overall count becuase I am doing pagination later on.

This also gets me closer, but I don't have access to the full Sequence object after values has been called:

result = Sequence.objects.values("sequence", "taxonomy").annotate(id=Max("id"))

If someone can point me in the right direction, I would really appreciate it! Thanks.

PDO how to check if input empty to not use WHERE

Hello I would like how I can transform the following code to use BindValues and to do the same job.

$sql = "SELECT * FROM documents WHERE 1";
            if (!empty($topic))   { $sql .= " AND topic = '$topic' ";   }
            if (!empty($date ))   { $sql .= " AND date LIKE '%$date%' "; }

WHERE clause to be applied only on the filled input So my question is how to transform this code in to the the following query

$sql = new page($pages "SELECT * FROM table WHERE topic LIKE :topic OR date LIKE :date ", $option);

$sql ->BindValue(':topic ', $_POST['topic '], PDO::PARAM_STR);
$sql ->BindValue(':date ', $_POST['date  '], PDO::PARAM_STR);

selecting and ordering from 3 different tables in mysql

I have a code which selects 10 of the users who have "earned" money ordering by the price desc. I have been using this query

SELECT products.seller, 
SUM(products.price * (1 - reseller.fee / 100)), 
COUNT(*) 
FROM products
INNER JOIN reseller ON reseller.username = products.seller
WHERE (products.seller!= 'MYSITE') 
AND products.sold=1 
AND products.sellerpaid=0 
AND products.username != 'None' 
GROUP BY products.seller
ORDER BY SUM(products.price * (1 - reseller.fee / 100)) DESC 
LIMIT 10

By this i get:

uploaded_by  SUM()  COUNT()
 username    10.00     2
 username1   11.00     3

....

Which works absolutely fine, but now i have another table, products1 and that contains something more thats why i cannot merge them, so I want to get the same results as in the first one but fetching the price of all products from this table as well I have tried LEFT JOIN, RIGHT JOIN, and many others but still cant do it correctly.

Please do not tell me to read more about joins cuz i already have, just cant do it, if you can come up with a solutions then post it if possible.

Also if there is anything that you do not understand, please comment so I can give further explanations.

Thank you.

Is possible to create a mysql database at execution time in node.js

For example, if I have a form with an input field where I type the database name and I click submit button to create a mysql database with the name from the field, is possible?

Upload thumbnail and original image to mySQL AFNetworking

I am using AFNetworking to upload images to a mySQL database via PHP from an iPhone app. Here is the code I am using:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json",nil];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
CGFloat compression = 1.0f;
UIImage *image = _uploadImage.image;
NSData *imageData = UIImageJPEGRepresentation(image, compression);
int random = arc4random() % 9999999;
NSString *photoName=[NSString stringWithFormat:@"%d-image.jpg",random];
[manager POST:@"http://ift.tt/1fQm1gD" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:@"image" fileName:photoName mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {            
        NSLog(@"Success: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

My question is - is it possible to use AFNetworking to save a thumbnail version as well as saving the original photo? If so, how would I go about this? Or would I have to use another library to achieve this? Will appreciate any help.

Using IFNULL in sqlalchemy core

I'm trying to use sqlalchemy core select rows from a mysql table using IFNULL.

Given a table like so:

id    int1    string1   other
1      7        NULL    other stuff
2      NULL     bar     more stuff 

The sql would be something like:

SELECT IFNULL(int1, 0) AS int1, IFNULL(string1, '') AS string1 FROM table

Is this possible using the core? What would be great would be something like

s = select(ifnull(table.c.int1, 0), ifnull(table.c.string1, ''))

After importing MySQL db I can no longer log in to phpMyAdmin

Not paying attention, I exported a database from a MySQL 5.5 server, and imported it into a MySQL 5.1 server. Both via phpMyAdmin.

No errors were reported in any logs. I was also immediately able to browse the database as well.

No other changes have been made to the servers or the software. However, following that event, I am unable to log into MySQL via phpMyAdmin using any available login.

I am able to log in via console, and have dropped the added database with no effect. I have also updated the max_allowed_packet size to 16M per other recommended steps also to no avail.

When I try logging in, I get the following message: "#2006 Cannot log in to the MySQL server".

I have not been able to locate any additional information regarding fixes for this. Any recommendations?

Options currently under consideration:

  1. Upgrade phpMyAdmin
  2. Upgrade MySQL (needed as well as required for item 1)

How to check if query returned true or false in replacement for mysql_error() in PDO

I am creating a web based application, and I am using PDO for my database. I have a query that selects everything from login table where username=something and password=something.

My code:

$query = $db->prepare("SELECT * FROM login WHERE username=:username AND password=:password");
$query->bindParam(':username',$username);
$query->bindParam(':password',$password); 
$query->execute();

However I want to check if the query returned true or false. For example in mysql we used to say:

$query = mysql_query("SELECT * FROM login WHERE username='$username' AND password='$password'  "); 
if($query == false){
    die(mysql_error()); 
}

My question is, how do I check if the query returned false or true using PDO and gives an error? This will help me get errors on my code during development.

What am i going to replace with mysql_error()?

How should hierarchical data be structured in mySQL

We are designing a database to keep track of a network including Servers, Switches, and cameras. We have noticed that there is a great deal of inheritance in the table definitions. For example, all switches have an IP address, but some have 48 ports while others only 24, some have SFP ports, some two power supplies, others just one.

I know that whether in normal or OO programming, you prefer to put everything in modules/objects. So it is better to have a class for a DOOR and a HANDLE object, instead of having a DOOR class with variables defining its handle. Is this the same with relational databases.

Here are two ways of describing transcievers. I can either create one table with boolean variables like so

CREATE TABLE IF NOT EXISTS Transceiver
(
   ID INT NOT NULL AUTO_INCREMENT,
   singleMode BOOL,
   multiMode BOOL,
   1Gig BOOL,
   10Gig BOOL,
   1km BOOL,
   10km BOOL,

   PRIMARY KEY (ID)
)ENGINE=InnoDB;

Or I can create multiple tables like so

CREATE TABLE IF NOT EXISTS MM1G1KmTransceiver
(
   ID INT NOT NULL AUTO_INCREMENT,

   PRIMARY KEY (ID)
)ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS MM10G1KmTransceiver
(
   ID INT NOT NULL AUTO_INCREMENT,

   PRIMARY KEY (ID)
)ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS MM1G10KmTransceiver
(
   ID INT NOT NULL AUTO_INCREMENT,

   PRIMARY KEY (ID)
)ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS MM10G10KmTransceiver
(
   ID INT NOT NULL AUTO_INCREMENT,

   PRIMARY KEY (ID)
)ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS SM1G1KmTransceiver
(
   ID INT NOT NULL AUTO_INCREMENT,

   PRIMARY KEY (ID)
)ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS SM10G1KmTransceiver
(
   ID INT NOT NULL AUTO_INCREMENT,

   PRIMARY KEY (ID)
)ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS SM1G10KmTransceiver
(
   ID INT NOT NULL AUTO_INCREMENT,

   PRIMARY KEY (ID)
)ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS SM10G10KmTransceiver
(
   ID INT NOT NULL AUTO_INCREMENT,

   PRIMARY KEY (ID)
)ENGINE=InnoDB;

The problem with relational databases is that you have to use Joins and unions, and if you have 15 different tables, the whole things turns into a nightmare.

In case anyone is wondering, we will later need to generate a Bill of Materials, so we may need to find out the total number of single mode transceivers, or total number of PSUs, or power consumption of all 24 port switches, etc.

EDIT It just occoured to me that there is no hierarchy in my example, however, I could make it go like so:

  • Transceiver Table
  • Single/Multi Mode Transceiver table pointing to Transceiver Table
  • etc.

Ironworker connection to Openshift MySQL database

I just installed the ironworker cartridge from Openshift's marketplace - experimenting with a hello-world nodejs worker that tries to connect to the MySQL DB on Openshift and the attempt is refused. [BTW, I can connect to the DB via MySQL workbench using the very same credentials, via port-forwarding]. I also SSH'd in to grab the environment info with

env | grep OPENSHIFT_MYSQL

and used the host and port.

Tried creating a basic connection in the worker and received the following result (actual config values changed):

my config: {"host":"111.11.nnn.nnn","port":3306,"user":"myapp","pass":"xxxxxxxxxxx","db":"app_db"}
about to make DB connection
We got an error connection to the DB: {"code":"ECONNREFUSED","errno":"ECONNREFUSED","syscall":"connect","fatal":true}

I believe the connection is being refused not by the database, but perhaps the firewall/environment itself because I can connect via other means. Suggestions?

FYI - the code:

var mysql = require('mysql');

// variables specific to your ironworker environment
var iron_helper = require('node_helper');
var params = iron_helper.params;
var task_id = iron_helper.task_id;
var config = iron_helper.config;
console.log('my config: ' + JSON.stringify(config));
console.log('about to make DB connection');
var connection = mysql.createConnection('mysql://'+config.user+':'+config.pass+'@'+config.host+':'+config.port+'/'+config.db);


var query = "select count(*) from reservations;";

connection.query( query, function(err, callResults){
if (err) {
   console.log("We got an error connection to the DB: " + JSON.stringify(err));
}
else {
    console.log("We got a result: " + JSON.stringify(callResults));
}
connection.destroy();
});

Selecting the number of last consecutive days from timestamp (excepting today)

I have a table A_DailyLogins with the columns ID (auto increment), Key (userid) and Date (timestamp). I want a query which would return the number of last consecutive days from those timestamp based on the Key, for example if he has a row for yesterday, one for two days ago and another one for three days ago, but the last one isn't from four days ago, it would return 3, because this is the number of last days the user was logged in.

My attempt was to create a query selecting the last 7 rows of the players ordered by Date DESC (this is what I wanted in the first place, but then I thought that it would be great to have all the last consecutive days), and then I retrieved the query result and compared the dates (converted to year/month/day with functions from that language [Pawn]) and increased the number of consecutive days when a date is before the other one with one day. (but this is extremely slow compared to what I think that can be done directly only with MySQL)

The closest thing I found is this: Check for x consecutive days - given timestamps in database . But it still isn't how I want it to be, it's still pretty different. I tried to modify it, but it is way too hard for me, I don't have that much experience in MySQL.

Query runs faster without an index. Why?

I have two tables. One of those tables has this schema:

CREATE TABLE `object_master_70974_` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `id_object` int(10) unsigned NOT NULL DEFAULT '0',
 `id_master` int(10) unsigned NOT NULL DEFAULT '0',
 `id_slave` int(10) unsigned NOT NULL DEFAULT '0',
 `id_field` bigint(20) unsigned NOT NULL DEFAULT '0',
 `id_slave_field` bigint(20) unsigned NOT NULL DEFAULT '0',
 PRIMARY KEY (`id`),
 UNIQUE KEY `id_object`    (`id_object`,`id_master`,`id_slave`,`id_field`,`id_slave_field`),
 KEY `id_object_2` (`id_object`,`id_master`,`id_field`,`id_slave_field`),
 KEY `id_object_3` (`id_object`,`id_slave`,`id_field`),
 KEY `id_object_4` (`id_object`,`id_slave_field`),
 KEY `id_object_5` (`id_object`,`id_master`,`id_slave`,`id_field`),
 KEY `id_object_6` (`id_object`,`id_master`,`id_slave`,`id_slave_field`),
 KEY `id_master` (`id_master`,`id_slave_field`),
 KEY `id_object_7` (`id_object`,`id_field`)
) ENGINE=InnoDB AUTO_INCREMENT=17827 DEFAULT CHARSET=utf8;

As you can see, there is an overlapping index KEY id_object_5 (id_object,id_master,id_slave,id_field) and there is no index that would cover these three fields: id_object, id_master, id_field. However, when I run these two queries:

SELECT f1.id 
FROM object_70974_ f1  
LEFT JOIN object_master_70974_ mss0 ON mss0.id_object IN (70974,71759)  
AND mss0.id_master = 71100 AND mss0.id_slave = 70912 AND mss0.id_field = f1.id

and

SELECT f1.id 
FROM object_70974_ f1  
LEFT JOIN object_master_70974_ mss0 ON mss0.id_object IN (70974,71759)  
AND mss0.id_master = 71100 AND mss0.id_field = f1.id

they both return the same number of rows (since in fact id_slave field does not really matter) - 3530, however, the first query is slower than the second query by one second - 8 and 7 seconds respectively. So, I guess I have to ask two questions - 1) why does the second query run faster, even though it does not use index and 2) why does the first query run so slowly and why does not it use an index (obviously). In short, what the heck is going on?

EDIT

This is the result of EXPLAIN command (identical for both queries):

"id"    "select_type"   "table" "type"  "possible_keys" "key"   "key_len"   "ref"   "rows"  "Extra"
"1" "SIMPLE"    "f1"    "index" \N  "attr_80420_"   "5" \N  "3340"  "Using index"
"1" "SIMPLE"    "mss0"  "ref"   "id_object,id_object_2,id_object_3,id_object_4,id_object_5,id_object_6,id_master,id_object_7"   "id_master" "4" "const" "3529"  "Using where"

EDIT

It's extremely interesting, because if I DROP id_master index (which for some strange reason is used by both queries), then it starts to use id_object_5 index.

EDIT

And, yes, with id_master index being dropped, both queries start to run super-fast. So, I guess there is some trouble with optimizer.

EDIT

I even have a guess what trouble faces the optimizer - it may be incorrectly treats id_slave_field field name in the key, as if it were two fields instead - id_slave and id_field. In this case it becomes reasonable, why it firstly used this key in both queries.

PDO Suggest refine results different than wildcard symbol

I am trying to make a PDO query to be searchable not only by the whole string but also by first letter or last letter anything like this. My question is what approach I have to take to achieve this goal.

My original idea was to use wildcard symbol and something like the following:

SELECT * FROM idname WHERE field LIKE CONCAT('%', :field , '%')

but this option for me is not working since I am getting an error: Warning: Division by zero in

My code ad the moment is the following:

try
{

$paginate = new pagination($page, 'SELECT * FROM idname WHERE field LIKE :field, $options);


}
catch(paginationException $e)
{
    echo $e;
    exit();
}

$paginate->bindValue(':field', $_POST['field'] , PDO::PARAM_STR);
$paginate->execute();

Any suggestions are welcome ?

how to insert form data into MYSQL using python

i am trying to insert the data entered into the web form into database table,i am passing the data to the function to insert the data,but it was not sucessful below is my code

def addnew_to_database(tid,pid,usid,address,status,phno,email,ord_date,del_date):
    connection = mysql.connector.connect(user='admin_operations', password='raghu',host='127.0.0.1',database='tracking_system')
    try:
        print tid,pid,usid,address,status,phno,email,ord_date,del_date
        cursor = connection.cursor()
        cursor.execute("insert into track_table (tid,pid,usid,address,status,phno,email,ord_date,del_date) values(tid,pid,usid,address,status,phno,email,ord_date,del_date)")
        cursor.execute("insert into user_table (tid,usid) values(tid,usid)")
    finally:
        connection.close()

hotspot billing software in php developer needed with ddwrt firmware or else [on hold]

I was going to share net through wifi at my area, So i need online billing softwre, for when user connect to my wifi and excess any page, Page auto redirect to login page. After Login sucessful user can excess any website.

I need online this program in php. with bandwith controll only.

I will Give Money who help me to create sotware in php. I am also a php dveloper but i dont have an Much Idea to do, This project.

Note: Limit user internet bandwith .

Thank You My Contact number is. +91 8149587579 Email: 0shoaib0@gmail.com

bootstrap formvalidation.io remote validator MySQL PHP

i'm having some issues getting a modal form validate a username from Mysql database using PHP.

here is my PHP script to validate the username, when i run it alone it works but when it will not get called from the remote validator.

PHP code :

checkUsername.php

            <?php

             $isAvailable = true;

             //get the username  and password
               $uname = trim($_POST['username']);
               $umail = trim($_POST['email']);

            //connect to database   
            require_once '/php-includes/dbconfig.inc.php';

                     $stmt = $DB_con->prepare("SELECT username, email FROM member WHERE username=:uname OR email=:umail");
                     $stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
                     $row=$stmt->fetch(PDO::FETCH_ASSOC);


                        if($row['username']==$uname) {
                            $isAvailable = false; 
                        }

                     // Finally, return a JSON
                echo json_encode(array('valid' => $isAvailable));
            ?>

and this is the formValidation.io script that i'm using from http://ift.tt/1OFKcKf

            $(document).ready(function() {
                $('#registerForm')
                    .formValidation({
                        framework: 'bootstrap',
                        icon: {
                            valid: 'glyphicon glyphicon-ok',
                            invalid: 'glyphicon glyphicon-remove',
                            validating: 'glyphicon glyphicon-refresh'
                        },
                        fields: {
                            userName: {
                                validators: {
                                    notEmpty: {
                                        message: 'The user name is required'
                                    },
                                    remote: {
                                        url: 'checkUsername.php'
                                    }
                                }
                            }
                        }
                    })
                    // This event will be triggered when the field passes given validator
                    .on('success.validator.fv', function(e, data) {
                        // data.field     --> The field name
                        // data.element   --> The field element
                        // data.result    --> The result returned by the validator
                        // data.validator --> The validator name

                        if (data.field === 'userName'
                            && data.validator === 'remote'
                            && (data.result.available === false || data.result.available === 'false'))
                        {
                            // The userName field passes the remote validator
                            data.element                    // Get the field element
                                .closest('.form-group')     // Get the field parent

                                // Add has-warning class
                                .removeClass('has-success')
                                .addClass('has-warning')

                                // Show message
                                .find('small[data-fv-validator="remote"][data-fv-for="userName"]')
                                    .show();
                        }
                    })
                    // This event will be triggered when the field doesn't pass given validator
                    .on('err.validator.fv', function(e, data) {
                        // We need to remove has-warning class
                        // when the field doesn't pass any validator
                        if (data.field === 'userName') {
                            data.element
                                .closest('.form-group')
                                .removeClass('has-warning');
                        }
                    });
            });
            </script>

Inserting values into column from another table in MySQL

I am inserting one column values from one table to another table. I have following two tables.

 Table - a

    ID    Entry_date    weight   height    TagsA
    111   1968-07-31    22       34
    111   1968-12-31    34       37
    112   1969-03-31    8        43
    112   1969-07-31    45       48
    113   1970-09-30    67       94
    113   1973-03-31    23       76

   Table - b

    ID    Entry_date    TagsB
    111   1968-07-31    1
    111   1968-12-31    1
    112   1969-03-31    0
    112   1969-07-31    0
    113   1970-09-30    0
    113   1973-03-31    1

These both tables are having equal number of rows around 44300. ID and Entry_date columns are same for both the tables. I want to get insert all the values present in Table - b column TagsB to Table - a column TagsA. So the resulting table should look like this:

 Table - a

    ID     Entry_date    weight   height    TagsA
    111   1968-07-31    22       34        1
    111   1968-12-31    34       37        1
    112   1969-03-31    8        43        0
    112   1969-07-31    45       48        0
    113   1970-09-30    67       94        0
    113   1973-03-31    23       76        1

I tried to use update:

update a set TagsA = (select TagsB from b where a.ID = b.ID and a.Entry_date = b.Entry_date);

Error Code: 1242. Subquery returns more than 1 row  714.523 sec

How to proceed in this case?

MySql Table Self Join

I have the table below

sku|date
---|---
A1 |Jan
A2 |Jan
A1 |Jan
A1 |Feb
A2 |Feb

I'm trying to get the count per month. I'd like to get the output below;

sku|JAN|FEB
---|---|--|
A1 |2  |1 |
A2 |1  |1 |

I've tried self join and left join with no success, and I'm getting a bit confused.

I get incorrect results with the code below

select s.sku, count(f.sku)
from database f, database s
where f.sku between '2015-01-01' and '2015-01-31'
and
s.sku=f.sku
group by s.sku

Please advise.

Rails active record WHERE EXISTS query

I have an SQL query that returns what I need, but I'm having trouble converting this into an active record query the "Rails way".

My SQL query is:

SELECT * from trips 
WHERE trips.title LIKE "%Thailand%"
AND EXISTS (SELECT * from places WHERE places.trip_id = trips.id AND places.name LIKE "%Bangkok%")
AND EXISTS (SELECT * from places WHERE places.trip_id = trips.id AND places.name LIKE "%Phuket%")

I'm trying something like this using Rails:

@trips=Trip.where("trips.title LIKE ?", "%Thailand%")
@trips=@trips.includes(:places).where(("places.name LIKE ?","%Bangkok%").exists?) => true, ("places.name LIKE ?","%Phuket%").exists?) => true)

But it doesn't seem to work and i'm stumped as to what to try.

MySQL Where clause values 0 and 1 not working correctly

The situation

In table I have columns configurated as ENUM('0','1'). I have select query build with PDO like this example

$value = isset($_POST['value']) ? $_POST['value'] : (isset($_GET["value"]) ? $_GET["value"] : null);

$sql = $pdo->prepare("SELECT * FROM tablename WHERE column = :value");
$sql->bindValue(':value', $_POST['value']); // post contains 0 or 1
$sql->execute();


The problem

When printing the results, value 1 is working normally. But when using value 0, all rows are showing including rows with value 1.

Following query is working normally when trying it in HeidiSQL, but it's not with PHP. What's wrong?

SELECT * FROM tablename WHERE column = '0'

I noticed that PHP thinks $_POST['value'] is unset when its value is zero. I'm using isset()


Trying to solve the problem

  • No effect either if using $_GET['value'] and url like index.php?value=0

  • Tried following, not working

    $sql->bindValue(':value', '0'); // post contains 0 or 1
    
  • I changed column type to TINYINT(1) - no effect. When looking for zero, all are showing.

  • Set PDO bindValue() $data_type to PDO::PARAM_BOOL, not working

MySQL INSERT IGNORE Adding 1 to Non-Indexed column

I'm building a small report in a PHP while loop. The query I'm running inside the while() loop is this:

INSERT IGNORE INTO `tbl_reporting` SET datesubmitted = '2015-05-26', submissiontype = 'email', outcome = 0, totalcount = totalcount+1

I'm expecting the totalcount column to increment every time the query is run. But the number stays at 1. The UNIQUE index composes the first 3 columns.

Here's the Table Schema:

CREATE TABLE `tbl_reporting` (
 `datesubmitted` date NOT NULL,
 `submissiontype` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
 `outcome` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `totalcount` mediumint(5) unsigned NOT NULL DEFAULT '0',
 UNIQUE KEY `datesubmitted` (`datesubmitted`,`submissiontype`,`outcome`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

When I modify the query into a regular UPDATE statement:

UPDATE `tbl_reporting` SET totalcount = totalcount+1 WHERE datesubmitted = '2015-05-26' AND submissiontype = 'email' AND outcome = 1

...it works.

Does INSERT IGNORE not allow adding numbers? Or is my original query malformed?

I'd like to use the INSERT IGNORE, otherwise I'll have to query for the original record first, then insert, then eventually update.

My PHP code on my PC(working great) doesn't work on my laptop

I have these two functions to fill a dropdown list.

function fillcombo($table,$colname)
{

$list="";

$sql="select $colname from $table order by $colname";

$Rs = setRs($sql); // Get data from database using setRs function


    foreach($Rs as $opt) {

    $list .='<option value="'.$opt[$colname] .'">'. $opt[$colname] .'</option>';

    }
    unset($opt);
 return $list;
}

//---------------------------------------------------------------------------

function setRs($sql){

include ('connect.php');

mysqli_select_db($conn,"MyDB" ); //Select database

$Rs = mysqli_query($conn,$sql) or die(mysqli_error($conn)); //Run Query

return $Rs; //Return recordset

$conn->close();

}


// This $Recordset has 93 rows as in my database. But the foreach loops only 5 times.

return $list yields the following html.

<option value=""></option><option value=""></option><option value=""></option><option value=""></option><option value=""></option>

On my PC it works fine and the select list is filled with all the 93 values. Any help will be greatly appreciated..Thanks

Cannot add foreign key constraint. Mysql

By executing the following SQL statement it gives me an error such as "Error 1215: Cannot add foreign key constraint"

this is my SQL code. the erro gives me to create the first table: "process"

CREATE TABLE process(
  idp VARCHAR(36) NOT NULL,
  idc VARCHAR(36) NOT NULL,
  name VARCHAR(255) NOT NULL,
  description TEXT NULL,
  provider TEXT NULL,
  PRIMARY KEY(idp),
  FOREIGN KEY (idc) REFERENCES clients(idc)
  ON DELETE CASCADE
) ENGINE=INNODB;

CREATE TABLE tag_group (
  idtg VARCHAR(36) NOT NULL,
  idp VARCHAR(36) NOT NULL,
  name VARCHAR(255) NOT NULL,
  description TEXT NULL,
  ttl TEXT NULL,
  PRIMARY KEY(idtg),
  FOREIGN KEY (idp) REFERENCES process(idp)
  ON DELETE CASCADE
) ENGINE=INNODB;

CREATE TABLE clients (
  idc VARCHAR(36) NOT NULL,
  name VARCHAR(255) NOT NULL,
  company VARCHAR(255) NOT NULL,
  address VARCHAR(255) NULL,
  phone VARCHAR(45) NULL,
  fax VARCHAR(255) NULL,
  website VARCHAR(255) NULL,
  PRIMARY KEY(idc)
) ENGINE=INNODB;

CREATE TABLE users (
  idu VARCHAR(36) NOT NULL,
  idc VARCHAR(36) NOT NULL,
  title VARCHAR(36) NULL,
  firs_name VARCHAR(255) NOT NULL,
  last_name VARCHAR(255) NOT NULL,
  email VARCHAR(255) NULL,
  password VARCHAR(255) NOT NULL,
  country VARCHAR(255) NULL,
  city VARCHAR(255) NULL,
  telephone VARCHAR(255) NULL,
  is_agent BOOLEAN NOT NULL,
  last_login TIMESTAMP NULL,
  timeout TIMESTAMP NULL,
  timeout_enabled BOOLEAN NULL,
  preferred_language VARCHAR(36) NOT NULL,
  PRIMARY KEY(idu),
  FOREIGN KEY (idc) REFERENCES clients(idc)
  ON DELETE CASCADE
) ENGINE=INNODB;

Mysql regex error #1139 using literal -

I tried running this query:

SELECT column FROM table WHERE column REGEXP '[^A-Za-z\-\']'

but this returns

#1139 - Got error 'invalid character range' from regexp

which seems to me like the - in the character class is not being escaped, and instead read as an invalid range. Is there some other way that it's suppose to be escaped for mysql to be the literal -?

This regex works as expected outside of mysql, http://ift.tt/1Iz37Gq.

I came up with an alternative to that regex which is

SELECT column FROM table WHERE column NOT REGEXP '([:alpha:]|-|\')'

so the question isn't how do I get this to work. The question is why doesn't the first regex work?

Nodejs user authentication sql command

i am trying to make user authentication form in node.js with express.

currently i am using this query to insert in my db.

var  username = req.body.username;
var  password = req.body.password;


connection.query('USE one');
  connection.query("INSERT INTO users(id,name,pass) VALUES (1,"+ username +","+password+")", 
    function (err, result) {
        if (err) throw err;
    }
);

my db structure is

+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(30) | NO   |     | NULL    |                |
| pass  | varchar(20) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

Please help i am getting an error:-

throw err; ^ Error: ER_BAD_FIELD_ERROR: Unknown column 'jjhk' in 'field list'