Search This Blog

Friday, April 17, 2015

How to check a value is SPGroup or SPUser

SPList olist = oweb.Lists.TryGetList("Test_List");
if (olist != null)
{
SPListItemCollection ocoll = olist.Items;
foreach(SPItem oitem in ocoll)
{
SPFieldUserValueCollection GetAllGroup = new SPFieldUserValueCollection(oweb, Convert.ToString(oitem["SPGroups"]));

for (int i = 0; i < GetAllGroup.Count; i++)
{
SPFieldUserValue singlevalue = GetAllGroup[i];
if (singlevalue.User == null)   // If it is GROUP condition is true
{
SPGroup group = oweb.Groups[singlevalue.LookupValue];
foreach (SPUser user in group.Users)
{
if (ouser.Name == user.Name)
{
isuserval = true;
break;
}
}
}
else
{
if (ouser.Name == singlevalue.User.Name) // Checks User is Current Login User
{
isuserval = true;
break;
}
}
}
}
}


Impersonation in Sharepoint

Although not recommended, there may be times when you need your code to perform certain functions that the current user does not have the necessary permissions to perform.

The SPSecurity class provides a method (RunWithElevatedPrivileges) that allows you to run a subset of code in the context of an account with higher privileges than the current user.
The premise is that you wrap the RunWithElevatedPrivileges method around your code.
And also In certain circumstances, such as when working with Web forms, you may also need to set the AllowSafeUpdates method to true to temporarily turn off security validation within your code.
If you use this technique, it is imperative that you set the AllowSafeUpdates method back to false to avoid any potential security risks.

Get values from People picker control

if (pplUser.Entities.Count > 0)
            {
                PickerEntity pe = (PickerEntity)pplUser.Entities[0];
                Username = pe.Key;
                ouser = SPContext.Current.Web.EnsureUser(Username);
                UserID = ouser.ID;
            }


Want A Proper Programming Style? Here Are Rules You Need To Follow

  1. Utmost readability of code

For a code to be readable and understandable, it needs to be formatted in a consistent manner. Plus, it should also use meaningful names for all the functions and variables with concise and accurate comments. It is important for you to make a clear note of all the tricky sections included within the code. You must be clear on the reasons as to why the software program will work and why it should work smoothly under all conceivable scenarios.

  1. Following the right naming conventions is mandatory

When to come to naming the classes, functions and variables, you need to follow the below mentioned guidelines:
  • Make sure to capitalize the first letter of a particular class name 
  • Use capitalization for separating multi-word names
  • Capitalize the names of constants and use underscores for separating the words
  • Make sure the first letter of a particular function or variable name is in lowercase.
  • Pay attention to the correct use of abbreviations. For example, use max instead of maximum.

  1. Use of white spaces is necessary

Although white spaces are meaningless for compilers, you can use them for improving the code readability. For instance, you can opt for leaving three blank lines between the functions. Also, you can use individual blank lines within the functions for separating the critical code sections.

  1. Proper maintainability of code must be ensured

You need to write the code in a manner that it is quite straightforward for a different programmer to make moderations to its functionality or fix bugs. Make sure to keep the functions general with all the key values being marked as constants that can be changed in the desired manner. All in all, the code must be robust and capable of handling any kind of input, followed by delivering the expected result without crashing.

  1. Easy-to-understand comments must be included within the code

Comments should be meaningful and clearly explain everything about the software program. While the volume of comments doesn’t matter, quality does. You must use /* comments*/ style for writing the comments, ensuring that they are included towards the top of every source file. Additionally, you can also opt for including your name, the date on which code was written and a brief description of the actual purpose of using the program. You must ensure that the block comments precede a majority of functions along with a good description of the function’s purpose. However, you may also opt for omitting the block comments for some obvious functions. The format that needs to be followed for writing inline comments is //comments.


  1. Proper usage of function is necessary

Each and every function included within the code snippet must be short and capable of accomplishing a specific task. You need to consider functions as “black boxes” which are independent and can handle almost any type of input efficiently. Never forget the rule of thumb i.e. “Ten Line Rule” which means that a function which is typically longer than ten lines can do a lot more and needs to be simplified in the most refined way. Not to forget, any repeated segments of the code must be drafted into a separate function. Doing this will shorten the length of program and improve its readability by great bounds and leaps.

  1. Code needs to be indented well

Indentation plays a vital role in marking the control flow within a software program. Every new while, for, if or switch structure will introduce a block which has been indented in the best manner. This is feasible also in case the brackets have been omitted for the one line statements. For instance, in case of if statements, the corresponding else statements must be lined up.

Wrapping Up

Writing software programs can turn to be a fun activity if you’re well familiar with the accurate programming style. Hope the above post would have enabled you to get acquainted with the rules that can allow you to adhere to a fabulous programming style.

Clear values from People picker control

pplUser.Entities.Clear();

Friday, April 3, 2015

Sharepoint


How to change the row index by clicking image up and down

You can get the row ID from OnRowCommand.

 protected void gridview_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            DataTable dt = new DataTable();
            dt = Getdetails();                  ///Get existing details from gridview
            int index = Convert.ToInt32(e.CommandArgument);     ///Get row ID
            string Command = Convert.ToString(e.CommandName); ///Get Commandname
            DataRow selectedRow = dt.Rows[index];                        ///Get the selected Row
            DataRow newRow = dt.NewRow();                                 ///Create a new row
            newRow.ItemArray = selectedRow.ItemArray;   ///Insert selected row into new row
            dt.Rows.Remove(selectedRow);                                      ///Remove selected row
            if (Command == "Up")
            {
                dt.Rows.InsertAt(newRow, index - 1);                    
            }
            else if (Command == "Down")
            {
                dt.Rows.InsertAt(newRow, index + 1);
            }
            gridview.DataSource = dt;
            gridview.DataBind();                             ///Set details into grid again
            ViewState["WFtable"] = dt;
            Setdetails(dt);                
        }


I hope this will help you guys.

thanks.

Degrade your IE browser

Some of your contents may not support in IE browser higher versions.
So we can degrade to down versions by following:

In your master page you can see a tag like:
<head runat="server">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
</head>

In content you can change the version of your browser:
<meta http-equiv="X-UA-Compatible" content="IE=9" />

Get sharepoint SPList ID

Navigate to the SharePoint list using the browser.
Select the Settings + List Settings menu command.
Copy the Url from the browser address bar into Notepad. It will look something like:
http://moss2007/ProjectX/_layouts/listedit.aspx?List=%7B26534EF9%2DAB3A%2D46E0%2DAE56%2DEFF168BE562F%7D

Delete everying before and including “List=”.
Change “%7B” to “{”
Change all “%2D” to “-“
Chnage “%7D” to “}”
You are now left with the Id:

{26534EF9-AB3A-46E0-AE56-EFF168BE562F}

Simple Ways to become a best programmer...

1. Never ever duplicate code

Avoid duplicating code at all costs. If you have a common code segment used in a few different places, refactor it out into its own function. Code duplication causes confusion among your colleagues reading your code, it causes bugs down the line when the duplicated segment is fixed in one location and not the others and it bloats the size of your code-base and executable. With modern languages its become possible to get really good at this, for example here is a pattern that used to be hard to solve before delegates and lambdas came along:

/// <summary>
/// Some function with partially duplicated code
/// </summary>
void OriginalA()
{
DoThingsA();

// unique code

DoThingsB();
}

/// <summary>
/// Another function with partially duplicated code
/// </summary>
void OriginalB()
{
DoThingsA();

// unique code

DoThingsB();
}
But now we can refactor the shared part of both functions and rewrite using a delegate:

/// <summary>
/// Encapsulate shared functionality
/// </summary>
/// <param name="action">User defined action</param>
void UniqueWrapper(Action action)
{
DoThingsA();

action();

DoThingsB();
}

/// <summary>
/// New implmentation of A
/// </summary>
void NewA()
{
UniqueWrapper(() =>
{
// unique code
});
}

/// <summary>
/// New implementation of B
/// </summary>
void NewB()
{
UniqueWrapper(() =>
{
// unique code
});
}

2. Notice when you start distracting yourself

When you find yourself flicking to facebook or twitter instead of working on a problem its often a sign that you need to take a short break. Go grab a coffee away from your desk and talk to your colleagues for 5 minutes or so. Even though this seems counter intuitive, you will be more productive in the long run.

3. Don’t rush the solution out the door

When under pressure to produce a solution to a problem, or to fix a bug, its very easy to get carried away and find yourself rushing, or even missing out your usual crucial testing cycle completely. This can often result in more problems and will make you look less professional in the eyes of your boss and colleagues.

4. Test your finished code

You know what your code is supposed to do, and you’ve likely tested that it works, but you really need to prove it. Analyse all the potential edge cases and make a test which confirms that your code performs as expected under all possible conditions. If there are parameters, send values outside of the expected range. Send null values. If you can, show your code to a colleague and ask them to break it. Unit testing is a formalised approach to this.

5. Code review

Before you promote your code into source control, sit down with a colleague and explain exactly what your change does. Often just by doing this you’ll recognise mistakes in your own code without your colleague saying a word. It’s much, much more effective than just reviewing your own work.

6. Write less code

If you find yourself writing a lot of code to do something simple, you’re probably doing it wrong. A good example is the lowly boolean:

if (numMines > 0)
{
   enabled=true;
}
else
{
   enabled=false;
}
When you could just write:

enabled = numMines > 0;
The less code you write the better. Less to debug, less to refactor, less to go wrong. Use with moderation; readability is just as important, you don’t want to make your code less readable by doing this.

7. Strive for elegant code

Elegant code is highly readable and solves the problem at hand with the smallest amount of code and machine action possible. Its quite difficult to achieve elegant code in all circumstances but after programming for a while you start to get a feel for what it looks like. Elegant code cannot be improved by refactoring anything. It makes you happy to look at it. You are proud of it. For example here is what I consider to be an elegant way of computing the area of a convex polygon:

static public double GetConvexPolygonArea(Vector2[] vertices)
{
double area = 0;
for (int i = 0; i < vertices.Length; i++)
{
Vector2 P0 = vertices[i];
Vector2 P1 = vertices[(i + 1) % vertices.Length];

area += P0.Wedge(P1);
}

return area / 2;
}

8. Write self documenting code

Comments are a very important part of programming for obvious reasons, but self documenting code can be even better because it makes it possible to understand code just by reading it. Function and variable names can often be deftly chosen so that when put together with the language semantics the code becomes readable even to non programmers. For example:

void DamagePlayer(Player player, int damageAmount)
{
if (!player.m_IsInvincible && !player.m_IsDead)
{
player.InflictDamage( damageAmount );
}
}
Self documenting code is not a substitute for comments. Use comments to describe ‘why’, self documenting code describes ‘what’.

9. Don’t use magic numbers

Numbers just inserted into the code are bad practice because there is nothing to describe what they represent. This is compounded by duplication; where the same number is used in multiple different places in the code. One will get changed and the others missed leading to bugs. Always use a named constant to describe the value you want to represent, even if it is only used in one place.

10. Don’t do manual labour

Humans are very good at making mistakes when doing a series of actions. If you have a build deployment process which is more than one step long, you’re doing it wrong. Automate as much as possible, reduce the chance of human error. This is especially important with tasks which you perform a lot.

11. Avoid premature optimisation

When you start optimising part of your already functioning code you risk breaking the functionality. Optimisation should only be performed in response to performance analysis, hopefully carried out towards the end of a project. Optimising before this analysis stage wastes time and can introduce bugs.

Restricting Custom People Picker to only one Sharepoint group programatically

Refer the following script files in your page,     <!-- For People Picker -->     <script type="text/javascript" src...