Recent Updates Page 2 Toggle Comment Threads | Keyboard Shortcuts

  • Ali BaderEddin 11:49 pm on September 18, 2010 Permalink | Reply
    Tags: Get-SPWebApplication, , Microsoft.SharePoint.PowerShell, Mount-SPContentDatabase, New-SPContentDatabase   

    Content DB Attach using PowerShell 

    In this post, I’ll talk about how to attach\mount a SharePoint content database to a SharePoint web application after it has been restored\attached to the SQL server. See my previous post for details on how to restore a database using PowerShell.

    SharePoint provides a cmdlet to do the content db attach. This cmdlet is called Mount-SPContentDatabase. I will create a script block wrapper for this cmdlet and show how to call it remotely. The script block below adds the SharePoint PowerShell snapin if it’s not already added, selects a web application in the farm, then calls the Mount-SPContentDatabase to do the content db attach.

    [ScriptBlock] $global:AttachSPContentDB =
        param([string] $dbName, [string] $dbServer)
            # Load the Sharepoint Cmdlets
            Write-Host "Loading SharePoint PowerShell Snapin"
            $spSnapin = Get-PSSnapin | where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}
            if($spSnapin -eq $null)
                Add-PSSnapin Microsoft.SharePoint.PowerShell
                Write-Host -ForegroundColor "Green" -Object "SharePoint PowerShell Snapin loaded"
                Write-Host -ForegroundColor "Gray" -Object "SharePoint PowerShell Snapin already loaded"
            # Get  web applciation url
            Write-Host "Selecting a web application in the farm"
            $webAppUrl = (Get-SPWebApplication | select -Index 0).Url
            # Mount the database at the specified SQL server to the web application
            Write-Host "Mounting database '$dbName' at SQL server '$dbServer' to web application '$webAppUrl'"
            $newDB = Mount-SPContentDatabase $dbName -DatabaseServer $dbServer -WebApplication $webAppUrl -AssignNewDatabaseId
            Write-Host -ForegroundColor "Green" -Object "Database mounted successfully with ID: " + ($newDB.Id)
            # Return content DB Id
            return $newDB.Id.ToString()
        catch [Exception]
            Write-Host -ForegroundColor "Red" -Object $_.Exception
            return $null

    To call this script block, pass the name of the Sql server and the name of the content database. Make sure that the content database is already restored\attached to the SQL server.

    .$AttachSPContentDB "ContentDBName" "SqlServerName"

    To call the script block on a remote SharePoint WFE, you can simply run

    Invoke-Command -ComputerName "WFEName" -ScriptBlock { .$AttachSPContentDB "ContentDBName" "SqlServerName" }

    Note that the New-SPContentDatabase cmdlet has the same effect as Mount-SPContentDatabase. The only difference is that New-SPContentDatabase creates a new SQL database if there is no database with the same name already available on the SQL server.

    • warszawa 10:11 pm on September 11, 2014 Permalink | Reply

      Βardzo lubіęodcienie!

    • comprar galletas decoradas 1:05 pm on September 12, 2014 Permalink | Reply

      Ponemos la masa sobre papel de horno y la estiramos con el rodillo
      hasta tener un grosor de 4 mm. Con un cortapastas de seis cm de
      diámetro vamos haciendo las galletas.

  • Ali BaderEddin 6:38 pm on September 18, 2010 Permalink | Reply
    Tags: Add-PSSnapin, attach, database, , , Invoke-Sqlcmd, LogicalFileName, MSSQL, network path, New-PSSession, PhysicalFileName, PowerShell, ReadFileList, RelocateFiles, restore, scriptblock, SMO, Smo.Restore, Smo.Server, SqlRestore, SqlServerCmdletSnapin100, _Data.mdf, _Log.ldf   

    SQL DB Restore using PowerShell 

    If you are looking for a PowerShell script that lets you restore a database from a backup (.bak) file to MSSQL server, then this is the right place for you.

    Database Restore – SQL

    Let’s say you have a .bak file (Ex: AdventureWorks), and you would like to restore it to an SQL server using PowerShell. If you use SQL Server 2008 Management Studio and click on the “Script” button, you will get th SQL statement that will do that restore for you.

    Here is the SQL RESTORE statement that will allow you to restore the AdventureWorksLT2008R2.bak to the new database ‘NewDatabaseName’.

    RESTORE DATABASE [NewDatabaseName]
    FROM DISK = N'C:\.etc..\AdventureWorksLT2008R2.bak'
    WITH FILE = 1,
    MOVE N'AdventureWorksLT2008R2_Data'
    TO N'C:\.etc..\MSSQL\DATA\NewDatabaseName.mdf',
    MOVE N'AdventureWorksLT2008R2_Log'
    TO N'C:\.etc..\MSSQL\DATA\NewDatabaseName_1.ldf',

    If you use SQL Server 2008 R2 Management Studio, the generated SQL statement would look like this.

    RESTORE DATABASE [NewDatabaseName]
    FROM  DISK = N'C:\.etc..\AdventureWorksLT2008R2.bak'
    WITH  FILE = 1,  NOUNLOAD,  STATS = 10

    Running this statement is almost the same as the previous statement, except that the MDF and LDF files would be named AdventureWorksLT2008R2_Data.mdf and AdventureWorksLT2008R2_Log.ldf respectively (instead of having NewDatabaseName in the file names).

    If we want to create a simple PowerShell function to run the SQL Restore command, we can do so using the OSQL Utility:

    function global:RestoreDB ([string] $newDBName, [string] $backupFilePath)
        [string] $dbCommand = "RESTORE DATABASE [$newDBName] " +
        "FROM    DISK = N'$backupFilePath' " +
        "WITH    FILE = 1, NOUNLOAD, STATS = 10"
        OSQL.EXE -E -Q $dbCommand

    We can also take advantage of the Invoke-Sqlcmd command to do the same thing. Here is how the function would look like:

    function global:RestoreDB ([string] $newDBName, [string] $backupFilePath)
        [string] $dbCommand = "RESTORE DATABASE [$newDBName] " +
                              "FROM    DISK = N'$backupFilePath' " +
                              "WITH    FILE = 1, NOUNLOAD, STATS = 10"
        Invoke-Sqlcmd -Query $dbCommand

    If using Invoke-Sqlcmd fails, make sure the SqlServerCmdletSnapin100 snapin is added. You can put the below snippet in the function above before the call to Invoke-Sqlcmd.

    $sqlSnapin = Get-PSSnapin | where {$_.Name -eq "SqlServerCmdletSnapin100"}
    if($sqlSnapin -eq $null)
    Add-PSSnapin SqlServerCmdletSnapin100

    Calling this function is as simple as:

    RestoreDB "NewDatabaseName" "C:\.etc..\AdventureWorksLT2008R2.bak"

    Remote SQL Server

    In case your SQL Server is on a remote machine that doesn’t have the SQL client installed, you can use the Invoke-Command to restore the database on the remote machine. However, the function needs to be loaded to be invoked on the remote machine, so either put it in a separate file and load it remotely or convert it to a script block that can be directly passed to Invoke-Command.

    Assuming the remote SQL server name is SQLServer01, here are the two approaches to do this.

    Using a Function

    Put the RestoreDB function in a new PowerShell file; Let’s call it DatabaseRestore.ps1. To call remotely, first we need to create a PowerShell session on the remote SQL Server machine.

    $session = New-PSSession -ComputerName "SQLServer01"

    If you are using SQL Server 2008 R2, you might get the following error: “Connecting to remote server failed with the following error message : The WinRM client cannot complete the operation within the time specified. Check if the machine name is valid and is reachable over the network and firewall exception for Windows Remote Management service is enabled“. The resolution is located here. In short, go to your SQL Server 2008 R2 machine, launch the Command Prompt as administrator then run this command: winrm quickconfig.

    After creating the session, we need to load the DatabaseRestore.ps1 script on the remote machine to be able to call the RestoreDB function.

    $scriptPath = "C:\..etc..\DatabaseRestore.ps1"
    Invoke-Command -Session $session -FilePath $scriptPath

    If you get an error that the file cannot be loaded because the execution of scripts is disabled on the system, then you should make sure that the execution policy is remotesigned or unrestricted (Set-ExecutionPolicy unrestricted).

    Next step would be to simply call the function. Note that the path to the backup file must be accessible to the remote SQL machine.

    Invoke-Command -Session $session -ScriptBlock { RestoreDB "NewDatabaseName" "C:\..etc..\AdventureWorksLT2008R2.bak" }
    Using a Script Block

    In our case, using a script block is simpler. All we need to do is define the script block, then run one single Invoke-Command to do the database restore. The script block definition is almost the same as the function definition, as shown below:

    [ScriptBlock] $global:RestoreDB = {
        param ([string] $newDBName, [string] $backupFilePath)
        [string] $dbCommand = "RESTORE DATABASE [$newDBName] " +
                              "FROM    DISK = N'$backupFilePath' " +
                              "WITH    FILE = 1, NOUNLOAD, STATS = 10"
        $sqlSnapin = Get-PSSnapin | where {$_.Name -eq "SqlServerCmdletSnapin100"}
        if($sqlSnapin -eq $null)
             Add-PSSnapin SqlServerCmdletSnapin100
        Invoke-Sqlcmd -Query $dbCommand

    Make sure you don’t forget the equal sign (=) in the first line of the above script block definition. Now, to restore the DB, we call a single Invoke-Command cmdlet. Make sure that the -ArgumentList parameters are separated by comma (,) or the script will fail.

    Invoke-Command -ComputerName "SQLServer01" -ScriptBlock $RestoreDB -ArgumentList "NewDatabaseName", "C:\AdventureWorksLT2008R2.bak" 
    Function vs. Script Block

    Here are some simple guidelines on when to use a function and when to use a script block.

    • To call a function on a remote machine, it must first be defined on the remote machine. That’s why we need an Invoke-Command to load the PowerShell file containing the function, then another Invoke-Command to call the function.
    • To call a script block remotely, it doesn’t have to be defined on the remote machine. When the script block is passed as a parameter to Invoke-Command, the whole script block actually gets copied to the remote machine.
    • If your logic has any dependency on any global variable or function (Ex: it calls another script block or it calls a helper function), then it makes most sense to use a function. Define the function, global variables and helper functions in one file, then load them on the remote machine.
    • If your logic is self-contained, then use a script block. The whole logic will get copied to the remote machine.

    Database Restore – SMO

    To have more control on how we do the database restore, we should use the SMO object model. For example, our script above restores the database with name “NewDatabaseName” but the MDF and LDF file names are still AdventureWorksLT2008R2_Data.mdf and AdventureWorksLT2008R2_Log.ldf. Now, you would think, why not use the SQL statement below in our script?

    RESTORE DATABASE [NewDatabaseName]
    FROM DISK = N'C:\.etc..\AdventureWorksLT2008R2.bak'
    WITH FILE = 1,
    MOVE N'AdventureWorksLT2008R2_Data'
    TO N'C:\.etc..\MSSQL\DATA\NewDatabaseName.mdf',
    MOVE N'AdventureWorksLT2008R2_Log'
    TO N'C:\.etc..\MSSQL\DATA\NewDatabaseName_1.ldf',

    To put this in a script block, it will look as follows:

    [ScriptBlock] $global:RestoreDB = {
    param ([string] $newDBName, [string] $backupFilePath, [string] $sqlDataPath, [string] $dataLogicalName, [string] $logLogicalName)
    [string] $dbCommand = "RESTORE DATABASE [$newDBName] " +
    "FROM    DISK = N'$backupFilePath' " +
    "WITH    FILE = 1, " +
    "MOVE N'$dataLogicalName' " +
    "TO N'$sqlDataPath\$newDBName.mdf', " +
    "MOVE N'$logLogicalName' " +
    "TO N'$sqlDataPath\$newDBName.ldf', " +
    "NOUNLOAD, STATS = 10"
    $sqlSnapin = Get-PSSnapin | where {$_.Name -eq "SqlServerCmdletSnapin100"}
    if($sqlSnapin -eq $null)
    Add-PSSnapin SqlServerCmdletSnapin100
    Invoke-Sqlcmd -Query $dbCommand

    Ok, this might be good enough, but it’s not dynamic\generic. You can get the SQL data path from the registry, but you cannot get the logical names of the data and log files unless you find a way to open the .bak file and read the logical names of those files. Instead of hardcoding the logical names of the Data and Log files (i.e. pass “AdventureWorksLT2008R2_Data” and “AdventureWorksLT2008R2_Log”), we can read the file list from the .bak file using SMO (ReadFileList() method).

    PowerShell comments below provide enough details. Note that if the backup file is on a network share, the ReadFileList() method would fail. So in that case, we need to copy the file locally. That’s why the script block takes “$isNetworkPath” boolean variable to take that into consideration.

    [ScriptBlock] $global:RestoreDBSMO = {
        param([string] $newDBName, [string] $backupFilePath, [bool] $isNetworkPath = $true)
            # Load assemblies
            [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
            [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
            [Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null
            [Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | Out-Null
            # Create sql server object
            $server = New-Object ("Microsoft.SqlServer.Management.Smo.Server") "(local)"
            # Copy database locally if backup file is on a network share
                $fileName = [IO.Path]::GetFileName($backupFilePath)
                $localPath = Join-Path -Path $server.DefaultFile -ChildPath $fileName
                Copy-Item $backupFilePath $localPath
                $backupFilePath = $localPath
            # Create restore object and specify its settings
            $smoRestore = new-object("Microsoft.SqlServer.Management.Smo.Restore")
            $smoRestore.Database = $newDBName
            $smoRestore.NoRecovery = $false;
            $smoRestore.ReplaceDatabase = $true;
            $smoRestore.Action = "Database"
            # Create location to restore from
            $backupDevice = New-Object("Microsoft.SqlServer.Management.Smo.BackupDeviceItem") ($backupFilePath, "File")
            # Give empty string a nice name
            $empty = ""
            # Specify new data file (mdf)
            $smoRestoreDataFile = New-Object("Microsoft.SqlServer.Management.Smo.RelocateFile")
            $defaultData = $server.DefaultFile
            if (($defaultData -eq $null) -or ($defaultData -eq $empty))
                $defaultData = $server.MasterDBPath
            $smoRestoreDataFile.PhysicalFileName = Join-Path -Path $defaultData -ChildPath ($newDBName + "_Data.mdf")
            # Specify new log file (ldf)
            $smoRestoreLogFile = New-Object("Microsoft.SqlServer.Management.Smo.RelocateFile")
            $defaultLog = $server.DefaultLog
            if (($defaultLog -eq $null) -or ($defaultLog -eq $empty))
                $defaultLog = $server.MasterDBLogPath
            $smoRestoreLogFile.PhysicalFileName = Join-Path -Path $defaultLog -ChildPath ($newDBName + "_Log.ldf")
            # Get the file list from backup file
            $dbFileList = $smoRestore.ReadFileList($server)
            # The logical file names should be the logical filename stored in the backup media
            $smoRestoreDataFile.LogicalFileName = $dbFileList.Select("Type = 'D'")[0].LogicalName
            $smoRestoreLogFile.LogicalFileName = $dbFileList.Select("Type = 'L'")[0].LogicalName
            # Add the new data and log files to relocate to
            # Restore the database
            "Database restore completed successfully"
        catch [Exception]
            "Database restore failed:`n`n " + $_.Exception
            # Clean up copied backup file after restore completes successfully
                Remove-Item $backupFilePath

    Here is how to call this script block (Don’t forget the dot (.) infront of the script block variable):

    .$RestoreDBSMO "NewDatabaseName" "C:\.etc..\AdventureWorksLT2008R2.bak" $false

    Same story goes for calling this function remotely.

    • Peter 3:04 am on January 29, 2014 Permalink | Reply

      I ran into an issue with “Invoke-Sqlcmd -Query $dbCommand” but fixed it with
      Invoke-Sqlcmd -Serverinstance ‘servername\instance’ -Query $dbCommand

    • detox isnt 3:26 pm on July 24, 2014 Permalink | Reply

      Hi there mates, how is everything, and what you desire to say regarding this article, in my view
      its genuinely remarkable in support of me.

  • Ali BaderEddin 11:08 pm on June 8, 2010 Permalink | Reply
    Tags: AllowWindowsClientInstall, optimizeCompilations, SharePoint Designer, SharePointFoundation, standalone, windows 7   

    SharePoint Foundation 2010 on Windows 7 

    This MSDN article describes in detail how to install SharePoint Foundation 2010 for development purposes on Windows Vista, Windows 7 and Windows Server 2008. The purpose of this post is to focus on the SharePoint installation on Window 7 only and clear out all the details for the other operating systems.

    1. Download SharePoint Foundation 2010 x64 for free. Note that there is no x86 version of SharePoint Server, so don’t bother setting it up if you have a 32-bit machine.
    2. Create a new folder “C:\SharePointFiles” and copy “SharePointFoundation.exe” to it.
    3. Start command prompt, change directory to C:\SharePointFiles and run the following command to extract the “SharePointFoundation.exe” to C:\SharePointFiles
      SharePointFoundation.exe /extract:C:\SharePointFiles
    4. Open C:\SharePointFiles\files\Setup\config.xml, add a new <Setting> tag under the <Configuration> element, then save the file. Make sure you copy the below element as is since all of the text in the configuration file is case-sensitive.
      <Setting Id=”AllowWindowsClientInstall” Value=”True”/>
    5. Install the following Prerequisites:
    6. Enable the required windows features by running this batch file:
    7. Restart your computer to complete the changes that you made to Windows Features.
    8. Install SharePoint 2010
      • Run Setup.exe under C:\SharePointFiles
      • Select standalone (Windows 7 can’t be used for production deployments of SharePoint 2010 and it’s recommended that you use Standalone only)
      • After the installation is complete, you will be prompted to start the SharePoint Products and Technologies Configuration Wizard.
    9. After a SharePoint solution (.wsp file) is deployed, it recycles the application pool. To improve the initial page load times, set the optimizeCompilations property of the <compilation> tag in your web.config file (C:\inetpub\wwwroot\wss\VirtualDirectories\80\web.config) to true.
      <compilation optimizeCompilations=”true”>

    SharePoint Designer 2010 is also free and can help you better design your SharePoint site(s). You can download it here.

    • Ravi 10:09 pm on August 1, 2010 Permalink | Reply

      Hello Sir,
      I want to develop an application in .net, that will read XML file. and will convert that code into any language such as C, C#, Java. But I am not getting How to start..
      Thank You.

    • Bas 12:51 am on September 13, 2010 Permalink | Reply

      Hey, I am trying to install spf 2010 on my Windows 7 machine. Works for me till step 4. I changed the config.xml file on location C:\SharePointFiles\Files\Setup\config.xml to:

      *Without linebreaks ofcourse.

      When I run the Setup I get the following Setup error:
      This product requires Windows Server 2008 Service Pack 2 or above.

      Do you have any idea what is going wrong?

      Thank you!

    • Bas 12:53 am on September 13, 2010 Permalink | Reply

      Can I show my code?

    • Bas 12:54 am on September 13, 2010 Permalink | Reply

      Probably not..

    • Ali BaderEddin 2:34 pm on September 13, 2010 Permalink | Reply

      What exactly are you blocked on in step 4?

    • Alessandro 7:32 pm on December 21, 2010 Permalink | Reply

      Hi guys,

      I’ll use Sharepoint in my company (~20 users) to act like a ECM, just for document repository, some permission roles, etc.

      I have a Quad-core PC with 4 GB RAM and Win7 64-bits installed. JIRA applications are already installed on this machine.

      Can I also install the Sharepoint Foundation 2010 for production in this machine, just for 20 users??? My question is, will I have performance issues???

      Thank you.

    • Ali BaderEddin 1:23 pm on December 23, 2010 Permalink | Reply

      Alessandro, I don’t have an answer to your question. That depends on how much traffic the 20 users put on the site.

      I would recommend having 8GB RAM on that machine given that there will be multiple IIS, SQL server, SharePoint timer service and User Code service processes running on that machine. Add to that the JIRA applications that you have, which I have no clue how much memory they’d consume.

    • Pachy 3:36 pm on January 19, 2011 Permalink | Reply

      I did all the steps but i got a blank page…what should I do??

    • Peter Cooper 7:39 am on January 25, 2011 Permalink | Reply

      Thanks for this. Was really useful and worked fine for me. You need to watch out if you copy-and-paste the XML line because the quote marks appear as ascii #148.

    • Doug Fisher 3:05 am on April 13, 2011 Permalink | Reply


      I have followed the above procedure but hit two snags:

      1 The batch file returns an error about an incorrect format
      2 Running Setup.exe gives an error regards the config.xml file. It says it is not valid. I have copied as instructed, so what is this about?

      My W7 is installed on VM Workstation 7

      Any help is greatly appreciated

      • Sharique Khan 10:33 pm on July 12, 2011 Permalink | Reply


        I was also facing the problem with the config file. The issue is in this blog in the opening quote for attribute is ” instead of “. So if you do a direct copy paste you will encounter the problem of xml invalid.

    • mayuri 8:29 am on September 28, 2011 Permalink | Reply

      Thank you very much for this post. I was successfully in setting up sp foundation on windows 7.

    • Michael J Murton 6:04 am on April 19, 2012 Permalink | Reply

      Hi, I am running into the same config.xml invalid error when I try to run setup.exe for SharePoint Foundation 2010. Is there a valid xml file that I can copy and paste? Any help would be appreciated. tx Mike

    • maiomar86 10:56 pm on September 11, 2012 Permalink | Reply

    • Scott 2:13 pm on December 13, 2012 Permalink | Reply

      Great article. The only problem I had was within editing the element, it didn’t like your quotes. I deleted them and added them back and worked as described. Thank you for doing this.

    • John 6:02 pm on June 5, 2013 Permalink | Reply

      I had to remove and readd the double quotes (4) and use initial caps on Id and Value. Then setup.exe was able to run without erroring on the config file.

    • escorts leeds 2:15 pm on July 14, 2014 Permalink | Reply

      I do not even know how I ehded up here, but I thought this post was great.
      I don’t know wwho you are but certainly you are going to a famous blogger if you aren’t already ;)

    • online electronic learning 9:58 pm on August 15, 2014 Permalink | Reply

      Why visitors still make use of too read news papers when in this technological world everything is presented on web?

    • Justine 3:11 am on August 26, 2014 Permalink | Reply

      This excellent website definitelyy has all of the information and facts I
      wanted concerning this subject and didn’t know who to ask.

    • Lelia 6:18 pm on October 2, 2014 Permalink | Reply

      I hadn’t practiced this part with my dad because he had forgotten to teach me.
      There is also the love and hate relationship with users
      and Microsoft. Open the Help and Support from the Start menu and click Options and Settings.

    • wat remover 1:53 pm on October 4, 2014 Permalink | Reply

      Office validation process Authentication in Windows Help, Microsoft proposed:
      “Microsoft for the purchase of a counterfeit Windows software provides complimentary Windows software. Adding registry elements to specific features of your application is again possible using the Filter Keys by Feature check-box. Speed is determined by so many different factors out of your control that I would not obsess over this aspect if I were you.

    • buy a domain 3:33 am on November 16, 2014 Permalink | Reply

      I delight in, lead to I discovered just what I used to be looking for.
      You have ended my four day lengthy hunt! God Bless you man. Have
      a great day. Bye

    • Emilio 8:01 am on November 29, 2014 Permalink | Reply

      and beyond, that home windows was wave-formed, which eventually developed
      into much more of a flag, because of shadowing along with
      other effects. Thankfully, this tablet actually has some
      innovative new features that people will likely want to get their hands
      on, and it should sell extremely fast. The tracking server tried
      to take action against, or users of the Bit – Torrent internetszolg.

  • Ali BaderEddin 3:52 pm on May 28, 2010 Permalink | Reply
    Tags: Back, Bottom, camera, Front, glOrtho, glRotatef, glScalef, glTranslatef, gluLookAt, gluPerspective, GL_MODELVIEW, GL_PROJECTION, Left, Right, Top   

    OpenGL Camera 

    The concept of a camera in a Graphics application is simple. Just imagine that what you see is the view of the camera. So adjusting the camera lens or moving\rotating it should affect your view. In the base OpenGL library, there is no concept of a camera. However, it can be simulated by applying the inverse of the camera transformation on the objects\pixels in the scene. Instead of having to build the matrix and invert it ourselves, the GLU library provides the gluLookAt function, which would do the work for us. This function takes as a parameter the location (x, y, z) of the camera\eye, the location (x, y, z) of the point to look at, and the coordinates (x, y, z) of the Up vector (rotation of the camera around its origin). Note that this function should be called on the ModelView matrix before any transformation is applied on objects in the scene. Avoid calling this function on the Projection matrix (more details here).

    Given the description above, after specifying the camera attributes with a call to gluLookAt then drawing the objects in the scene, one would expect to see the objects in the scene based on the view of the camera. This expectation is completely valid, however, there is one more variable that affects what we see: the viewing volume (similar to real-world camera focus), which is controlled by calls on the projection matrix. Try to imagine what you’ll see if you run the code below:

    GLdouble eyeX = 0, eyeY = 0, eyeZ = 2;
    GLdouble centerX = 0, centerY = 0, centerZ = 0;
    GLdouble upX = 0, upY = 1, pZ = 0;
    void display()
        //  Set up camera properties
        glMatrixMode (GL_MODELVIEW);
        gluLookAt (eyeX, eyeY, eyeZ,
                   centerX, centerY, centerZ,
                   upX, upY, upZ);
        //  Draw an Object at the origin
        drawObject ();

    The answer to the question above is that you’ll see nothing! The reason is that eyeZ = 2, the viewing volume is glOrtho(-1, 1, -1, 1, -1, 1) by default, and the object is drawn at the origin. Here is a visual demonstration using Nate Robin’s interactive OpenGL tutorial (projection.exe).

    If we change zFar (last parameter of glOrtho) of projection to 3 or if we change eyeZ of the camera to 0.5, then we’ll be able to see the object.

    To summarize all of this, I am taking advantage of one of the slides of the Siggraph OpenGL tutorial.

    If you’ve used one of those 3D modeling software out there (like 3ds Max, Maya, etc…), then you’ve certainly seen multiple orthogonal views (Front, Back, Top, Bottom, Left, Right) of your 3D drawing. Here is a screenshot from 3ds Max.

    Using the OpenGL camera, I’m going to create an OpenGL app that has 6 sub-windows each displaying the same object, but from a different camera angle. The world coordinates will be glOrtho(-1, 1, -1, 1, -2, 2) and the views will be: Front, Back, Top, Bottom, Left, and Right. The parameters that are going to be passed to gluLookAt will vary based on the view:

    The program looks as follows.

    Note that you can use the left mouse button to rotate the object, right mouse button to translate the object, and middle mouse button to scale it. Also, the ‘r’ key will reset the object transformations in the scene. You can find the full source code here. If you have any issues compiling or running the app, check out this section for details about compiling and running an OpenGL app that uses the GLUT library.

    • annuaire inverse 8:10 am on September 23, 2014 Permalink | Reply

      hi!,I like your writing so so much! percentage we be in contact more approximately your
      article on AOL? I need an expert in this area to solve my problem.
      Maybe that is you! Taking a look forward to peer you.

  • Ali BaderEddin 9:14 pm on May 27, 2010 Permalink | Reply  

    GLUT Menu World 

    This post demonstrates how to create a GLUT menu and add to it sub-menus and menu items.

    In the above sample app, clicking on a menu item in the popup menu will log that menu item’s ID to the console window. Below is the function setupMenus() that creates the main menu and adds to it all the sub-menus and menu items. You can change it based on your needs then call it in the init() method.

    //  Set up the GLUT Menus.
    void setupMenus ()
        int subMenuCount;  //  Count of sub menus
        int menuItemCount; //  Count of menu items in a submenu
        int *menuIds;      //  Submenu IDs
        char str[256];     //  The string of the current menu item
        int i, j;          //  Iterators
        //  Generate a random value for submenu count
        subMenuCount = rand() % 20;
        //  Allocate memory for the submenu IDs
        menuIds = (int *) xmalloc (subMenuCount * sizeof (int));
        //  Create all the sub menus
        for (i = 0; i < subMenuCount; i++)
            menuIds[i] = glutCreateMenu (showMenuItem);
        for (i = 1; i < subMenuCount; i++)
            //  Set sub menu string
            sprintf (str, "SubMenu %d", i);
            //  Add the current submenu to previous submenu
            glutSetMenu (menuIds[i-1]);
            glutAddSubMenu (str, menuIds[i]);
            //  New menu item count for the new submenu
            menuItemCount = rand () % 20;
            //  Add menu items to the current submenu
            for (j = 1; j < menuItemCount; j++)
                sprintf (str, "Menu Item %d", j);
                glutAddMenuEntry (str, j);
        //  Set main menu as the current menu
        glutSetMenu (menuIds[0]);
        //  Attach the menu to the RMB

    Major GLUT functions briefly explained:

    • glutCreateMenu creates the main menu or sub-menu and returns its ID. It takes as a parameter a pointer to a function with the signature void func (int menuItemId). This function is called every time the  user clicks a menu item in the menu and the parameter menuItemId passed to it represents the id of the menu item.
    • glutAddSubMenu adds another menu to current menu.
    • glutAddMenuEntry adds a menu item to the current menu.
    • glutSetMenu sets the current menu. So when we call glutAddSubMenu or glutAddMenuEntry, they get added to the current menu.
    • glutAttachMenu(GLUT_RIGHT_BUTTON) attaches the “current” menu to the right click button. So when you right click the mouse, the popup menu will show up.

    This is the function that we are passing to glutCreateMenu in our sample app. Every time the user clicks on a menu item, this function is called and it will simply display the menu item id on the console window.

    //  Displays the menu item id on the console window
    void showMenuItem (int val)
        printf ("Menu Item: %d\n", val);

    Download the full source code here.

    • facebook likes buy review 1:49 am on September 6, 2014 Permalink | Reply

      The excellent quick film above illustrates the damaging correlation involving specific peoples’ Facebook likes and their actual happiness.

      For anyone who has ever been a tiny uncomfortable watching a friend happily spin their breakup as “Lastly Single!!!” or any other variation on that theme,
      you must enjoy this. facebook likes buy review

Compose new post
Next post/Next comment
Previous post/Previous comment
Show/Hide comments
Go to top
Go to login
Show/Hide help
shift + esc

Get every new post delivered to your Inbox.

%d bloggers like this: