Thursday, April 21, 2011

make a new behavior for cakephp

i am working on cms in which users submits articles and visitors can vote on those articles, so i am confused. should i make a vote behavior (since it deals with data) or i will me it on a component (because it is an action in my controller) ?

help is very appreciated.

From stackoverflow
  • Neither. Behaviors are for applying the same functionality ("behavior") to multiple models. Only your Article model is "voteable". Likewise, Components are for re-using the same functionality in multiple Controllers, but again, only the Article controller needs a vote action.

    Perhaps in your Article views (index listing and single view), you may want to create a vote Element that gets rendered next to each article title in the index view, and next to the title in the single Article view as well. Since this "vote widget" is needed in at least 2 different views, writing it as an Element makes perfect sense.

    I hope this clarifies things a bit for you.

    NOSLOW

  • NOSLOW pretty much has it nailed, but he didn't mention the model part. If it were me, I would make a Votes model. I usually use the models to deal with data (fat models). Have the controllers handle the request, shepard the data, and pass it off to the fat model.

    As NOSLOW said, I would make the voting section an element to include in your views.

Using aspnet_regiis to change the ASP.Net version of a single site on a web server

We would like to change a web site from version 1.1 to 2.0.50727 during the installation of a solution.

We would prefer a solution that could do this in code.

We can do this by running Aspnet_regiis -i . However, this has a drawback that it changes the version for all sites on the server, and the customer may have other sites that we should not change.

Is there a way to do this in code?

Is there a way to run Aspnet_regiis such that it only affects a single site on the web server?

From stackoverflow
  • Is there a way to run Aspnet_regiis such that it only affects a single site on the web server?

    Yes.

    Run aspnet_regiis -? and it will list all its options, including how to specify a virtual directory (it will include all child virtual directories as well).

  • For a virtual directory use:

    C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis /s W3SVC/1/ROOT/<YourVirtualDirectoryName>
    

    Where 1 (W3SVC/1/ROOT) is the website id.

  • Found a similar question on stackoverflow with an answer that used code:

    http://stackoverflow.com/questions/1299084/iis-6-0-directoryentry-scriptmaps-property-and-set-net-version

Structure memory allocation

struct node{
  int data;
  struct node * next;
};

How does the compiler allocate memory for "next" member in when we have not yet allocated memory for the structure "struct node"

From stackoverflow
  • Next is only a pointer so it is a fixed size value in every machine, it'll just add int+pointer sizes + padding and allocate node struct

  • The member next is a pointer. Pointers are all the same size, so the compiler does not need to know how big the thing that next may point to is.

    Christopher : In other words, the compiler allocates enough space for "next" to store the pointer to node in the node structure. To actually use "next" you must make another allocation call to fill the next structure.
  • next member is a pointer - a variable that will contain an address of node, not node itself. All data type pointers are usually of the same size so it's enough for the compiler to know that it's a pointer to be able to compute its size.

what does ^A stand for in vim

I need to replace ^A, ^B in a file, the following command is useless :s/^A/

From stackoverflow
  • You need to escape the ^ with a \, i.e. s/\^A/^B/. ^ denotes "start of line" in a regular expression. In the replacement text, escaping is not necessary, but possible.

  • To get the ^A character, press CTRL-V CTRL-A

    If you have configured the "paste" action with CTRL-V (generally on Windows) you can use CTRL-Q instead of it.

phpmailer error "Could not instantiate mail function"

I'm using the mail() basic example modified slightly for my user id and I'm getting the error "Mailer Error: Could not instantiate mail function"

if I use the mail function -

mail($to, $subject, $message, $headers);

it works fine, though I'm having trouble sending html, which is why I'm trying PHPMailer.

this is the code:

$mail             = new PHPMailer(); // defaults to using php "mail()"
$body             = file_get_contents('contents.html');
$body             = eregi_replace("[\]",'',$body);
    print ($body ); // to verify that I got the html
$mail->AddReplyTo("reply@domain.com","my name");
$mail->SetFrom('from@domain.com', 'my name');
$address = "to@domain.com";
$mail->AddAddress($address, "her name");
$mail->Subject    = "PHPMailer Test Subject via mail(), basic";
$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
$mail->AddAttachment("images/phpmailer.gif");      // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment

if(!$mail->Send()) {
 echo "Mailer Error: " . $mail->ErrorInfo;
} else {
 echo "Message sent!";
}

?>

From stackoverflow
  • You need to make sure that your from address is a valid email account setup on that server.

How to pass http://www.domainname.com as variable in htaccess?

Hi,

In my htaccess I have line

RewriteRule ^link-([0-9]+)-(.*).htm$ link.php?id=$1&link=$2 [L,NC]

For variable 2 there may be link as well. For example: http://wwww.mysite.com/link-10-www.domain.com/click.htm?id=497&mid=13&prod=1&productname=name&target=http://www.domainname.com/name2.htm. When i click on this link, page not found message is displayed. Can anyone help me to find the solution?

Thanks for your co-operation

From stackoverflow
  • Your RewriteRule and your example appear to be completely different. Your RewriteRule shows a redirect matching a URL with link-123-something.htm in it, but the example URL you give goes to click.htm.

    If you want click.htm to redirect somewhere, you'll need a separate RewriteRule.

    : Thanks i made correction above :)
  • Your example will look at this query string:

    link-10-www.domain.com/click.htm
    

    and assign

    $1 = 10
    $2 = www.domain.com/click
    

    and rewrite to

    link.php?id=10&link=www.domain.com/click
    

    If that is not happening, I would check whether you have a file called link.php. Also, you have four w's in your example (wwww.mysite.com).

    If you have a file called link.php, can you tell whether it gets called? Since it is being passed a link, perhaps it is redirecting to "www.domain.com/click" and that file doesn't exist?

    Hard to tell without knowing more.

HTML iframes and javascript

I have two iframes and each iframe show two different html pages. Both html pages refer to a common javascript file which contains a global variable. If I set the value of that global variable in one frame during html page load. Will the value be accessible using the same global variable to another iframe html page? why or why not?

From stackoverflow
  • No. The top level of JavaScript's scope space is the page level. However, you can access another page's scope by using window.parent

    Rex M : @Deepak feel free to click the "Check" to accept the answer if it solves your problem or answers your question.
    Benry : Alas, he cannot accept your answer until he has a reputation of 10. Which he does now, since I up-voted his question.
    Benry : Maybe this is no longer true. Was once.
  • Actually I'm noticing it doesn't seem to maintain scope and maybe someone can shed light on this.

    Example 1: You have a HTML page with some Flash Content that has some functions to get the SWF Object and fire a command. When this page is loaded into a IFRAME the 'getSWFObj' is "not a function".

    Example 2: I load a HTML Page that has a series of object based JavaScript files. I create a instance called "player" and it creates some sub objects like "navigation". When I call "player.navigation" I get a error saying it doesn't exist when loaded into a IFRAME.

Jquery count number of hidden elements within div

How can I count the number of items in div that are hidden?

Thanks in advance

From stackoverflow
  • I think that

    $("#someElement > *").filter(":hidden").size();
    

    will work.

    Updated: Added the '*'. Note that this will select the immediate children of #someElement.

    Zed : Nope, this will return 1, if #someElement is hidden, 0 otherwise.
    jscharf : You're right - the selector is missing a relation. Updated.
    Ronal : Excellent answer, thank you!
  • Direct children of someElement that are hidden:

    $('#someElement > :hidden').length;
    

    Any descendants of someElement that are hidden:

    $('#someElement :hidden').length;
    

    If you already have a jQuery object you can use it as the context:

    var ele = $('#someElement');
    
    $(':hidden', ele).length;
    
  • $("#someElement *:hidden").size()
    

SerialPort.DataReceived repeatedly subscribe/unsubscribe

I am using a serial port to communicate with a remote diagnostics device.

The length of the response from the remote device varies depending upon the command but is known ahead of time. So, currently I send the command and wait for the required number of response bytes to be received.

I subscribe to the 'SerialPort.DataReceived' event whenever I'm not actively soliciting data. The handler for this event simply dumps any 'unsolicited' received data to a log (unsolicited data is typically only received if the remote device restarts unexpectedly, etc).

In some cases I want to send commands at a rate of about 60Hz.

My question is whether it's best to unsubscribe/subscribe to the 'SerialPort.DataReceived' event every time I call my 'SendCommand' method to actively solicit data, or should I leave the event subscription alone and just toggle a boolean 'TransferInProgress' flag that the DataReceived handler can use to ignore incoming data when I'm actively soliciting it?

Here's the current implementation:

public virtual bool SendCommand(byte[] command, ref byte[] response) {

    try {
        TransferInProgress = true;
        OnTransferStarted();

        // temporarily unsubscribe since we're actively soliciting data
        _port.DataReceived -=
            new SerialDataReceivedEventHandler(SerialPort_DataReceived);

        _port.DiscardInBuffer();
        _port.Write(command, 0, command.Length);
        OnCommandSent(command);

        // read the requested number of response bytes
        int responseBytesRead = 0;

        while (responseBytesRead < response.Length) {
            responseBytesRead +=
                _port.Read(response, responseBytesRead, (response.Length - responseBytesRead));
        }

        OnCommandResponseReceived(response);
        return true;
    }
    catch (Exception ex) {
        OnCommandSendFailed(ex.Message);
        return false;
    }
    finally {
        _port.DataReceived +=
            new SerialDataReceivedEventHandler(SerialPort_DataReceived);
        OnTransferComplete();
        TransferInProgress = false;
    }
}

-Trevor

From stackoverflow
  • My opinion if I'm understanding correctly would be to simply handle all your receiving data in the DataReceived handler or you have one other options.

    If the data received between actual request isn't much you could just read the buffer and log it before transmitting your request. The serial driver receive buffer may be enough to store a small amount of data. Then send the request and read in just the response. This will probable be the easier method and simpler code.

  • I normally toggle a boolean. With subscribing/unsubscribing you run the risk of subscribing to the same event more than once. For instance in your code if OnTransferStarted() throws an exception you will subscribe twice to the DataReceived event.

  • Have you thought about handling all of your data reception in one place? You could treat the commands you send as fire and forget, parsing the data received for the responses. If the responses do not have an identifying header and the ONLY way you know how to parse them is by knowing which command you sent and the length of the response, then you could keep track of the commands sent in a queue. The way that would work, is that in your Data Received handler you would check the queue of commands you're waiting on a response for, and then parse the data received like you do now.

    Long story short, I would recommend handling all incoming data in one place.

    : I like the idea of using a queue to track commands but I'm wondering how I'd be able to detect unsolicited data? How would I be able to determine if the remote device fires out a few bytes in between commands using this method? (note: the remote device occasionally seems to reset itself and sends out a few 'startup' type bytes. I don't have control over this, unfortunately).
    nathan : You'd still detect the unsolicited data in your Data Received handler, but you would know it's unsolicited because you have no commands in your "SentCommandsQueue". I've had similar problems in serial communications, you'll have to buffer your received data and piece together the answers parsing out the reset messages. Once you have a complete response, remove the command from your queue. Since the reset bytes seem to have some sort of signature for the beginning of the sequence, you should be able to parse them out easily.
    : I think I can probably implement something like this. My only reservation is that the reset bytes aren't always the same (in order or quantity), so it might be possible to end up with an unintended offset if the reset data is received in between normal commands. That said, I believe this particular serial device has an option to enable command echoing. I can use the command echo as the identifying header during parsing of the response array.

Can the controller code generation template be changed?

In Visual Studio when you add a new controller to your MVC application some macro creates a file with methods like:

//
// GET: /Thing/Details/5

public ActionResult Details(int id)
{
    return View();
}

I want my methods to look like:

/// <example>GET: /Thing/Details/XXX...</example>
public ActionResult Details(Guid id)
{
    return View(Repository.GetItem<Thing, Guid>(id, "Id"));
}

The main differences are standard notation for the comments with the two redundant lines removed and I use unique identifiers rather than integers for my id's. If possible, I'd like the code to pass my Model to the view to also be generated.

Is there a built in mechanism that will let me control the code template that is used?

From stackoverflow
  • I think David Hayden has a solution for you here. Blog Post

    Hope that hleps,

    Dan

    grenade : Beautiful, thanks!

iTextSharp and DataGridView

Where can I find a code snippet which can convert a DataGridView to a PDF document using iTextShape or something similar?

I want to have the same table headers as in DataGridView in my PDF document.

From stackoverflow

NSString to Print in in binary format

Hi I dont understand of the below case of converting int to byte , the below java code can able to print the byte value as below

System.out.println("binary output ::: "+Byte.toString(bo[0]));
System.out.println("binary output ::: "+Byte.valueOf(bo[1]));
System.out.println("binary output ::: "+Byte.valueOf(bo[2]));
System.out.println("binary output ::: "+Byte.valueOf(bo[3]));
System.out.println("binary output ::: "+new String(bo));

binary output ::: 0
binary output ::: 0
binary output ::: 0
binary output ::: 1
binary output ::: squaresquaresquaresquare ( 4 square chars) - binary data

but when i make a objective-c code to the same data into final NSString it also prints as "0001" but not in binary format ( 4 square chars)

I need NSString in binary format how do i print NSString in binary format instead of "0001"

please help

From stackoverflow
  • The string is printing the integers, because that's what you're putting into it (%i == integer). %c is the token for characters.

    Or, you can just pass the array into -[NSString initWithBytes:length:encoding:]. If you a string with a single byte, use the same method, passing an offset pointer into the array, and a length of one.

    kperryua : I'd have to see the code you used when you tried it to help you any more.
  • Hi kperry NSString *str = [ [NSString alloc] initWithBytes:barr length:sizeof(barr) encoding:NSUTF8StringEncoding]];

    I have tried ASCII necoding also , but it only gives empty string only.

WCF: What value should the servicePrincipalName have?

I'm trying to set up client impersonation on my service.

I need to set a value for the servicePrincipalName of my services endPoint

I'm looking at this but still cannot quite figure it out
http://technet.microsoft.com/en-us/library/cc961723.aspx

My service is hosted in a console app on a server that we'll call ServerName1.
The Uri is: "net.tcp://ServerName1:9990/TestService1/"

What specifically should my servicePrincipalName be?

I tried, with no joy:

<identity>
    <servicePrincipalName value="ServerName1" />
</identity>
From stackoverflow
  • The name of the user you wish the service to user (execute under). So if you want to execute it under 'local network' credentials the above XML should look like:

    <identity>
        <servicePrincipalName value="Local Network" />
    </identity>
    
  • Configuring servicePrincipleName is a difficult topic to describe it in a few words Perhaps these articles will help http://msdn.microsoft.com/en-us/library/bb628618.aspx http://msdn.microsoft.com/en-us/magazine/cc163570.aspx#S6

    Most probably, you need to configure it the following way

    <identity>
        <servicePrincipalName value="HOST/ServerName1:9990" />
    </identity>
    

    We usually use userPrincipalName instead of servicePrincipalName, like this

    <identity>
      <userPrincipalName value="account@domain.com" />
    </identity>
    

Reading and Updating application settings from NSUserDefaults using Flipside View Controller.

Does any one have a good sample to read and update application settings from NSUserDefaults using a flipside view controller.

I'd like to read and edit 4 fields stored in textbox, pickerview and a slider control. Any sample code would be helpful.

From stackoverflow

list of duplicate dictionaries copy single entry to another list

Hello,

newbie question again.

Let's say i have a list of nested dictionaries.

a = [{"value1": 1234, "value2": 23423423421, "value3": norway, "value4": charlie},
     {"value1": 1398, "value2": 23423412221, "value3": england, "value4": alpha},
     {"value1": 1234, "value2": 23234231221, "value3": norway, "value4": charlie},
     {"value1": 1398, "value2": 23423213121, "value3": england, "value4": alpha}]

What i want is to move a singularis entry of each duplicate where value1, value3 and value4 matches. The result should be looking like this:

b = [{"value1": 1398, "value2": 23423412221, "value3": england, "value4": alpha},
     {"value1": 1234, "value2": 23234231221, "value3": norway, "value4": charlie}]

The orginal list, a, should remain in it's orginal state.

From stackoverflow
  • There was a similar question on this recently. Try this entry.

    In fact, you asked that question: "Let's say there exists multiple entries where value3 and value4 are identical to other nested dictionaries. How can i quick and easy find and remove those duplicate dictionaries."

    It sounds like the same thing, right?

    Edit: liberally stealing Alex's code, it looks something like this:

    import itertools
    import pprint
    import operator
    
    alpha, charlie, norway, england = range(4)
    
    a = [{"value1": 1234, "value2": 23423423421, "value3": norway, "value4": charlie},
         {"value1": 1398, "value2": 23423412221, "value3": england, "value4": alpha}, 
         {"value1": 1234, "value2": 23234231221, "value3": norway, "value4": charlie}, 
         {"value1": 1398, "value2": 23423213121, "value3": england, "value4": alpha}]
    
    
    getvals = operator.itemgetter('value1', 'value3', 'value4')
    
    a.sort(key=getvals)
    
    b = [g.next() for _, g in itertools.groupby(a, getvals)]
    pprint.pprint(b)
    

    And the result is:

    [{'value1': 1234, 'value2': 23423423421L, 'value3': 2, 'value4': 1},
     {'value1': 1398, 'value2': 23423412221L, 'value3': 3, 'value4': 0}]
    
    Jonas : Yes :) stupid of me.

Rebol Draw: how to load image from the internet ?

This works

view layout [
    image load http://i2.ytimg.com/vi/e3wShd_bX8A/default.jpg
]

But this doesn't

view layout [box 100x100 effect [draw [
        image load http://i2.ytimg.com/vi/e3wShd_bX8A/default.jpg
    ]
]
From stackoverflow
  • LOAD is not part of the EFFECT or DRAW dialects, so it is being ignored.

    You can use COMPOSE to ensure it gets executed:

    view layout [
        box 100x100 effect compose/deep [
            draw  [
            image (load http://i2.ytimg.com/vi/e3wShd_bX8A/default.jpg)
            ]
        ]
    

    ]

    Notes:

    • COMPOSE/DEEP because we are two deep in blocks -- effect [draw [ ... ]]

    • the "native" REBOL code that you want executed is in parenthesis: (load ...)

How to declare variable containing character limiting to 1000 bytes in vb6

How to declare variable containing character limiting to 1000 bytes in vb6

From stackoverflow
  • This is a rough approximation. It assumes you are flexible with that 1000 byte limit.

    Private mData As String
    Public Property Let Data(value As String)
    
        If Len(value) <= 1000 Then
            mData = value
        Else
            'Do whatever '
        End If
    
    End Property
    
  • Dim myString as String * 1000
    
    ChaosPandion : I had no idea... +1
  • Here is the syntax for a fixed-length string of 500 characters, which is 1000 bytes. VB6 strings are Unicode (UTF-16) and therefore each character has two bytes. The value of a fixed-length string will always have 500 characters - trailing spaces will be added, or excess characters truncated.

    Dim s As String * 500  ' 500 characters, 1000 bytes
    

    I wonder whether you are dealing with binary data rather than text. The Byte data type is better for binary data.

    Dim byt(1000) as Byte  ' an array of 1000 bytes
    

What does it mean by putting dots into a struts forward tag?

As the example below, I came across this one when reading the source code of JAVA D.I.Y Forum.

<forward name="feedback" path=".page.index.feedback"/>
<forward name="group" path=".page.index.group"/>
From stackoverflow
  • Unfortunately I'm finding it hard to see the source for JAVA D.I.Y Forum (it seems to only be available in a RAR file, and I'm not installing something just to look at it), but I would guess that the project is using tiles. Somewhere there should be a tiles configuration file which tells the application how to build the view.

    Winston Chen : yeah.. it turns out to be tiles. Thank you man!!

looking for idea to embbed "book like view " in exe file

Hello all i have application that convert data structure from the GUI to doc/pdf/rtf/html ... files the structere logic contains the info about pages and data on each page so basccly i can convert it to every thing . but my problem is that i wish to convert this structure to some kind of book that is exe binary file . and i have no idea how or which ways i can do it ? can you give me some ideas or solutions on who to embed book into exe file Thanks

From stackoverflow
  • Do you want a PDF? Your question doen't make much sense. Please elaborate.

    : i like it to be self contained exe file that will be able to "somehow" display browserble text ( like pdf )
    Noon Silk : Why not use PDF?

Help eliminating friends/internals

I often see people say things like "if you need friend/internal then your design is wrong", could someone tell me how to redesign the following code to eliminate the internal in ChessPiece.Location?

It's currently used so that adding a piece to ChessBoard sets the ChessPiece.Location property to match, obviously making it public would be even worse than internal and making it private would prevent ChessBoard from updating the Location. Thanks for any insights.

public struct Coord
{
   public Coord(int x, int y) { this.X = x; this.Y = y; }
   public int X { get; private set; }
   public int Y { get; private set; }
}

public class ChessBoard
{
   public ChessBoard() { /*[...]*/ }
   public ChessPiece this[int x, int y]
   {
       get
       {
           // Return ChessPiece at this position (or null)
       }
       set
       {
           // Add ChessPiece at this position and set its Location property
       }
}

public class ChessPiece
{
   public ChessPiece() { /*[...]*/ }
   public Coord Location { get; internal set; }
}
From stackoverflow
  • My first thoughts would be

    • board is just a container
    • piece has a public read-only immutable position property
    • Initial position is set in piece construction
    • Position is changed by invoking a move operation on a piece
  • I personally think it's strange that the ChessPiece knows it's location - that seems like a function of the ChessBoard, not the piece itself. (What location is a chess piece after it's taken and off the table? It'd normally still be a valid piece...)

    I'd put the location/movement logic into the ChessBoard, and store a Dictionary<ChessPiece, Coord> for the location of each valid chess piece.

  • I often see people say things like "if you need friend/internal then your design is wrong"

    I think that's silly. Friend and internal exist in the language for good reason.

    eliminate the internal in ChessPiece.Location

    That would make it impossible to update the ChessPiece.Location.

    That would be OK if the ChessPiece knew enough about the game to update its own Location, for example:

    public class ChessPiece
    {
      public ChessPiece() { /*[...]*/ }
      public Coord Location { get; }
      //a measure of how good it would be to move this piece
      public int GoodnessOfBestMove
      {
        get
        {
          //calculate what self's best possible move is
          ... todo ...
        }
      }
      //an instruction to go head and do that move
      public void Move()
      {
        //do self's self-calculated best move, by updating self's private Location
        ... todo ...
      }
    }
    
    class Strategy
    {
        void Move()
        {
          ChessPiece bestChessPiece = null;
          foreach (ChessPiece chessPiece in chestPieces)
          {
            if ((bestChessPiece == null) ||
              (chessPiece.GoodnessOfBestMove > bestChessPiece.GoodnessOfBestMove))
            {
              //found a better piece to move
              bestChessPiece = chessPiece;
            }
          }
          //found the best piece to move, so now tell it to move itself
          bestChessPiece.Move();
        }
    }
    

    For further details there's an OO principle called "tell don't ask" which you can Google for.

    Another possibility is for the Board to store each ChessPiece in a 2-D array owned by the board. To move a piece, the Board puts the piece in a different slot in the array; and when a piece wants to report its location, it searches for itself in the array.

    ALthough the above are alternatives, I'm not saying that they're necessarily good or better solutions for this problem: I don't think I'd want to encode game strategy as an implementation detail of each piece; instead I might have some non-private way to let some other class update the Location of each piece.

  • I agree strongly with Steve. Internal and friend are in the language for a reason, but this isn't necessarily an example of it.

    Personally I'd put a Move(Coord) method on the piece. That way the piece can validate the validity of its own moves (plus you can use derived classes for specialized logic, i.e. for pawn vs knight). Coord should be immutable (the coordinate doesn't move and should be immutable, the piece moves to a new coordinate).

    You shouldn't be able to just set a piece on the board at any point, that moves your responsibility for the validity of a move to your calling class. If you need to set up custom boards, create a new board with a new starting position.

    I'd also disagree about the strategy approach. I do agree a strategy pattern is good here, but it shouldn't necessarily be built into the piece. I would move the strategy into piece-specific strategy classes. This way your pieces and board are simple, clean and usable for a person-vs-person game and extended for a person-vs-cpu game

Good asp.net mvc (VB) books

Are there any good MVC books using the VB language?

Thx...

From stackoverflow
  • ASP.NET MVC Framework Unleashed

    By Stephen Walther

  • Not sure about VB but if you consider c# then: (Apress) Pro ASP.NET MVC Framework, by Steevn Sanderson, is a great read!

  • I suggest Professional ASP.NET MVC 1.0. The code examples are in C# but if you are a decent VB.NET developer (i am primarily VB.NET myself) you should have no problem following it and converting to VB.NET in your head. I'd prefer a good book with C# than a bad one aimed at the VB.NET crowd. Just my two cents...

on click submit problem

Using jquery, I want to post data to from one of my pages to another one. By looking at examples, I coded something. Problem here, I get the following error.

Error: $(document.getElementsByName("signup")).Click is not a function Source File: http://sabahtan.com/ak/ Line: 18

    $(document).ready(function() { 
        $(document.getElementsByName("signup")).Click(function() { 
                $.ajax({
                        type: "POST",
                        data: { PROCESS: "Add2Member", FIRSTNAME: $(document.getElementsByName("FIRSTNAME")).val(), LASTNAME: $(document.getElementsByName("LASTNAME")).val(), EMAILADDRESS: $(document.getElementsByName("EMAILADDRESS")).val(), PASSWORD: $(document.getElementsByName("PASSWORD")).val(), CITY: $(document.getElementsByName("CITY")).val() },
                        url: "default.cs.asp", 
                success: function(output) { 
                $("#SIGNUPFORM").html(output);
                }
                }); 
        }); 
    });


                    <form method="post" action="default.cs.asp?Process=Add2Member" id="SIGNUPFORM">
                        <fieldset>
                            <p>
                                <label>Adınız</label>
                                <input type="text" name="FIRSTNAME" />
                                <small><%=err_FIRSTNAME%></small>
                            </p>
                            <p>
                                <label>Soyadınz</label>
                                <input type="text" name="LASTNAME" />
                                <small><%=err_LASTNAME%></small>                                    
                            </p>
                            <p>
                                <label>E-posta Adresiniz</label>
                                <input type="text" name="EMAILADDRESS" />
                                <small><%=err_EMAILADDRESS%></small>
                            </p>
                            <p>
                                <label>Şifreniz</label>
                                <input type="text" name="PASSWORD" />
                                <small><%=err_PASSWORD%></small>
                            </p>
                            <p>
                                <label>Yaşadığınız Yer</label>
                                <input type="text" name="CITY" />
                                <small><%=err_CITY%></small>
                            </p>
                            <p>
                                <input type="submit" name="signup" value="Kaydol" class="signup">
                            </p>
                        </fieldset>
                    </form>
From stackoverflow
  • It should be click not Click

    You can use selectors to simplify this:

    $(document.getElementsByName("signup")).Click(function() {
    

    to this:

    $("*[name=signup]")).click(function() {
    

    Though personally I'd just put an id on the signup element.

    Efe : Thanks! I dont receive the error anymore. But, when submit clicked, user still redirected to default.cs. But I want them stay on the same page, default
    Greg : Try making the click function return false
    Efe : I have url: "default.cs.asp" in javascript but I did not remove action="default.cs.asp?Process=Add2Member" from the form. Do I need to remove it?
    Greg : No, don't remove the action
    Efe : hey this still is not working as I want it to be. When submit button click, page still redirected. Text link: http://www.aslanyurek.com/
  • I'm pretty sure you want submit and check out serialize

    $("#SIGNUPFORM").submit(function() {
                     $.ajax({
                        type: "POST",
                        data: $(this).serialize() ,
                        url:  this.action, 
                success: function(output) { 
                $("#SIGNUPFORM").html(output);
                }
    
      return false;
    });
    

    If you really want to make life easy you can check out the Form plugin

mysql 4.x login problem

Hi I install php 5 and mysql 4.x and mysql 5.x on my windows server. When I try to connect my sql 4 from php myadmin I got access denied for user@localhost USING password : yes

I try command line , and inform if I use mysql -uuser -p , I can login wihtout problem but if I use mysql -uuser@localhost -p , I got access denied error.

What is diffrence between user and user@localhost ? what setting is wrong?

From stackoverflow
  • MySQL will search for the user named after the -u parameter; user@localhost is not the value stored in the mysql.user table, so use user. Note that if you want to specify the host, use the -h param:

    mysql -u user -h localhost -p
    

ASP.NET MVC: Make Session entirely cookie-less (hidden form field)

Hello, is there some kind of standardized way which would allow me to make my ASP.NET MVC web app sessions entirely cookie*less*, but still keep session support through some standardized hidden form field value on every page (e.g. which would get parsed transparently on every request)?

P.S. I'm not looking for a URL based /(sessionid)/ solution. As stated above, this should preferably be via hidden form field.

From stackoverflow
  • A hidden form field would only work if every navigation element on your site is a button which submits the form. This would (among other things) make the back button and refresh awkward and make your site un-spiderable to search engines.

    Dykam : Or ajax based page retrieval.
    Rex M : @Dykam which is awful, and not what AJAX is for.

Jquery, Ajax form and redirection

Ok,

I need to use ajax for some fancy pop-ups and validation things but I want to avoid javascript redirect if everything is ok in form.

Here is the basic-simple scenario.

We have dynamic site and some user login form. Al logic (does user exist, is password ok etc) is on a server side.

Server pseudo code look like this:

$username,$password; //form user input

if (authenicate($user,$password)){
   redirect('myaccount');
}
else {
   print 'Wrong username and/or password'; //this should be displayed in the popup.
}

Now if I use ajax to display what server printed, how to tell to frontend to leave redirections to server side!?

I solved this on stupid way (because I have about 15 different forms). And I use javascript redirect if answer form server is for example "LOGGED".

Just to mention that I use jQuery and this plugin http://malsup.com/jquery/form/. Some sample code is here: http://pastie.org/584993

I believe that u will understand what I need and I appriciate all suggestions and answers :) Thanks!

From stackoverflow
  • Send back JSON to the client. Have a Status parameter, a Message parameter, and a Url parameter. On success set Status to true, and the Url to the page to which to direct. On error, set status to False and the Message to the error message. On the client side, use the Status to determine whether to redirect or popup the message

     $.ajax({
         url: '/login.php',
         dataType: 'json',
         data: $('form').serialize(),
         type: 'post',
         success: function(data) {
             if (data.Status) {
                location.href = data.Url;
             }
             else {
                alert( data.Message );
             }
         }
     });
    

Checking for directory and file write permissions in .NET

In my .NET 2.0 application, I need to check if sufficient permissions exist to create and write to files to a directory. To this end I have the following function that attempts to create a file and write a single byte to it, deleting itself afterwards to test that permissions do exist.

I figured the best way to check was to actually try and do it, catching any exceptions that occur, but I'm not particularly happy about the general Exception catch, so is there a better, or perhaps a more accepted way of doing this?

Any comments or suggestions welcome.

Thanks.

private const string TEMP_FILE = "\\tempFile.tmp";

/// <summary>
/// Checks the ability to create and write to a file in the supplied directory.
/// </summary>
/// <param name="directory">String representing the directory path to check.</param>
/// <returns>True if successful; otherwise false.</returns>
private static bool CheckDirectoryAccess(string directory)
{
    bool success = false;
    string fullPath = directory + TEMP_FILE;

    if (Directory.Exists(directory))
    {
        try
        {
            // Attempt to create a temporary file.
            using (FileStream fs = new FileStream(fullPath, FileMode.CreateNew, FileAccess.Write))
            {
                fs.WriteByte(0xff);
            }

            // Delete temporary file if it was successfully created.
            if (File.Exists(fullPath))
            {
                File.Delete(fullPath);
                success = true;
            }
        }
        catch (Exception)
        {
            success = false;
        }
    }
From stackoverflow
  • Directory.GetAcessControl(path) does what you are asking for.

    public static bool HasWritePermissionOnDir(string path)
    {
        var writeAllow = false;
        var writeDeny = false;
        var accessControlList = Directory.GetAccessControl(path);
        var accessRules = accessControlList.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
    
        foreach (FileSystemAccessRule rule in accessRules)
        {
            if ((FileSystemRights.Write & rule.FileSystemRights) != FileSystemRights.Write) continue;
    
            if (rule.AccessControlType == AccessControlType.Allow)
                writeAllow = true;
            else if (rule.AccessControlType == AccessControlType.Deny)
                writeDeny = true;
        }
    
        return writeAllow && !writeDeny;
    }
    

    (FileSystemRights.Write & rights) == FileSystemRights.Write is using something called "Flags" btw which if you don't know what it is you should really read up on :)

    blowdart : That will, of course, throw an exception if you can't actually get the ACL on the directory.
    aloneguid : What does it check for? That directory has Write permissions, but for which user? :)
  • Hi there.

    Try working with this C# snippet I just crafted:

    using System;
    using System.IO;
    using System.Security.AccessControl;
    using System.Security.Principal;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string directory = @"C:\downloads";
    
                DirectoryInfo di = new DirectoryInfo(directory);
    
                DirectorySecurity ds = di.GetAccessControl();
    
                foreach (AccessRule rule in ds.GetAccessRules(true, true, typeof(NTAccount)))
                {
                    Console.WriteLine("Identity = {0}; Access = {1}", rule.IdentityReference.Value, rule.AccessControlType);
                }
            }
        }
    }
    

    And here's a reference you could also look at. My code might give you an idea as to how you could check for permissions before attempting to write to a directory.

    Cheers. Jas.

  • IMO, you need to work with such directories as usual, but instead of checking permissions before use, provide the correct way to handle UnauthorizedAccessException and react accordingly. This method is easier and much more error prone.

  • The answers by Richard and Jason are sort of in the right direction. However what you should be doing is computing the effective permissions for the user identity running your code. None of the examples above correctly account for group membership for example.

    I'm pretty sure Keith Brown had some code to do this in his wiki version (offline at this time) of The .NET Developers Guide to Windows Security. This is also discussed in reasonable detail in his Programming Windows Security book.

    Computing effective permissions is not for the faint hearted and your code to attempt creating a file and catching the security exception thrown is probably the path of least resistance.

    KeeperOfTheSoul : It is also the only reliable method as otherwise someone could change the permission between checking and actually trying save (unlikely, but possible).
    Andy : Thanks for this. So the only change I should do to my code is to catch a security exception instead of the general 'Exception'?
    Kev : @Andy - yes, it's the path of least resistance unless you want to write the code to compute effective permissions.

Asp.net client side cryptography

Hello!

How can I sign data with standard .net crypto providers on client side?

From stackoverflow
  • If it's on the client side it probably won't be ASP.NET, you'll be using JavaScript (unless you maybe do it in Silverlight).

    So that's your answer; use Silverlight if you wish to use ASP.NET, or use JavaScript otherwise.

    asmois : Thanks for answer. I cann't use Silverlight. Can I reach .net cryptography classes in javascript?
    Noon Silk : Not without Silverlight no. I mean, unless you distribute some local executable.
    asmois : Thanks! I have no questions.

jquery - go to next table row based on class name from current row location?

I can get the current row using this code. The "this" is a link in a table cell in the row.

$currentTR = $(this).parents('tr');

These next two lines can do the same thing, get the tr after the current row.

$nextTR = $(this).parents('tr').next();  
$nextTR = $(this).parents('tr').next('tr');

If I output $nextTR.html() I see what I expect

I don't know how many rows I need to go to get to the correct row except by class name and doing it like this doesn't work for me.

$nextTR = $(this).parents('tr').next('.concept');  
$nextTR = $(this).parents('tr').next('tr .concept');

All I get is null

The example on docs.Jquery link text uses this

$("p").next(".selected").css("background", "yellow");

What am I missing here?

From stackoverflow
  • You want to get the next one that is of a certain class?

    You could try doing .next() and then checking the class perhaps?

    I'm slightly confused about your question, i'll admit, because you seem to have provided your own answer ...

  • Give nextAll a shot.

    hobbs : Crap, I was going to come up with a fancy solution using the new `index` function, but `$(this).closest('tr').nextAll('tr.concept').eq(0) seems like a winner`. :)
    Breadtruck : So this makes sense. Does nextAll go to the bottom of the page from current position and then start back at the top of the dom and come back to the start position, and that is how many elements get returned?
    Andy Gaskell : @Breadtruck - no. In your example nextAll returns all rows after the "current" row.
  • I've tried to recreate your html + javascript at jsbin and I can reproduce the problem:

    siblings() returns all 4 rows, and I can see that two of the rows have class="concept", but next('.concept') does not return anything.

    screenshot from firebug: siblings works ok, next doesnt

    Isn't next() supposed to be a subset of siblings() ?


    thanks for the comment, now I get it! I need silbings, not next.

    silbing and filter

    Andy Gaskell : next only returns the next element. If the selector you send into your call to next doesn't match the next element your result set will be empty.