Sudoku-Generator

Does anybody know PL/SQL-code for generating Sudoku-puzzles?
Cheers,
Nuerni

Thanks for above links. But all seem to be solvers not generators - it's obvious that making sudoku puzzles is more complex than solving.
Another starting point would be migration from other code to PL/SQL...?! Any further ideas?

Similar Messages

  • Sudoku generator problems(Stack overflow)

    I've been having some troubles trying to implement a program that generates sudoku problems. It takes a complete puzzle and pulls out the first number and tries to solve it with any of the 8 other numbers and if it can't then that means removing that variable completely will still keep the uniqueness of the solution. Problem is, I'm getting some stack overflow errors while implementing this and I have no idea why. My code is as follows, where the method solve is a program I've already written that can solve any sudoku problem.
    public int[][] generate(int [][] board) throws java.io.IOException {
              int oldValue;
              int[][] tempBoard = new int[9][9];
              for (int x = 0; x < 9; x++) {
                   for (int y = 0; y < 9; y++) {
                        tempBoard[x][y] = board[x][y];
              for (int x = 0; x < 9; x++) {
                   for (int y = 0; y < 9; y++) {
                        oldValue = board[x][y];
                        for (int z = 1; z <= 9; z++) {
                             if (z != oldValue) {
                                  board[x][y] = z;
                                  tempBoard = solve(tempBoard);
                                  if (tempBoard != null) {
                                       board[x][y] = oldValue;
                                       break;
                                  else {
                                       tempBoard = new int[9][9];
                                       for (int a = 0; a < 9; a++) {
                                            for (int b = 0; b < 9; b++) {
                                                 tempBoard[a] = board[a][b];
                        board[x][y] = 0;
                        for (int c = 0; c < 9; c++) {
                             for (int d = 0; d < 9; d++) {
                                  tempBoard[c][d] = board[c][d];
              return board;

    I was in the middle of editing that when you posted that, sorry
    public int[][] generate(int [][] board) throws java.io.IOException {
              int oldValue;
              int[][] tempBoard = new int[9][9];
              for (int x = 0; x < 9; x++) {
                   for (int y = 0; y < 9; y++) {
                        tempBoard[x][y] = board[x][y];
              for (int x = 0; x < 9; x++) {
                   for (int y = 0; y < 9; y++) {
                        oldValue = board[x][y];
                        for (int z = 1; z <= 9; z++) {
                             if (z != oldValue) {
                                  board[x][y] = z;
                                  tempBoard = solve(tempBoard);
                                  if (tempBoard != null) {
                                       board[x][y] = oldValue;
                                       break;
                                  else {
                                       tempBoard = new int[9][9];
                                       for (int a = 0; a < 9; a++) {
                                            for (int b = 0; b < 9; b++) {
                                                 tempBoard[a] = board[a][b];
                        board[x][y] = 0;
                        for (int c = 0; c < 9; c++) {
                             for (int d = 0; d < 9; d++) {
                                  tempBoard[c][d] = board[c][d];
              return board;
    Edited by: rhett77 on Oct 19, 2007 10:23 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Sudoku Algorithm

    Hi, i was venturing out to design an algorithm to generate sudoku puzzles, I was thinking of emplying 2D Matrix arrays. The idea I have is filling up the whole grid first with a solution then taking away a few numbers. I don't really know how to do this, though I have an idea, getting it to check the rows and columns add up to 45 and each 3x3 grid adds up to 45, 45 being the sum of all the numbers in a 3x3 grid. Would anyone be able to tell me if this would work and how would I be able to program this in JAVA. Many thanks in advance.

    And I need an algorithm to solve sudokupuzzles.
    That's the hard part, at least if you want to solve
    it without brute force.Indeed, I thought that only with brute force Sudoku can be solved.
    Indeed, I don�t think that there is a "magic intelligent" algorithm that can solve it . Well, Sudoku is cool exactly because it can just be solved by brute force. LOL!!!!
    Maybe some math genius person knows how to write an algorithm to solve Sudoku easily, or how to explain and prove mathematically that an algorithm to solve that is not possible.

  • Sudoku GUI

    Hey am trying to create a GUI for my Sudoku board.
    Here is how it currently looks: (See code below)
    There are two things I wanna change
    1. How do I center align the number so they are not stuck to the right edge as they are now?
    2. How do I add a bolder line around blocks/boxes(e.g. the 3*3 sections). Im sure these are pretty easy but havent been able to figure it out as of yet!
    Any help would be greatly appreciated.
    Code:
    package proj.sudoku.gui;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Cursor;
    import java.awt.Font;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.InputMethodEvent;
    import java.awt.event.InputMethodListener;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingConstants;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import proj.sudoku.representation.Board;
    import proj.sudoku.representation.Square;
    import proj.sudoku.ui.Sudoku;
    public class SudokuGUI extends JFrame implements ActionListener{
    private JTextField unfilledSquaresTextField;
    private JTextArea messagesTextArea;
    private JTable boardTable;
    private Board board;
    private Sudoku sudoku = new Sudoku();
    private int noOfUnfilledSquares = 20;
    private static final long serialVersionUID = 1L;
    class BoardTableTableModel extends AbstractTableModel {
    public final String[] COLUMN_NAMES = { "Row 0", "Row 1", "Row 2", "Row 3", "Row 4", "Row 5", "Row 6", "Row 7", "Row 8"};
    public int getRowCount() {
    return 9;
    public int getColumnCount() {
    return COLUMN_NAMES.length;
    public String getColumnName(int columnIndex) {
    return COLUMN_NAMES[columnIndex];
    public Object getValueAt(int rowIndex, int columnIndex) {
    int squareValue = board.getSquare(rowIndex, columnIndex).getSquareValue();
    if(squareValue == 0){
    return null;
    }else{
    return new Integer(squareValue);
    public boolean isCellEditable(int row, int col){
    return true;
    public void setValueAt(Object value, int row, int col) {
    int intValue = ((Integer)value).intValue();
    if((intValue >= 0) && (intValue < 10)){
    Square square = board.getSquare(row, col);
    square.setSquareValue(((Integer)value).intValue());
    board.setSquare(square, row, col);
    fireTableCellUpdated(row, col);
    public Class getColumnClass(int c) {
    return Integer.class;
    * Create the frame
    public SudokuGUI(Board newBoard) {
    super();
    getContentPane().setBackground(new Color(128, 128, 255));
    board = newBoard;
    getContentPane().setLayout(new GridBagLayout());
    setTitle("Sudoku Sudokme");
    setBounds(100, 100, 607, 456);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JPanel tablePanel = new JPanel();
    tablePanel.setLayout(new GridBagLayout());
    final GridBagConstraints gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.weighty = 0.5;
    gridBagConstraints.weightx = 1;
    getContentPane().add(tablePanel, gridBagConstraints);
    boardTable = new JTable();
    boardTable.setRowHeight(40); // TODO This line has been changed
    boardTable.setFont(new Font("", Font.PLAIN, 20));// TODO This line has been changed
    boardTable.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
    boardTable.setRowSelectionAllowed(false);
    boardTable.setShowGrid(true);
    boardTable.setModel(new BoardTableTableModel());
    final GridBagConstraints gridBagConstraints_2 = new GridBagConstraints();
    gridBagConstraints_2.gridx = 0;
    gridBagConstraints_2.gridy = 0;
    gridBagConstraints_2.insets = new Insets(0, -265, 0, 0);// TODO This line has been changed
    //gridBagConstraints_2.insets = new Insets(5, -265, 5, 0);
    tablePanel.add(boardTable, gridBagConstraints_2);
    final JPanel messagesPanel = new JPanel();
    messagesPanel.setLayout(new GridBagLayout());
    final GridBagConstraints gridBagConstraints_6 = new GridBagConstraints();
    gridBagConstraints_6.weighty = 0.3;
    gridBagConstraints_6.weightx = 1.0;
    gridBagConstraints_6.gridy = 1;
    gridBagConstraints_6.gridx = 0;
    getContentPane().add(messagesPanel, gridBagConstraints_6);
    messagesTextArea = new JTextArea();
    messagesTextArea.setAlignmentY(Component.BOTTOM_ALIGNMENT);
    messagesPanel.add(messagesTextArea, new GridBagConstraints());
    messagesTextArea.setText(board.getMessage());
    messagesTextArea.setEditable(false);
    final JPanel generateButtonPanel = new JPanel();
    generateButtonPanel.setLayout(new GridBagLayout());
    final GridBagConstraints gridBagConstraints_3 = new GridBagConstraints();
    gridBagConstraints_3.gridy = 2;
    gridBagConstraints_3.gridx = 0;
    getContentPane().add(generateButtonPanel, gridBagConstraints_3);
    final JButton generateEmptyBoardButton = new JButton();
    generateEmptyBoardButton.addActionListener(this);
    generateEmptyBoardButton.setText("Generate Empty Board");
    final GridBagConstraints gridBagConstraints_9 = new GridBagConstraints();
    gridBagConstraints_9.gridy = 0;
    gridBagConstraints_9.gridx = 0;
    generateButtonPanel.add(generateEmptyBoardButton, gridBagConstraints_9);
    final JButton generateBoardButton = new JButton();
    generateBoardButton.addActionListener(this);
    generateBoardButton.setText("Generate Board");
    final GridBagConstraints gridBagConstraints_10 = new GridBagConstraints();
    gridBagConstraints_10.gridx = 2;
    generateButtonPanel.add(generateBoardButton, gridBagConstraints_10);
    final JLabel unfilledSquaresLabel = new JLabel();
    unfilledSquaresLabel.setText("Unfilled Squares");
    final GridBagConstraints gridBagConstraints_11 = new GridBagConstraints();
    gridBagConstraints_11.gridy = 0;
    gridBagConstraints_11.gridx = 3;
    generateButtonPanel.add(unfilledSquaresLabel, gridBagConstraints_11);
    unfilledSquaresTextField = new JTextField();
    unfilledSquaresTextField.setFont(new Font("", Font.BOLD, 14));
    unfilledSquaresTextField.addActionListener(this);
    unfilledSquaresTextField.setText(new Integer(noOfUnfilledSquares).toString());
    unfilledSquaresTextField.setBackground(Color.WHITE);
    final GridBagConstraints gridBagConstraints_12 = new GridBagConstraints();
    gridBagConstraints_12.gridy = 0;
    gridBagConstraints_12.gridx = 4;
    unfilledSquaresLabel.setLabelFor(unfilledSquaresTextField);
    generateButtonPanel.add(unfilledSquaresTextField, gridBagConstraints_12);
    final JPanel solveButtonsPanel = new JPanel();
    solveButtonsPanel.setRequestFocusEnabled(false);
    solveButtonsPanel.setLayout(new GridBagLayout());
    final GridBagConstraints gridBagConstraints_1 = new GridBagConstraints();
    gridBagConstraints_1.weighty = 0.1;
    gridBagConstraints_1.weightx = 1;
    gridBagConstraints_1.gridy = 3;
    gridBagConstraints_1.gridx = 0;
    getContentPane().add(solveButtonsPanel, gridBagConstraints_1);
    final JButton heuristicsSolveButton = new JButton();
    heuristicsSolveButton.addActionListener(this);
    heuristicsSolveButton.setText("Heuristics Solve");
    final GridBagConstraints gridBagConstraints_4 = new GridBagConstraints();
    gridBagConstraints_4.gridx = 0;
    solveButtonsPanel.add(heuristicsSolveButton, gridBagConstraints_4);
    final JButton bruteForceSolveButton = new JButton();
    bruteForceSolveButton.addActionListener(this);
    bruteForceSolveButton.setText("Brute Force Solve");
    final GridBagConstraints gridBagConstraints_7 = new GridBagConstraints();
    gridBagConstraints_7.gridx = 1;
    solveButtonsPanel.add(bruteForceSolveButton, gridBagConstraints_7);
    final JButton hybridSolveButton = new JButton();
    hybridSolveButton.addActionListener(this);
    hybridSolveButton.setText("Hybrid Solve");
    final GridBagConstraints gridBagConstraints_8 = new GridBagConstraints();
    gridBagConstraints_8.gridx = 2;
    solveButtonsPanel.add(hybridSolveButton, gridBagConstraints_8);
    final JPanel testButtonsPanel = new JPanel();
    testButtonsPanel.setLayout(new GridBagLayout());
    final GridBagConstraints gridBagConstraints_5 = new GridBagConstraints();
    gridBagConstraints_5.weighty = 0.1;
    gridBagConstraints_5.weightx = 1.0;
    gridBagConstraints_5.gridy = 4;
    gridBagConstraints_5.gridx = 0;
    getContentPane().add(testButtonsPanel, gridBagConstraints_5);
    final JButton checkIfValidButton = new JButton();
    checkIfValidButton.addActionListener(this);
    checkIfValidButton.setText("Check If Valid");
    testButtonsPanel.add(checkIfValidButton, new GridBagConstraints());
    final JButton checkIfLegalButton = new JButton();
    checkIfLegalButton.addActionListener(this);
    checkIfLegalButton.setText("Check If Legal");
    testButtonsPanel.add(checkIfLegalButton, new GridBagConstraints());
    public static void main(String args[]) {
    try {
    SudokuGUI frame = new SudokuGUI(new Board());
    frame.setVisible(true);
    //frame.pack();
    } catch (Exception e) {
    e.printStackTrace();
    public void actionPerformed(ActionEvent arg0) {
    if(arg0.getSource().getClass().getName().equals("javax.swing.JTextField")){
    noOfUnfilledSquares = new Integer(((JTextField)arg0.getSource()).getText()).intValue();
    this.repaint();
    }else{
    try{
    board = sudoku.processGUICommands(board, arg0.getActionCommand(), noOfUnfilledSquares);
    messagesTextArea.setText(board.getMessage());
    this.repaint();
    }catch(Exception e){
    e.printStackTrace();
    }

    1) Use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags when posting code so the code is readable
    2) The code you posted isn't compileable or executable so we see exactly what you layout looks like
    3) If you have a Grid type layout, then I would think a GridLayout would be more appropriate to use then the GridBagLayout. Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]How to Use Layout Managers for more information.
    How do I add a bolder line around blocks/boxes[url http://java.sun.com/docs/books/tutorial/uiswing/misc/border.htmlHow to Use Borders[/url]
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.

  • Cool n free sudoku - Sudokool

    hi friends
    I have developed a game in java which is based on the popular sudoku puzzles.
    U can get the game at
    http://www.koolpages.com/shiraz/Sudokool.zip
    Now the problem is that the game runs only in windows.
    The main game file is an executable jar file.So double click on the file opens the game.
    But in linux the jar files gets opened and shows the archived class files.
    So plz help me ,how can i make the game run in linux ?
    I cannot use applet bcoz the game interacts with the local files for saving records.
    Moreover the java files are not compiling in linux.
    I have recently installed FC4.When i try to compile java files on terminal,it gives the following warning (where i use inheritance)
    eg.
    class now extends JFrame
    $javac now.java
    Warning: The serializable class now does not declare a static final serialVersionUID field of type long
    However the same file works perfectly well when run on Windows.The JVM on FC4 is 1.4.2 and even though i have installed the latest version of gcc(4.0.1)the problem still persists
    Plz help me...

    Have you thought about generating solutions?During my extensive mind travelling in the future I've noted that Sudoku has replaced the Eight Queen problem as next year's favourite homework assignment. This forum was completely flooded with queries from desperate newbies and only a heroic round-the-clock effort from all regulars could hold the reputation up of this forum as the number one homework cheating place. Thank you all for your future effort.

  • My sudoku program, any comments, improvements appreciated

    Hi all,
    So I've been refining my amateur-ish programming skills for around a month, and have been writing a C++ program that solves sudoku. (My background is in physics.) I realize there are a lot of mathematical sides in sudoku, but I'm concentrating on the programming side and not too much on the math/brain side. Now the program is basically finished (I hope!) and I just thought the hackers here can have a look and see if there are any things I can improve.
    The link is here: http://ifile.it/jkr56v8/Sudoku.tar
    Basically, a sudoku is an instance of Board, an abstract base class with the pure abstract function Go(). Any concrete class derived from it is essentially a strategy. I think this design pattern is called strategy?
    I've implemented two basic strategies, BruteForce and Priority. BruteForce does the good old sudoku brute force algorithm, which use trial-and-error from the top left box to the bottom right box all possibilitiies until the correct one is found. Priority does basically the same as BruteForce, except instead of trying from top left to bottom right, it plugs numbers in the box that has the most filled "associated" boxes.
    To accommodate "composite strategies," I implemented the prototype pattern, so for example, I can write
    void HyperBF::Go(void)
    BruteForce::Go();
    When a solution is found, I throw an exception to notify the main program, am I correct in that this is a clear and elegant use? Or is it a misuse and an alternative should be considered?
    To actually choose a strategy, I created an abstract factory, a singleton. I'm aware there are all the advice out there that says don't use a singleton unless absolutely necessary? So, should I use a singleton in this case? Also, I think my implementation of the singleton leads to a bug, which is the only known bug: when I put a completed sudoku as input, it gives the output as usual, but gives a segmentation fault afterwards:
    ./Sudoku Puzzle/test_1_Basic.psv BruteForce | tail -n 12 | head -n9 | tee completed
    |5|1|8|2|9|6|7|3|4|
    |3|9|7|8|4|1|2|6|5|
    |6|4|2|5|7|3|1|9|8|
    |1|5|6|4|2|7|3|8|9|
    |4|7|9|3|6|8|5|1|2|
    |8|2|3|9|1|5|6|4|7|
    |7|8|4|1|3|2|9|5|6|
    |2|3|5|6|8|9|4|7|1|
    |9|6|1|7|5|4|8|2|3|
    ./Sudoku completed BruteForce
    Starting configuration:
    |5|1|8|2|9|6|7|3|4|
    |3|9|7|8|4|1|2|6|5|
    |6|4|2|5|7|3|1|9|8|
    |1|5|6|4|2|7|3|8|9|
    |4|7|9|3|6|8|5|1|2|
    |8|2|3|9|1|5|6|4|7|
    |7|8|4|1|3|2|9|5|6|
    |2|3|5|6|8|9|4|7|1|
    |9|6|1|7|5|4|8|2|3|
    Final configuration:
    |5|1|8|2|9|6|7|3|4|
    |3|9|7|8|4|1|2|6|5|
    |6|4|2|5|7|3|1|9|8|
    |1|5|6|4|2|7|3|8|9|
    |4|7|9|3|6|8|5|1|2|
    |8|2|3|9|1|5|6|4|7|
    |7|8|4|1|3|2|9|5|6|
    |2|3|5|6|8|9|4|7|1|
    |9|6|1|7|5|4|8|2|3|
    Number of attempts: 0.
    Time elapsed: 0.00 s.
    Segmentation fault
    So what's wrong here?
    Having implemented the basic functionalities, I tried to play around and gain some simple experience in some optimization. I looked at the Go() function and saw probably the expensive operation is IsConsistent(), so I optimized it by only checking the consistency of changed boxes. By doing so, I reduced the computational time to around 1/3 the original time. Is this the right move, or bad move, or are there better moves?
    As a last question, I defined the number of attempts as a global variable. My reason is that, although it is possible to put it in class Board, I just think it doesn't "naturally belong" there, and putting it in a restricted scope would mean a lot of passing of parameters, slowing the program down unnecessarily. So, is this global variable fine?
    Lastly, please have a look at my Makefile. This is the first Makefile I wrote, and it took me 3 solid days to get all the .o files in Release/ ! Are there things I've left out?
    I realize the Generator is a joke, but at this moment I don't care too much about that, unless anyone has some good ideas.
    Any comments would be greatly appreciated! Thanks in advance!

    Grazz256 wrote:
    Just looking over your code a little I have a couple of comments about your coding style. Please keep in mind that these are just comments...
    I think you need to comment your code more. I know its a pain and I'm horrible about it as well but it really does help when/if you go back to read your code in a couple of years.
    I try to avoid lines like these:
      fprintf( stdout, "Starting configuration:\n" ); a->Write(stdout);
      start = clock(); a->Go();
    by putting two commands on one line it makes the code harder to read. with one command on each line I can quickly scan through and know
    generally what each line does, with two I have to actually read each line fully so that I don't miss anything.
    Descriptive variable names can also help with readability, I've always been taught the convention of using the first character to indicate type then
    using a short descriptive name. For instance you have a function that returns a long value, the value would be decalred like this:
    long lRetVal;
    so looking through the code I would know thats a long value that represents a return value.
    This is an area I'm all over the place with, I always try to stick to one convention but never seem manage it...
    As far as your problem goes, where are the boards normally deleted? ie if an incomplete sudoku is inputed?
    One possible solution is to run an IsComplete check before you start processing the board. so you would have...
    if (a->IsConsistent()) {
    if (a->IsComplete()) {
    a->Go()
    I'll be honest in that I don't really understand the flow of your code, but instead of having the board deleted within strategy or within win why not just delete it on the next line... eg:
    start = clock(); a->Go();
    delete a;
    the downside to this approach is that you would have to delete it within each exception as well but this is relatively minor.
    Cheers
    Thanks for your comments. At my present level of programming skills, any comments will help.
    I thought all my code was basically concise and self-explanatory, and each function is small enough that a quick skim through the definition and declaration would be enough to understand. As the project grew, however, things got slightly more complicated. I have added more comments in my source files, trying to comment why rather than how. I thought the flow of the code was fairly obvious though, by inspecting the main loop. It takes care of the input, bark if anything's wrong, trigger a.Go(), and try to catch a Win. Do you mean the flow within Go()? Anyway, it is very true I need clearer coding style.
    Yeah I now solved the segfault problem. The reason a completed sudoku was deleted twice is because the original sudoku is meant to be deleted by the abstract factory, while the solved sudoku is meant to be deleted by Win. When a solved sudoku is inputted it would be deleted twice. Due to lack of programming experience, I failed to see the obvious way is to, as Grazz256 said, check in the beginning whether the inputted sudoku is already solved. If it is, then I duplicate the inputted sudoku and throw the win exception.
    By the way, I think I'm beginning to understand why some people are obsessed wtih optimization. I did 3 optimization techniques in my program. First, I thought the most expensive procedure is the IsConsistent() method. By evaluating it lazily I reduced the time to 1/3 the original time. Then following http://www.acm.org/crossroads/xrds1-4/ovp.html, I used initialized the 2D vector within each sudoku via constructor rather than as statements. Doing so gave a 20% time boost. Using a friend procedure while copying sudokus boost another 5%. Doing a right move and getting positive feedback through better performance can be so satisfying.
    EDIT:
    I found out there was memory leak after all, which I finally solved.
    What happens is with all my brute force algorithms I keep creating new Board's and call the Board's Go() recursively. To delete all Board's in the heap I need to have, within each Board::Go(), instead of
    Board* a = Clone(); // return new derived Board(*this);
    a->Put(x,y,'0'+k);
    a->Go();
    delete a; // if an exception is thrown this line never gets executed
    this
    Board* a = Clone();
    a->Put(x,y,'0'+k);
    try {a->Go(); }
    catch( const Win& e) {
    delete a;
    throw(e);
    delete a;
    But this deletes the winning sudoku too. This means I have to keep the result in Win, either by duplicating the winning sudoku or storing the string. In the end I overloaded Board::Write(File* f) to also have Board::Write(std::string& p) to sprintf on the reference of a string, so Win just stores the solution in string format. Finally, no memory leak, no need to do a first check to see if the inputted sudoku is already solved, and no pointer deleted twice.
    So in the end, to manage pointers I recursively threw exceptions. That made me ask, is using exceptions worth it, or should I stick to the more conventional methods, such as have Go() return a boolean value, then deleting pointers which would give an implementation that is essentially the same as recursive exceptions?
    I still think exceptions is the way to go, the reasons being:
    1) Exception mechanism provide a natural place to hold the result. Throwing exceptions recursively and the traditional way is essentially the same, but where should the result be stored in the latter case?
    2) Arguing over the dictionary, an exception is not necessarily an "error." Winning is an exception in this algorithm, because failure is the norm (as in life).
    3) Exception arguably gives better presentation in the main loop, to my "unbiased" eyes at least. Board* a->Go() is triggered in the try block in the main(), with all (foreseeable) possible results caught as exceptions. It is true that this might be a bit unconventional, but given proper comments I still think it is at least as good as the conventional way, in terms of presentation.
    So what do you think?
    Last edited by dumas (2009-12-21 12:37:47)

  • Using SQVI to generate report of open and released delivery schedule lines

    All,
    I'm using SQVI  to generate an excel spreadsheet for some buyers to show open released schedule lines because they are a 1 line item per scheduling agreement company.
    I used the logical database MEPOLDB instead of a table joint and pulled fields from EKKO(vendor, SA #,&purchasing group), EKPO(Material Number), EKEH(schedule line type), and EKET(delivery date, scheduled qty,previous qty).
    Does this sound like I'll get the results I want on paper as long as I use the right selection criteria, because the report I'm getting isn't quite what I expect? I am unable to identify which lines are authorized to ship vs. trade-off zone, planning, etc. in the report thus far.

    Hi Mark,
                 I have faced same requirement. I am not sure about transporting to TST and PROD. I done by this way.
    After generating SQVI program in DEV , I assigned that program  to a transaction and tested in DEV. Later i have regenarated SQVI in Production. then I assigned the generated Program to same transaction in DEV. And transported the Tcode assignment of program to Production..
    About authorization , if its not sensitive report, BASIS can restrict at transaction level.
    Regards,
    Ravi.

  • Error while generating a role

    Hi SAP Techies,
    I am getting the following error while generating a role,
    "18 field value(s) for object K_CCA were not entered in the profile"
    Can you please provide me a solution to fix this problem.
    Thanks.
    Regards,
    Agustuss

    How many cost centres are you putting in the role?  Do you have cost centre set as an org level?
    From your User Name I assume that you are at the BBC...Do you still use a program to populate the cost centres in the role based on the cost centre group names?  If so it is possible that you are trying to put too many cost centres in the field and the the profile will not generate because of this (we had it back in 2001 when I was working there).
    Do you have the technical error message details?

  • Credit memo generate in case of free goods

    Dear Friends
    one material price is rs450/- and with 5+1 when customer place order 5 pc that time system delivery 6 bec 1 is free. when customer return 1pc then what will be the credit memo pricing for each material.
    Thanking you
    Arun

    Dear Friends
    I am just clearly adding question with exact requirement.
    material per pc 450/- and scheme is 5+1
    order qty 5   Price is 450*5=2250
    dlv qty 6
    now client generate credit memo request for one pc in sap it is coming Rs450/- pc
    but client requrement is not this
                               2250/6=Rs. 375/- that mean they will give rs 375/- per pc not Rs 450/- per pc. for that what should i do customisation for credit memo request pricing.
    regards
    arun

  • PXI 6070E, Unable to capture waveform on ACH0 while generating a wavefrm on DAC0

    I'm trying to plot the sinewave being generated continuously (verified with a scope) by DAC0 that is wired to ACH0. All I get is noise. When I disconnect DAC0 (but leave it running) and connect an external function generator to ACH0, it plots just fine. Has anyone seen this problem?

    Hello,
    Have you tried changing the input mode? I'm not very sure what input mode you are using but I would recommend to use differential.
    For troubleshooting bad readings, it is always advisable to read the signals from MAX (Measurement and Automation Explorer) first, and then use other programs like LabView, LabWindows/CVI or Measurement Studio.
    If you want to use differential mode, here's how you would connect the signals: Connect DAC0 OUT to ACH0, and AOGND to ACH8.
    Finally, here's a link to an interesting Knowledge Base: Data Acquisition: Troubleshooting Offset, Incorrect, and Noisy Readings
    Good luc
    k with your application!

  • Generate prov.xml for Creative Cloud. Return Code 27

    We're trying to follow this guide (Creative Cloud Help | Using Adobe Provisioning Toolkit Enterprise Edition) to serialize a package (or something). We're stuck on generating prov.xml. My best attempt at an entry is:
    C:\Program Files (x86)\Common Files\Adobe\OOBE\PDApp\CCP\utilities\APTEE>adobe_prtk.exe --tool=VolumeSerialize --generate --serial=xxxx-xxxx-xxxx-xxxx-xxxx-xxxx --regsuppress=ss --eulasuppress --locales=en_US --provfilepath=C:\Program Fil
    es (x86)\Common Files\Adobe\OOBE\PDApp\CCP
    It says half of this is optional, but I'm skeptical.
    Anyway, I'm getting return code 27. This indicates that it is unable to edit the prov.xml file specified. I didn't specify a prov.xml file, I'm trying to make one. The syntax I'm using differs from what I found on the page I linked, as that was giving me syntax errors. I lifted this off someone else's code. I've tried just about every variation I can think of. Any help would be appreciated.
    This is on Windows

    One of these links may help
    http://helpx.adobe.com/creative-cloud/packager.html
    http://forums.adobe.com/community/download_install_setup/creative_suite_enterprise_deploym ent

  • Installation Problem on 11g, RHEL 5 - Unable to generate temporary script

    Hello all,
    This is for the first time i am encountering this kind of error on 11g. Half way through installation i get this error.
    All parameters set correct, used the official installation technique (works fine previously), except for this time i am getting a weird error, which does not allow me to continue with the installation.
    Please help.
    Environment
    Oracle 11g
    RHEL 5
    Error on GUI -
    OUI-10053: Unable to generate temporary script: {0}. Unable to continue install
    Error on command prompt -
    OUI-10053:Unable to generate temporary script: /u01/app/oraInventory/orainstRoot.sh. Unable to continue install.
    Help appreciated.
    Thanks

    Hi Monu Koshy
    Can you please control the user rights and also the df ?
    ls -al /u01/app/oraInventory/
    df -h /u01/app/oraInventory/
    Regards,
    Hub

  • Manage-bde command is not generating recovery key on network location

    Hi,
    I am trying to save the recovery key to the network share location and start up key in the USB drive while enabling bit locker.When the OS drive gets encrypted, the default folder for recovery password shows that it contains 1 file but not getting anything
    inside it when i checked the properties of the folder.
    i have already changed the group policy as "choose default folder for recovery password".
    I am using the command to enable the bit-locker as "manage-bde.exe -on C: -rk
    <network location to save recovery key> -sk <location of the USB drive>
    -rp to enable the bit-locker. It is generating the start up key in the USB but not the recovery key on network share.
    Can anyone suggest what i am missing or what else i should do to generate the recovery key on network share.
    Does manage-bde process be able to save the recovery key on network share or it hand over to some other process to perform this task.
    Thanks
    Gaurav Ranjan

    I got you Manoj, but I want to ask you one think that what if i lost the startup  key or my USB stick. I have my recovery key on the network share.  In order to log-in my machine I need the recovery password. From where i will get the recovery
    password(48 digit). Surely from the recovery key on the network share. So how can i get the recovery password if only we have the recovery key.
    I know both are different in context. Both are two different thing. I have lost my USB stick along with the recovery password and I have to log-in my machine. How can i do that i want to know that. Do there is any method to get recovery password from the
    recovery key on network share. I have retrieved the recovery password when the recovery key in AD. But this time it is on network share.
    Also one think which I need to solve is that the manage-bde -protectors -add command creates a new .bek file along with the older one. So the .bek file which get shown at the time of the start up of the machine is different from that stored in the network.
    So i am getting confused as which .bek file is for which machine and hard to retrieve the password.
    Is there any method to store recovery key on network without the -protectors -add command line so that both the .bek file should be matched and can easily be known for indiviual machine in an OU. As if both the .bek files will be different it would be difficult
    to to retrieve the recovery password for the machines.
    Please do inform if you need some more information about the scenario if i missed something.
    Thanks
    Gaurav Ranjan

  • Generate xml source file for Oracle Order Capture Print Quote

    Hi,
    I am new to xml and need to work on creating templates for Print Quote.
    I am trying to generate the xml source file for which I enabled the report in system administrator and set the output to XML and assigned to Quoting Reports responsiblity. I then assigned XML Report Publisher to the same responsiblity.
    I ran the report (Print Quote) and then I am trying to run the XML Report Publisher but I cannot get the request id in the list of values.
    I am able to generate xml source file for other reports like Printed Purchase Order etc.,
    The view output for the (Print Quote) report is as follows:
    <?xml version="1.0" ?>
    - <!-- Generated by Oracle Reports version 6.0.8.26.0
    -->
    <ASOPQTER />
    How do I get the xml source file? Or are there seeded templates that I can use to create more templates? Any help would be appreciated. Thanks Ravi

    Hi, I am in the same position - did this issue ever ger resolved by anyone. I have done a few XMLP reports successfully now using the Word add-in, but customising the Quote output differs from other standard reports.
    If you look at the data definition for Quote it is a 'dummy' definition and has no XML file attached. Does anyone know how I can get the XML format for the report output?
    Also the template uses XSL-FO ?!?!?! rather than RTF - not sure how to work with this, the Oracle docs are not very helpful in this regard either.
    Has anyone successfully managed to customise the Quote print report? Many thanks,
    Roger

  • Dynamic CRM 2013 Online how to execute Report, generate PDF and email

    Dear All,
    I am using Dynamic CRM 2013 online. For quote, I have workflow and Dialogue processes for review process. On approval, I want the system to generate a PDF of quote report, attach the PDF and email it to the Customer.
    Better I would like, When approver, clicks on the approve button, the system should auto generate a PDF of quote report, attach the PDF and email it to the Customer, without any further input from the user. If its not possible, I may have to put button on
    quote form.
    I am using the attached code, but facing various issues.
    1. Under prepare the SOAP Message coding part, I am not sure what should be the below URL for CRM 2013 Online?
    xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
    2. What should be the emailid here? Is it Recepient Contact id(Guid) ?
    var emailid = resultXml.selectSingleNode("//CreateResult").nodeTypedValue;
    alert("emailid" + emailid.toString());
    3. Using this code, not able to create Entity for "ActivityMimeAttachment", I am getting newEntity as undefined.
    Below is the code I am using. Please check and help me out, where I am going wrong. Let me know if any better way to implement it. At present, I have put one button on quote form, on click event, below code will get executed.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title></title>
    <script type="text/javascript">
    var Xrm;
    if (window.opener) { Xrm = window.opener.Xrm; }
    else if (window.parent) { Xrm = window.parent.Xrm; }
    function getReportingSession() {
    var reportName = "Quotation_Report"; //set this to the report you are trying to download
    var reportId = "7C39D18F-1DC6-E311-8986-D89D6765B238"; //set this to the guid of the report you are trying to download
    var recordid = Xrm.Page.data.entity.getId();
    // recordid = recordid.substring(1, 37); //getting rid of curly brackets
    alert(recordid);
    var pth = Xrm.Page.context.getServerUrl() + "/CRMReports/rsviewer/reportviewer.aspx";
    var retrieveEntityReq = new XMLHttpRequest();
    retrieveEntityReq.open("POST", pth, false);
    retrieveEntityReq.setRequestHeader("Accept", "*/*");
    retrieveEntityReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    retrieveEntityReq.send("id=%7B" + reportId + "%7D&uniquename=" + Xrm.Page.context.getOrgUniqueName() + "&iscustomreport=true&reportnameonsrs=&reportName=" + reportName + "&isScheduledReport=false");
    var x = retrieveEntityReq.responseText.indexOf("ReportSession=");
    var ret = new Array();
    ret[0] = retrieveEntityReq.responseText.substr(x + 14, retrieveEntityReq.responseText.indexOf("&", x) - x - 14); //the session id
    x = retrieveEntityReq.responseText.indexOf("ControlID=");
    ret[1] = retrieveEntityReq.responseText.substr(x + 10, retrieveEntityReq.responseText.indexOf("&", x) - x - 10); //the control id
    return ret;
    function createEntity(ent, entName, upd) {
    var jsonEntity = JSON.stringify(ent);
    var createEntityReq = new XMLHttpRequest();
    var ODataPath = Xrm.Page.context.getServerUrl() + "XRMServices/2011/OrganizationData.svc";
    createEntityReq.open("POST", ODataPath + "/" + entName + "Set" + upd, false);
    createEntityReq.setRequestHeader("Accept", "application/json");
    createEntityReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    createEntityReq.send(jsonEntity);
    var newEntity = JSON.parse(createEntityReq.responseText).d;
    alert("new entity" + newEntity);
    return newEntity;
    function createAttachment() {
    var params = getReportingSession();
    var recordid = Xrm.Page.data.entity.getId();
    alert("recordid " + recordid);
    var orgName = Xrm.Page.context.getOrgUniqueName();
    var userID = Xrm.Page.context.getUserId();
    //create email record
    // Prepare the SOAP message.
    var xml = "<?xml version='1.0' encoding='utf-8'?>" +"<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'" +
    " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +
    " xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
    "<soap:Header>" +
    "</soap:Header>" +
    "<soap:Body>" +
    "<Create xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
    "<entity xsi:type='email'>" +
    "<regardingobjectid type='quote'>" + recordid + "</regardingobjectid>" +
    "<subject>" + "Email with Attachment4" + "</subject>" +
    "</entity>" +
    "</Create>" +
    "</soap:Body>" +
    "</soap:Envelope>";
    // Prepare the xmlHttpObject and send the request.
    var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
    xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
    xHReq.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Create");
    xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xHReq.setRequestHeader("Content-Length", xml.length);
    xHReq.send(xml);
    // Capture the result
    var resultXml = xHReq.responseXML;
    // alert("resultXml " + resultXml);
    // Check for errors.
    var errorCount = resultXml.selectNodes('//error').length;
    if (errorCount != 0) {
    alert("ERROR");
    var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
    alert(msg);
    var emailid = resultXml.selectSingleNode("//CreateResult").nodeTypedValue;
    alert("emailid" + emailid.toString());
    //var emailid = userID;
    var post = Object();
    post.Body = encodePdf(params);
    var email = new Array();
    email[0] =new Object();
    email[0].id = emailid;
    email[0].entityType ='email';
    post.Subject ="File Attachment";
    post.AttachmentNumber = 1;
    post.FileName ="Report.pdf";
    post.MimeType ="application/pdf";
    post.ObjectId = Object();
    post.ObjectId.LogicalName ="email";
    post.ObjectId.Id = email[0].id;
    post.ObjectTypeCode ="email";
    alert(post.ObjectId.Id);
    createEntity(post,"ActivityMimeAttachment", "");
    alert("created successfully");
    email.Subject = "Your Order";
    //Set The current order as the Regarding object
    email.RegardingObjectId = {
    Id: Xrm.Page.data.entity.getId(), //Get the current entity Id , here OrderId
    LogicalName: Xrm.Page.data.entity.getEntityName()//Get the current entity name, here it will be “salesOrder”
    //Create Email Activity
    SDK.JScriptRESTDataOperations.Create(email, "Email", EmailCallBack, function (error) { alert(error.message); });
    // Email Call Back function
    function EmailCallBack(result) {
    email = result; // Set the email to result to use it later in email attachment for retrieving activity Id
    var activityPartyFrom = new Object();
    // Set the From party of the ActivityParty to relate an entity with Email From field
    activityPartyFrom.PartyId = {
    Id: customerId, // id of entity you want to associate this activity with.
    LogicalName: "contact"
    // Set the "activity" of the ActivityParty
    activityPartyFrom.ActivityId = {
    Id: result.ActivityId,
    LogicalName: "email"
    // Now set the participation type that describes the role of the party on the activity).
    activityPartyFrom.ParticipationTypeMask = { Value: 2 }; // 2 means ToRecipients
    // Create the from ActivityParty for the email
    SDK.JScriptRESTDataOperations.Create(activityPartyFrom, "ActivityParty", ActivityPartyFromCallBack, function (error) { alert(error.message); });
    var activityPartyTo = new Object();
    // Set the From party of the ActivityParty to relate an entity with Email From field
    activityPartyTo.PartyId = {
    Id: ownerId, // id of entity you want to associate this activity with.
    LogicalName: "systemuser"
    // Set the "activity" of the ActivityParty
    activityPartyTo.ActivityId = {
    Id: result.ActivityId,
    LogicalName: "email"
    // Now set the participation type that describes the role of the party on the activity). activityPartyTo.ParticipationTypeMask = { Value: 1 }; // 1 means Sender
    // Create the from ActivityParty
    SDK.JScriptRESTDataOperations.Create(activityPartyTo, "ActivityParty", ActivityPartyToCallBack, function (error) { alert(error.message); });
    //ActivityParty From Callback
    function ActivityPartyFromCallBack(result) {
    //ActivityParty To Callback
    function ActivityPartyToCallBack(result) {
    var StringMaker = function () {
    this.parts = [];
    this.length = 0;
    this.append = function (s) {
    this.parts.push(s);
    this.length += s.length;
    this.prepend = function (s) {
    this.parts.unshift(s);
    this.length += s.length;
    this.toString = function () {
    return this.parts.join('');
    var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    function encode64(input) {
    var output = new StringMaker();
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;
    while (i < input.length) {
    chr1 = input[i++];
    chr2 = input[i++];
    chr3 = input[i++];
    enc1 = chr1 >> 2;
    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
    enc4 = chr3 & 63;
    if (isNaN(chr2)) {
    enc3 = enc4 = 64;
    else if (isNaN(chr3)) {
    enc4 = 64;
    output.append(keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4));
    return output.toString();
    var bdy = new Array();
    var bdyLen = 0;
    function concat2Bdy(x) {
    bdy[bdyLen] = x;
    bdyLen++;
    function encodePdf(params) {
    bdy = new Array();
    bdyLen = 0;
    var retrieveEntityReq = new XMLHttpRequest();
    var pth = Xrm.Page.context.getServerUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + params[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + params[1] + "&OpType=Export&FileName=Public&ContentDisposition=OnlyHtmlInline&Format=PDF";
    retrieveEntityReq.open("GET", pth, false);
    retrieveEntityReq.setRequestHeader("Accept", "*/*");
    retrieveEntityReq.send();
    BinaryToArray(retrieveEntityReq.responseBody);
    return encode64(bdy);
    </SCRIPT>
    <SCRIPT type=text/vbscript>
    Function BinaryToArray(Binary)
    Dim i
    ReDim byteArray(LenB(Binary))
    For i = 1 To LenB(Binary)
    byteArray(i-1) = AscB(MidB(Binary, i, 1))
    concat2Bdy(AscB(MidB(Binary, i, 1)))
    Next
    BinaryToArray = byteArray
    End Function
    </SCRIPT>
    </head>
    <body>
    <input type="button" onclick="createAttachment();" value="Attach Report" />
    </body>
    </html>
    Thanks. and waiting for your valuable comments.
    - Mittal

    Hello,
    Yes, I was able to make my code working as below. Tested on CRM online 2013.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
    <script type="text/javascript">
    if (typeof (SDK) == "undefined")
    { SDK = { __namespace: true }; }
    SDK.JScriptRESTDataOperations = {
    _context: function () {
    if (typeof GetGlobalContext != "undefined")
    { return GetGlobalContext(); }
    else {
    if (typeof Xrm != "undefined") {
    return Xrm.Page.context;
    else { return new Error("Context is not available."); }
    _getServerUrl: function () {
    var serverUrl = this._context().getServerUrl()
    if (serverUrl.match(/\/$/)) {
    serverUrl = serverUrl.substring(0, serverUrl.length - 1);
    return serverUrl;
    _ODataPath: function () {
    return this._getServerUrl() + "/XRMServices/2011/OrganizationData.svc/";
    _errorHandler: function (req) {
    return new Error("Error : " +
    req.status + ": " +
    req.statusText + ": " +
    JSON.parse(req.responseText).error.message.value);
    _dateReviver: function (key, value) {
    var a;
    if (typeof value === 'string') {
    a = /Date\(([-+]?\d+)\)/.exec(value);
    if (a) {
    return new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
    return value;
    Create: function (object, type, successCallback, errorCallback) {
    var req = new XMLHttpRequest();
    req.open("POST", this._ODataPath() + type + "Set", true);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.onreadystatechange = function () {
    if (this.readyState == 4 /* complete */) {
    if (this.status == 201) {
    successCallback(JSON.parse(this.responseText, SDK.JScriptRESTDataOperations._dateReviver).d);
    else {
    errorCallback(SDK.JScriptRESTDataOperations._errorHandler(this));
    req.send(JSON.stringify(object));
    Retrieve: function (id, type, successCallback, errorCallback) {
    var req = new XMLHttpRequest();
    req.open("GET", this._ODataPath() + type + "Set(guid'" + id + "')", true);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.onreadystatechange = function () {
    if (this.readyState == 4 /* complete */) {
    if (this.status == 200) {
    successCallback(JSON.parse(this.responseText, SDK.JScriptRESTDataOperations._dateReviver).d);
    else {
    errorCallback(SDK.JScriptRESTDataOperations._errorHandler(this));
    req.send();
    Update: function (id, object, type, successCallback, errorCallback) {
    var req = new XMLHttpRequest();
    req.open("POST", this._ODataPath() + type + "Set(guid'" + id + "')", true);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("X-HTTP-Method", "MERGE");
    req.onreadystatechange = function () {
    if (this.readyState == 4 /* complete */) {
    if (this.status == 204 || this.status == 1223) {
    successCallback();
    else {
    errorCallback(SDK.JScriptRESTDataOperations._errorHandler(this));
    req.send(JSON.stringify(object));
    Delete: function (id, type, successCallback, errorCallback) {
    var req = new XMLHttpRequest();
    req.open("POST", this._ODataPath() + type + "Set(guid'" + id + "')", true);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("X-HTTP-Method", "DELETE");
    req.onreadystatechange = function () {
    if (this.readyState == 4 /* complete */) {
    if (this.status == 204 || this.status == 1223) {
    successCallback();
    else {
    errorCallback(SDK.JScriptRESTDataOperations._errorHandler(this));
    req.send();
    RetrieveMultiple: function (type, filter, successCallback, errorCallback) {
    if (filter != null) {
    filter = "?" + filter;
    else { filter = ""; }
    var req = new XMLHttpRequest();
    req.open("GET", this._ODataPath() + type + "Set" + filter, true);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.onreadystatechange = function () {
    if (this.readyState == 4 /* complete */) {
    if (this.status == 200) {
    successCallback(JSON.parse(this.responseText, SDK.JScriptRESTDataOperations._dateReviver).d.results);
    else {
    errorCallback(SDK.JScriptRESTDataOperations._errorHandler(this));
    req.send();
    __namespace: true
    </script>
    <script type="text/javascript">
    //Create Email and link it with Order as Regarding field
    var Xrm;
    var email = new Object();
    var ownerID = "";
    var CustomerId = "";
    if (window.opener) { Xrm = window.opener.Xrm; }
    else if (window.parent) { Xrm = window.parent.Xrm; }
    //Get ownerid who send email of quotation to customer
    function GetOwnerID() {
    var owner = Xrm.Page.getAttribute("ownerid").getValue();
    ownerID = owner[0].id;
    var ownerName = owner[0].name;
    var entityType = owner[0].entityType;
    GetToEmailGUID();
    //Get customerid who receive email of quotation from owner
    function GetToEmailGUID() {
    var Customer = Xrm.Page.getAttribute('customerid').getValue();
    CustomerId = Customer[0].id;
    var CustomerName = Customer[0].name;
    var entityType = Customer[0].entityType;
    //if CustomerId is type of "Account" then get Primary Contact id of that account
    if (entityType == "account") {
    var contact = Xrm.Page.getAttribute("customerid").getValue();
    if (contact === null) return;
    var serverUrl = Xrm.Page.context.getClientUrl();
    var oDataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc/AccountSet(guid'" + contact[0].id + "')?$select=PrimaryContactId";
    var req = new XMLHttpRequest();
    req.open("GET", oDataSelect, false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json;charset=utf-8");
    req.onreadystatechange = function () {
    if (req.readyState === 4) {
    if (req.status === 200) {
    var retrieved = JSON.parse(req.responseText).d;
    CustomerId = retrieved.PrimaryContactId.Id;
    else {
    alert(this.statusText);
    req.send();
    function CreateEmail() {
    GetOwnerID();
    email.Subject = "Email with Report Attachment";
    //Set The current order as the Regarding object
    email.RegardingObjectId = {
    Id: Xrm.Page.data.entity.getId(), //Get the current entity Id , here OrderId
    LogicalName: Xrm.Page.data.entity.getEntityName()//Get the current entity name, here it will be “salesOrder”
    //Create Email Activity
    SDK.JScriptRESTDataOperations.Create(email, "Email", EmailCallBack, function (error) { alert(error.message); });
    // Email Call Back function
    function EmailCallBack(result) {
    email = result; // Set the email to result to use it later in email attachment for retrieving activity Id
    var activityPartyFrom = new Object();
    // Set the From party of the ActivityParty to relate an entity with Email From field
    activityPartyFrom.PartyId = {
    Id: CustomerId, //"79EBDD26-FDBE-E311-8986-D89D6765B238", // id of entity you want to associate this activity with.
    LogicalName: "contact"
    // Set the "activity" of the ActivityParty
    activityPartyFrom.ActivityId = {
    Id: result.ActivityId,
    LogicalName: "email"
    // Now set the participation type that describes the role of the party on the activity).
    activityPartyFrom.ParticipationTypeMask = { Value: 2 }; // 2 means ToRecipients
    // Create the from ActivityParty for the email
    SDK.JScriptRESTDataOperations.Create(activityPartyFrom, "ActivityParty", ActivityPartyFromCallBack, function (error) { alert(error.message); });
    var activityPartyTo = new Object();
    // Set the From party of the ActivityParty to relate an entity with Email From field
    activityPartyTo.PartyId = {
    Id: ownerID, //"79EBDD26-FDBE-E311-8986-D89D6765B238", // id of entity you want to associate this activity with.
    LogicalName: "systemuser"
    // Set the "activity" of the ActivityParty
    activityPartyTo.ActivityId = {
    Id: result.ActivityId,
    LogicalName: "email"
    // Now set the participation type that describes the role of the party on the activity).
    activityPartyTo.ParticipationTypeMask = { Value: 1 }; // 1 means Sender
    // Create the from ActivityParty
    SDK.JScriptRESTDataOperations.Create(activityPartyTo, "ActivityParty", ActivityPartyToCallBack, function (error) { alert(error.message); });
    //ActivityParty From Callback
    function ActivityPartyFromCallBack(result) {
    //ActivityParty To Callback
    function ActivityPartyToCallBack(result) {
    GetReportId('Quotation');
    //Create attachment for the created email
    function CreateEmailAttachment() {
    //get reporting session and use the params to convert a report in PDF
    var params = getReportingSession();
    //Email attachment parameters
    var activitymimeattachment = Object();
    activitymimeattachment.ObjectId = Object();
    activitymimeattachment.ObjectId.LogicalName = "email";
    activitymimeattachment.ObjectId.Id = email.ActivityId;
    activitymimeattachment.ObjectTypeCode = "email",
    activitymimeattachment.Subject = "File Attachment";
    activitymimeattachment.Body = encodePdf(params);
    activitymimeattachment.FileName = "Report.pdf";
    activitymimeattachment.MimeType = "application/pdf";
    //Attachment call
    SDK.JScriptRESTDataOperations.Create(activitymimeattachment, "ActivityMimeAttachment", ActivityMimeAttachmentCallBack, function (error) { alert(error.message); });
    //ActivityMimeAttachment CallBack function
    function ActivityMimeAttachmentCallBack(result) {
    var features = "location=no,menubar=no,status=no,toolbar=no,resizable=yes";
    var width = "800px";
    var height = "600px";
    window.open(Xrm.Page.context.getServerUrl() + "main.aspx?etc=" + 4202 + "&pagetype=entityrecord&id=" + email.ActivityId, "_blank", features);
    // To open window which works in outlook and IE both
    //openStdWin(Xrm.Page.context.getServerUrl() + "main.aspx?etc=" + 4202 + "&pagetype=entityrecord&id=" + email.ActivityId, "_blank", width, height, features);
    //This method will get the reportId based on a report name that will be used in getReportingSession() function
    function GetReportId(reportName) {
    var oDataSetName = "ReportSet";
    var columns = "ReportId";
    var filter = "Name eq '" + reportName + "'";
    retrieveMultiple(oDataSetName, columns, filter, onSuccess);
    function retrieveMultiple(odataSetName, select, filter, successCallback) {
    var serverUrl = Xrm.Page.context.getServerUrl();
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    var odataUri = serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "?";
    if (select) {
    odataUri += "$select=" + select + "&";
    if (filter) {
    odataUri += "$filter=" + filter;
    $.ajax({
    type: "GET",
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    url: odataUri,
    beforeSend: function (XMLHttpRequest) {
    XMLHttpRequest.setRequestHeader("Accept", "application/json");
    success: function (data) {
    if (successCallback) {
    if (data && data.d && data.d.results) {
    successCallback(data.d.results);
    else if (data && data.d) {
    successCallback(data.d);
    else {
    successCallback(data);
    error: function (XmlHttpRequest, errorThrown) {
    if (XmlHttpRequest && XmlHttpRequest.responseText) {
    alert("Error while retrieval ; Error – " + XmlHttpRequest.responseText);
    function onSuccess(data) {
    reportId = data[0].ReportId.replace('{', ").replace('}', ");
    CreateEmailAttachment(); // Create Email Attachment
    //Gets the report contents
    function getReportingSession() {
    var pth = Xrm.Page.context.getServerUrl() + "/CRMReports/rsviewer/reportviewer.aspx";
    var retrieveEntityReq = new XMLHttpRequest();
    var Id = Xrm.Page.data.entity.getId();
    var quotationGUID = Id.replace('{', ""); //set this to selected quotation GUID
    quotationGUID = quotationGUID.replace('}', "");
    var reportName = "Quotation"; //set this to the report you are trying to download
    var reportID = "7C39D18F-1DC6-E311-8986-D89D6765B238"; //set this to the guid of the report you are trying to download
    var rptPathString = ""; //set this to the CRMF_Filtered parameter
    var strParameterXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='quote'><all-attributes /><filter type='and'><condition attribute='quoteid' operator='eq' uitype='quote' value='" + quotationGUID + "' /> </filter></entity></fetch>";
    retrieveEntityReq.open("POST", pth, false);
    retrieveEntityReq.setRequestHeader("Accept", "*/*");
    retrieveEntityReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    rptPathString = "id=%7B" + reportID + "%7D&uniquename=" + Xrm.Page.context.getOrgUniqueName() + "&iscustomreport=true&reportnameonsrs=&reportName=" +
    reportName + "&isScheduledReport=false&p:CRMAF_Filteredquote=" + strParameterXML;
    //remove the part starting from &p:salesorderid if your report has no parameters
    retrieveEntityReq.send(rptPathString);
    var x = retrieveEntityReq.responseText.indexOf("ReportSession=");
    var ret = new Array();
    ret[0] = retrieveEntityReq.responseText.substr(x + 14, retrieveEntityReq.responseText.indexOf("&", x) - x - 14); //the session id
    x = retrieveEntityReq.responseText.indexOf("ControlID=");
    ret[1] = retrieveEntityReq.responseText.substr(x + 10, retrieveEntityReq.responseText.indexOf("&", x) - x - 10); //the control id
    return ret;
    var bdy = new Array();
    var bdyLen = 0;
    function concat2Bdy(x) {
    bdy[bdyLen] = x;
    bdyLen++;
    function encodePdf(params) {
    bdy = new Array();
    bdyLen = 0;
    var retrieveEntityReq = new XMLHttpRequest();
    var pth = Xrm.Page.context.getServerUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + params[0] +
    "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + params[1] +
    "&OpType=Export&FileName=Public&ContentDisposition=OnlyHtmlInline&Format=PDF";
    retrieveEntityReq.open("GET", pth, false);
    retrieveEntityReq.setRequestHeader("Accept", "*/*");
    retrieveEntityReq.send();
    BinaryToArray(retrieveEntityReq.responseBody);
    return encode64(bdy);
    var StringMaker = function () {
    this.parts = [];
    this.length = 0;
    this.append = function (s) {
    this.parts.push(s);
    this.length += s.length;
    this.prepend = function (s) {
    this.parts.unshift(s);
    this.length += s.length;
    this.toString = function () {
    return this.parts.join('');
    var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    function encode64(input) {
    var output = new StringMaker();
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;
    while (i < input.length) {
    chr1 = input[i++];
    chr2 = input[i++];
    chr3 = input[i++];
    enc1 = chr1 >> 2;
    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
    enc4 = chr3 & 63;
    if (isNaN(chr2)) {
    enc3 = enc4 = 64;
    } else if (isNaN(chr3)) {
    enc4 = 64;
    output.append(keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4));
    return output.toString();
    </script>
    <script type="text/vbscript">
    Function BinaryToArray(Binary)
    Dim i
    ReDim byteArray(LenB(Binary))
    For i = 1 To LenB(Binary)
    byteArray(i-1) = AscB(MidB(Binary, i, 1))
    concat2Bdy(AscB(MidB(Binary, i, 1)))
    Next
    BinaryToArray = byteArray
    End Function
    </script>
    </head>
    <body>
    <input type="button" onclick="CreateEmail();" value="Attach Report" />
    </body>
    </html>
    Thank you,
    Mittal.

Maybe you are looking for

  • I have lost the ability to view iTunes on my iPhone...anyone know how this happens?

    Can someone give me some insight as to how I could loose viewing iTunes on my iPhone?  It only shows a blank "History" page telling me I don't have any preview history...I cannot go anywhere in iTunes from here.  Thanks for any info on this

  • Widget insertion not working DW CS5 Mac

    I've got a template open and am trying to insert the JBuilder Accordian widget.  I've done all the necessary processes to download the widget from Adobe and put it into my "My Widgets" in the browser.  I click on Insert / Widget and get nothing, no d

  • Bean create & use

    Hi All, I have problem with a jsp page which use a bean! Perhaps I get wrong when I compile the bean file "Login.java" or I place "Login.class" in wrong place! Can you tell me where I must place compiled file in TOMCAT folder? The error displayed is:

  • What does flashing green LED on a Powersupply really mean?

    I found this 3.3 voltage standby (VSB) is on but the power supply unit is not powering the other modules I have two nexus 3500 switches . 3 PS's show solid green and one is flashing green. No amber lights. Thoughts?

  • Upgrading my

    I currently have OSX 10.8.5 and am trying to upgrade to OSX Mavericks, however even though I have the installation app download and I am the admin (only one account, Mac Book Air) every time I click on the install icon I get a message saying "Upgradi