Monday, May 23, 2011

Navigation to the webpage was canceled chm file



CHM Navigation to the Webpage was cancelled
This happend to me after upgrading to Internet Exporer 7.
If you are wondering why you cant read the CHM files, just do the steps below :
  • Open it again and you will get the same popup as shown below
    CHM Navigation to the Webpage was cancelled popup
  • Uncheck the checkboxAlways ask before opening this file (Highlighted in the image above).
  • Press Open

Tuesday, May 17, 2011

Accessibility Levels


When access is allowed to a member, it said to be accessible. Otherwise, it is inaccessible. Use the access modifiers, publicprotectedinternal, or private, to specify one of the following declared accessibilities for members.
Declared accessibilityMeaning
publicAccess is not restricted.
protectedAccess is limited to the containing class or types derived from the containing class.
internalAccess is limited to the current assembly.
protected internalAccess is limited to the current assembly or types derived from the containing class.
privateAccess is limited to the containing type.
Only one access modifier is allowed for a member or type, except for the protected internal combination.
Access modifiers are not allowed on namespaces. Namespaces have no access restrictions.
Depending on the context in which a member declaration takes place, only certain declared accessibilities are permitted. If no access modifier is specified in a member declaration, a default accessibility is used.
Top-level types, which are not nested into other types, can only have internal or public accessibility. The default accessibility for these types is internal.
Nested types, which are members of other types, can have declared accessibilities as indicated in the following table.
Members ofDefault member accessibilityAllowed declared accessibility of the member
enumpublicNone
classprivatepublicprotected
internal
private
protected internal
interfacepublicNone
structprivatepublicinternal
private
The accessibility of a nested type depends on its accessibility domain, which is determined by both the declared accessibility of the member and the accessibility domain of the immediately containing type. However, the accessibility domain of a nested type cannot exceed that of the containing type.

C# Method Wizard


Add a method and define its elements using the one-page C# Method Wizard.
Method access
Sets the access to the method. Access modifiers are keywords for setting access to the method. Specify the access other classes have to the method. The method access level is set to public by default. The following access levels are available: See Accessibility Levels for an overview of these five levels and for more information about specifying access for methods.
Return type
Sets the value type that the method returns in the return statement. The return type is set to void by default. For more information about C# return types, see Value Typesand Built-in Types Table.The following value types are available:
Method name
Sets the name of the method to add to the class. You must add at least the method name.
Modifier
Sets the parameter's modifier. Modifier is set to None by default. See Method Parameters for more information.
Parameter type
Sets the type for the Parameter name. The parameter type is set to int by default. The type is reflected in the Method signature box at the bottom of the wizard. The same values available for the return type are available for the parameter type, with the exception of void.
Parameter name
Sets the name of a parameter to pass through your method. After typing the name, you must click Add to add it to the list of parameters that will pass through your method.If you do not provide a parameter name, the wizard ignores any Modifier or Parameter type selections. Once you click Add, the parameter name appears in Parameter list and in Method signature at the bottom of the wizard. If you supply a parameter name and then click Finish before you click Add, the parameter is not added to the method. You must find the method and insert the parameter manually.
Add
Adds the parameter you specify in Parameter name, and its modifier and type, to the Parameter list and displays the complete parameter in the Method signature box at the bottom of the wizard. You must click Add to add a parameter to the list.
Remove
Removes the parameter you select in Parameter list from the list and from the Method signature box at the bottom of the wizard.
Parameter list
Displays all parameters and their modifiers and types currently added for the method. As you add parameters, the wizard updates the Parameter list to display each parameter, with its modifier and type.
Method modifiers
Modifies the declarations of types and type members. By default, no modifiers are included. Using this wizard, you can add the following modifiers.
Modifier optionDescription
StaticThe method belongs to the type itself rather than to a specific object.
AbstractThe method is a member of an abstract class. If the class to which you are adding the method is not abstract, this option is not available. See C# Class Wizard for more information.
VirtualThe method's implementation can be changed by an overriding member in a derived class.
ExternAdvanced. The method is implemented externally.
OverrideAdvanced. Provide a new implementation of a virtual member inherited from a base class.
NewAdvanced. Explicitly hides a member inherited from a base class. To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier.
You can combine certain modifiers; however, some modifiers are mutually exclusive. For example, you can set your modifiers to new virtualextern static or override abstract. The following combinations of options are not allowed:
ModifierCannot combine with ...
staticvirtualabstract, and override
virtualstaticabstract, and override
overridenewstatic, and virtual
abstractvirtual and static
newoverride
externabstract
Depending on your modifier selection, check boxes appear dimmed for excluded combinations.
Comment
Provides a short description to the method. Comments are converted into XML documentation and encapsulated by <summary> tags, which are used to provide the descriptions.
Method signature
Displays the method as it is added to your code when you click Finish. You cannot edit the text in this box. To change the method, change the appropriate fields in the wizard.

Copy listitems from one custom list to another, then move them into subfolders.


SPListItem listItem = web.GetListItem(listItemUrl);
listItem.CopyTo(destinationUrl); // Copies the item to the specified destinations
or
listItem.CopyFrom(sourceUrl); // Overwrites the current item with the specified version of the item.

SPListItem item = Web.Lists["Announcement"].GetItemById(5);
SPFile file = Web.GetFile(item.Url);
file.MoveTo("New location...with the ID_.000");


Copy file and folder recursively from local drive to SharePoint list.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;
using System.IO;
using System.Text.RegularExpressions;

namespace WindowsFormsApplication2
{
    public partial class Uploder : Form
    {
        public Uploder()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
         
        }

        private void button1_Click(object sender, EventArgs e)
        {
            selectFolder.ShowDialog();
            textBox1.Text = selectFolder.SelectedPath;

            using (SPSite site = new SPSite(textBox2.Text))
            {
                using (SPWeb rootWeb = site.OpenWeb())
                {
                    ActionDocLibRecursive(rootWeb);
                }
            }

        }

     



        private void ActionDocLibRecursive(SPWeb web)
        {
            // loop through each list in the web site
            foreach (SPList list in web.Lists)
            {
                // check if the list is a document library
                if (list.BaseType == SPBaseType.DocumentLibrary)
                {
                    // if it is, create a document library object
                    SPDocumentLibrary docLib = (SPDocumentLibrary)list;
                    // check that the document library is not a "catalog"
                    // (e.g. "Master Pages &amp; Page Layouts" .. or "Web Template Gallery")
                    if (docLib.IsCatalog == false)
                    {
                        LibList.Items.Add(docLib);
                    }
                }
            }

            // call the recursive loop back on itself

            //foreach (SPWeb subWeb in web.Webs)
            //{
            //    // call resursive method on each sub-site of the current site
            //    ActionDocLibRecursive(subWeb);
            //}
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            button2.Enabled = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
         
            try
            {
                selectFolder.ShowDialog();
                textBox1.Text = selectFolder.SelectedPath;
                string localPath = selectFolder.SelectedPath; //Local path.
                string sharePointSite = "http://blr-ws-168/"; //SharePoint site URL.
                string documentLibraryName = "Documents"; // SharePoint library name.
               
                // Make an object of your SharePoint site.
                using (SPSite oSite = new SPSite(sharePointSite))
                {
                    SPWeb oWeb = oSite.OpenWeb();
                    ActionDocLibRecursive(oWeb);

                    CreateDirectories(localPath,oWeb.Folders[documentLibraryName].SubFolders);
                }
            }
            catch (Exception ex)
            {
               
               // MessageBox.Show("Error:" + ex.Message);
               // richTextBox1.AppendText( ex.Message + "\n");
            }
        }

        private void CreateDirectories(string path, SPFolderCollection oFolderCollection)
        {
            //Upload Multiple Files
            foreach (FileInfo oFI in new DirectoryInfo(path).GetFiles())
            {
                CreateValidFileName(oFI.Name);
                FileStream fileStream = File.OpenRead(oFI.FullName);
                SPFile spfile = oFolderCollection.Folder.Files.Add
                            (oFI.Name, fileStream, true);
           
                label4.Text = oFI.Name;
               
                spfile.Update();
                //richTextBox1.AppendText(oFI.Name + "Was Added Sucessfully\n"+ " In "+ spfile);
               
            }

            //Upload Multiple Folders
            foreach (DirectoryInfo oDI in new DirectoryInfo(path).GetDirectories())
            {
                string sFolderName = oDI.FullName.Split('\\')[oDI.FullName.Split('\\').Length - 2];
                SPFolder spNewFolder = oFolderCollection.Add(sFolderName);
               
                spNewFolder.Update();
                //Recursive call to create child folder
                CreateDirectories(oDI.FullName, spNewFolder.SubFolders);

            }

        }

        public void CreateValidFileName(string Filename)
        {
            string invalidChars = Regex.Escape(new string(Path.GetInvalidFileNameChars()));
            string invalidReStr = string.Format(@"[{0}]+", invalidChars);
            Filename = Regex.Replace(Filename, invalidReStr, "_");
           
        }

       
    }
}

How to programmatically download attachments from list items in Windows

SPWeb web = new SPSite("<Site URL>").OpenWeb(); SPList list = web.Lists["<ListName>"]; SPListItem item = list.Items[1]; folder = web.Folders["Lists"].SubFolders[strListName].SubFolders["Attachments"].SubFolders[item.ID.ToString()]; foreach(SPFile file in folder.Files) { byte[] binFile = file.OpenBinary(); System.IO.FileStream fstream = System.IO.File.Create("c:\\MyDownloadFolder\\" + file.Name); fstream.Write(binFile, 0, binFile.Length); }

Monday, May 16, 2011

A generic stack class


#include <iostream>
#include <new>
#include <string>
#include <sstream>

using namespace std;

#if !defined __STACK_H
#define __STACK_H

namespace stk{
template<class T>
class GGStack; // Forward declaration of GGStack class for overloaded <<
operator

template<class T>
ostream& operator<<(ostream &,GGStack<T> &); // template declaration of
<<
operator

template<class T>
class GGStack{
private:
T *p;
int top,length;

string str()const;
public:
GGStack();
GGStack(const int);
GGStack(const GStack<T>&);
~GStack();

void push(T);
T pop();
int get_length()const;
bool is_empty()const;
GStack<T> operator=(const GStack<T>&);

// only for basic types
friend ostream& operator<< <>(ostream&,GStack<T> &);

class GStackException{
private:
string desc;
public:
GStackException(string exp){ desc="Exception : "+exp; }
string get_exp(){ return desc; }
};
};

template<class T>
GStack<T>::GStack(){
top=-1;
length=0;
p=0;
}

template<class T>
GStack<T>::GStack(const int size){
top=-1;
length=size;
try{
p=new T[length];
}catch(bad_alloc ba){
cout<<"Memory can not be alllocated
";
return;
}
}

template<class T>
GStack<T>::GStack(const GStack<T> &o){
top=o.top;
length=o.length;
try{
p=new T[length];
}catch(bad_alloc ba){
cout<<"Memory allocation failed
";
return;
}
for(int i=0;i<length;i++)
p[i]=o.p[i];
}

template<class T>
GStack<T>::~GStack(){
if(p!=0)
delete [] p;
}

template<class T>
void GStack<T>::push(T elem){
if(p==0){
try{
p=new T[1];
}catch(bad_alloc ba){
throw GStackException("Memory fault
");
}
length++;
top++;
p[top]=elem;
}
else if(top==(length-1)){
T *q;
try{
q=new T[length+1];
}catch(bad_alloc ba1){
throw GStackException("Memory fault
");
}
for(int i=0;i<length;i++)
q[i]=p[i];
length++;
top++;
q[top]=elem;
delete [] p;
p=q;
}
else{
top++;
p[top]=elem;
}
}

template<class T>
T GStack<T>::pop(){
if(p==0 || top==-1){
throw GStackException("GStack empty!
");
}
T ret=p[top];
top--;
length--;

if(top==-1){
delete [] p;
p=0;
}
else{
T *q;
try{
q=new T[length];
}catch(bad_alloc ba){
throw GStackException("Memory fault
");
}
for(int i=0;i<length;i++)
q[i]=p[i];
delete [] p;
p=q;
}

return ret;
}

template<class T>
int GStack<T>::get_length()const{
return length;
}

template<class T>
bool GStack<T>::is_empty()const{
return ((p==0)? true : false);
}

template<class T>
string GStack<T>::str()const{  // private member function
if(p==0)
return string("");
stringstream ss;
for(int i=0;i<length;i++){
ss << p[i];
if(i!=(length-1))
ss << ", ";
}
//ss<<"
";
return ss.str();
}

template<class T>
GStack<T> GStack<T>::operator=(const GStack<T> &stk){
length=stk.length;
top=stk.top;

if(p!=0)
delete [] p;
try{
p=new T[length];
}catch(bad_alloc ba){
throw GStackException("Memory fault in copying!
");
}
for(int i=0;i<length;i++)
p[i]=stk.p[i];

return *this;
}

template<class T>
ostream& operator<<(ostream &o,GStack<T> &s){
o<<s.str();
return o;
}

} // namespace stk;

#endif

Exceptions in C++

Exceptions provide a way to react to exceptional circumstances (like runtime errors) in our program by transferring control to special functions called handlers.

To catch exceptions we must place a portion of code under exception inspection. This is done by enclosing that portion of code in a try block. When an exceptional circumstance arises within that block, an exception is thrown that transfers the control to the exception handler. If no exception is thrown, the code continues normally and all handlers are ignored.

An exception is thrown by using the throw keyword from inside the try block. Exception handlers are declared with the keyword catch, which must be placed immediately after the try block:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// exceptions
#include <iostream>
using namespace std;

int main () {
  try
  {
    throw 20;
  }
  catch (int e)
  {
    cout << "An exception occurred. Exception Nr. " << e << endl;
  }
  return 0;
}
An exception occurred. Exception Nr. 20


The code under exception handling is enclosed in a try block. In this example this code simply throws an exception:

 
throw 20;


A throw expression accepts one parameter (in this case the integer value 20), which is passed as an argument to the exception handler.

The exception handler is declared with the catch keyword. As you can see, it follows immediately the closing brace of the try block. The catch format is similar to a regular function that always has at least one parameter. The type of this parameter is very important, since the type of the argument passed by the throw expression is checked against it, and only in the case they match, the exception is caught.

We can chain multiple handlers (catch expressions), each one with a different parameter type. Only the handler that matches its type with the argument specified in the throw statement is executed.

If we use an ellipsis (...) as the parameter of catch, that handler will catch any exception no matter what the type of the throw exception is. This can be used as a default handler that catches all exceptions not caught by other handlers if it is specified at last:

1
2
3
4
5
6
try {
  // code here
}
catch (int param) { cout << "int exception"; }
catch (char param) { cout << "char exception"; }
catch (...) { cout << "default exception"; }


In this case the last handler would catch any exception thrown with any parameter that is neither an int nor a char.

After an exception has been handled the program execution resumes after the try-catch block, not after the throw statement!.

It is also possible to nest try-catch blocks within more external try blocks. In these cases, we have the possibility that an internal catch block forwards the exception to its external level. This is done with the expression throw; with no arguments. For example:

1
2
3
4
5
6
7
8
9
10
11
try {
  try {
      // code here
  }
  catch (int n) {
      throw;
  }
}
catch (...) {
  cout << "Exception occurred";
}


Exception specifications


When declaring a function we can limit the exception type it might directly or indirectly throw by appending a throw suffix to the function declaration:

 
float myfunction (char param) throw (int);


This declares a function called myfunction which takes one agument of type char and returns an element of type float. The only exception that this function might throw is an exception of type int. If it throws an exception with a different type, either directly or indirectly, it cannot be caught by a regular int-type handler.

If this throw specifier is left empty with no type, this means the function is not allowed to throw exceptions. Functions with no throw specifier (regular functions) are allowed to throw exceptions with any type:

1
2
int myfunction (int param) throw(); // no exceptions allowed
int myfunction (int param);         // all exceptions allowed 


Standard exceptions

The C++ Standard library provides a base class specifically designed to declare objects to be thrown as exceptions. It is called exception and is defined in the <exception> header file under the namespace std. This class has the usual default and copy constructors, operators and destructors, plus an additional virtual member function called what that returns a null-terminated character sequence (char *) and that can be overwritten in derived classes to contain some sort of description of the exception.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// standard exceptions
#include <iostream>
#include <exception>
using namespace std;

class myexception: public exception
{
  virtual const char* what() const throw()
  {
    return "My exception happened";
  }
} myex;

int main () {
  try
  {
    throw myex;
  }
  catch (exception& e)
  {
    cout << e.what() << endl;
  }
  return 0;
}
My exception happened.


We have placed a handler that catches exception objects by reference (notice the ampersand & after the type), therefore this catches also classes derived from exception, like our myexobject of class myexception.

All exceptions thrown by components of the C++ Standard library throw exceptions derived from this std::exception class. These are:

exceptiondescription
bad_allocthrown by new on allocation failure
bad_castthrown by dynamic_cast when fails with a referenced type
bad_exceptionthrown when an exception type doesn't match any catch
bad_typeidthrown by typeid
ios_base::failurethrown by functions in the iostream library

For example, if we use the operator new and the memory cannot be allocated, an exception of type bad_alloc is thrown:

1
2
3
4
5
6
7
8
try
{
  int * myarray= new int[1000];
}
catch (bad_alloc&)
{
  cout << "Error allocating memory." << endl;
}


It is recommended to include all dynamic memory allocations within a try block that catches this type of exception to perform a clean action instead of an abnormal program termination, which is what happens when this type of exception is thrown and not caught. If you want to force a bad_alloc exception to see it in action, you can try to allocate a huge array; On my system, trying to allocate 1 billion ints threw a bad_alloc exception.

Because bad_alloc is derived from the standard base class exception, we can handle that same exception by catching references to the exception class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// bad_alloc standard exception
#include <iostream>
#include <exception>
using namespace std;

int main () {
  try
  {
    int* myarray= new int[1000];
  }
  catch (exception& e)
  {
    cout << "Standard exception: " << e.what() << endl;
  }
  return 0;
}
 

Featured Posts

#Linux Commands Unveiled: #date, #uname, #hostname, #hostid, #arch, #nproc

 #Linux Commands Unveiled: #date, #uname, #hostname, #hostid, #arch, #nproc Linux is an open-source operating system that is loved by millio...