Tag Archives: C#

How to execute a stored procedure within C# program – with Parameter, using Loop

csharp

Here is a sample :

using (SqlConnection conn = new SqlConnection(ConnectionString) {
    conn.Open();

    // 1.  create a command object identifying the stored procedure
    SqlCommand cmd  = new SqlCommand("CustOrder", conn);

    // 2. set the command object so it knows to execute a stored procedure
    cmd.CommandType = CommandType.StoredProcedure;

    // 3. add parameter to command, which will be passed to the stored procedure
    cmd.Parameters.Add(new SqlParameter("@CusID", custId));

    // execute the command
    using (SqlDataReader rdr = cmd.ExecuteReader()) {
        // iterate through results, printing each to console
        while (rdr.Read())
        {
            Console.WriteLine("Product: {0,-35} Total: {1,2}",rdr["ProductName"],rdr["Total"]);
        }
    }
}

Reading from web.config’s AppSettings in a SharePoint timer job

csharpSharePoint-2013

Well, this was not as straight-forward as i first thought. Why? Because the timer job does not run in the same App Domain as the web application. They are in two separate processes : W3WP.EXE  and OWSTIMER.EXE for the Web Application worker process and the SharePoint timer respectively.

So, how do you go about it?

Well, firstly you need to add reference to your timer job as follows (unless your using VB !):

using System.Configuration;
using System.Web.Configuration;

Reading AppSettings in Timer

using (SPSite site = new SPSite(“http://SiteCollectionUrl"))

        {

            Configuration config = WebConfigurationManager.OpenWebConfiguration(“/”, site.WebApplication.Name);

            returnconfig.AppSettings.Settings[“AppSettingKeyToRead”].Value;

        }

Admittedly, this solution is hard coding the Uri of the Site Collection, but this is purely for demonstration purposes.

Get absolute URL to listitem’s default display form – Sharepoint2013

csharp

Problem : 

I need to have an absolute URL of a listitem’s display form – currently I do it the following way:

On http://mydomain.com/:

item.ParentList.ParentWeb.Url.TrimEnd('/') //"http://mydomain.com"
+ "/" 
+ item.ParentList.DefaultDisplayFormUrl.Trim('/')//"Lists/WorkflowTasks/DispForm.aspx"
+ "?ID=" + item.ID //"?ID=1"

This gets me the correct URL, meaning http://mydomain.com/Lists/WorkflowTasks/DispForm.aspx?ID=1.

However this fails when my site collection is on a slightly more sophisticated host url, for examplehttp://mydomain.com/sites/secondsite/ – both methods from my code return the url containing the “/sites/secondsite/ part so I end up with http://mydomain.com/sites/secondsite/sites/secondsite/Lists/etc

How do I code it in a more reliable way?

Solution :

There are a couple of methods for this available in the object model without the need to handle the slashes etc yourself, one method using MakeFullUrl:

var fullUrl = item.ParentList.ParentWeb.Site.MakeFullUrl(item.ParentList.DefaultDisplayFormUrl);

Also

+ "?ID=" + item.ID //"?ID=1"

Resolved.

Using C# to read data from a SharePoint list using the SharePoint REST API

If you’re working with a C# application that is required to read information contained in a SharePoint list located on an external SharePoint farm, the SharePoint REST API can provide just the solution that you’re looking for.  Here is some sample code that you can use for accessing the information contained in that SharePoint list:

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Web.Script.Serialization;

namespace Sample
{
    public class SharePointListReader
    {
        ...

        public List<SharePointListItem> GetAllSPListItems()
        {
            List<SharePointListItem> posts = new List<SharePointListItem>();
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://webapp/site/_api/web/lists/getbytitle('listName')/items?$select=id,Title");
            request.Method = "GET";
            request.Accept = "application/json;odata=verbose";
            request.ContentType = "application/json;odata=verbose";
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;
            WebResponse response = request.GetResponse();
            Data data = null;

            // Read the returned posts into an object that can be consumed by the calling application
            using (response)
            {
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    try
                    {
                        string jSON = reader.ReadToEnd();
                        data = serializer.Deserialize(jSON);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format("An error occurred when reading the list items from SharePoint: {0}; {1}", ex.Message, ex.StackTrace));
                    }
                }
            }
            foreach (SharePointListItem post in data.d.results)
            {
                posts.Add(post);
            }
            return posts;
        }
    }

    public class Data
    {
        public Results d { get; set; }
    }

    public class Results
    {
        public SharePointListItem[] results { get; set; }
    }

    public class SharePointListItem
    {
        public string id { get; set; }
        public string Title { get; set; }
    }
}

Regular Expressions Example (c#) – CSharp

csharp

The following example shows the use of Regular Expresssions in C#.This program has basic validation scripts for validation easily useable in all programs.

/*
<HowToCompile>
csc /r:System.Text.RegularExpressions.dll,System.dll Validation.cs
</HowToComplie>
*/
using System.Text.RegularExpressions;
using System;
class Validation
{
public static void Main()
{
String strToTest;
Validation objValidate=
new Validation();
Console.Write(“Enter a String to Test for Alphabets:”);
strToTest=Console.ReadLine();
if(objValidate.IsAlpha(strToTest))
{
Console.WriteLine(“{0} is Valid Alpha String”,strToTest);
}
else
{
Console.WriteLine(“{0} is not a Valid Alpha String”,strToTest);
}
}
// Function to test for Positive Integers.
public bool IsNaturalNumber(String strNumber)
{
Regex objNotNaturalPattern=
new Regex(“[^0-9]”);
Regex objNaturalPattern=
new Regex(“0*[1-9][0-9]*”);
return !objNotNaturalPattern.IsMatch(strNumber) &&objNaturalPattern.IsMatch strNumber);
}
// Function to test for Positive Integers with zero inclusive
public bool IsWholeNumber(String strNumber)
{
Regex objNotWholePattern=
new Regex(“[^0-9]”);
return !objNotWholePattern.IsMatch(strNumber);
}
// Function to Test for Integers both Positive & Negative
public bool IsInteger(String strNumber)
{
Regex objNotIntPattern=
new Regex(“[^0-9-]”);
Regex objIntPattern=
new Regex(“^-[0-9]+$|^[0-9]+$”);
return !objNotIntPattern.IsMatch(strNumber) &&
objIntPattern.IsMatch(strNumber);
}
// Function to Test for Positive Number both Integer & Real
public bool IsPositiveNumber(String strNumber)
{
Regex objNotPositivePattern=
new Regex(“[^0-9.]”);
Regex objPositivePattern=
new Regex(“^[.][0-9]+$|[0-9]*[.]*[0-9]+$”);
Regex objTwoDotPattern=
new Regex(“[0-9]*[.][0-9]*[.][0-9]*”);
return !objNotPositivePattern.IsMatch(strNumber) &&
objPositivePattern.IsMatch(strNumber) &&!objTwoDotPattern.IsMatch(strNumber);
}
// Function to test whether the string is valid number or not
public bool IsNumber(String strNumber)
{
Regex objNotNumberPattern=
new Regex(“[^0-9.-]”);
Regex objTwoDotPattern=
new Regex(“[0-9]*[.][0-9]*[.][0-9]*”);
Regex objTwoMinusPattern=
new Regex(“[0-9]*[-][0-9]*[-][0-9]*”);
String strValidRealPattern=”^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$”;
String strValidIntegerPattern=”^([-]|[0-9])[0-9]*$”;
Regex objNumberPattern =
new Regex(“(” + strValidRealPattern +”)|(” +
trValidIntegerPattern + “)”);
return !objNotNumberPattern.IsMatch(strNumber) &&!objTwoDotPattern.IsMatch
strNumber) && !objTwoMinusPattern.IsMatch(strNumber) && objNumberPattern.IsMatch(strNumber);
}
// Function To test for Alphabets.
public bool IsAlpha(String strToCheck)
{
Regex objAlphaPattern=
new Regex(“[^a-zA-Z]”);
return !objAlphaPattern.IsMatch(strToCheck);
}
// Function to Check for AlphaNumeric.
public bool IsAlphaNumeric(String strToCheck)
{
Regex objAlphaNumericPattern=
new Regex(“[^a-zA-Z0-9]”);
return !objAlphaNumericPattern.IsMatch(strToCheck);
}
}

There is another simple way to perform these validation think of it while the next article comes.

Free SharePoint 2013 eBooks

SharePoint-2013

Looking for new and free SharePoint reference books? This eBook collection will certainly satisfy your appetite for improvement in SharePoint technology field. There’s plenty of valuable tutorials here to keep you busy reading for a while. Be sure to grab few of these eBooks, check more related goodies at the bottom and don’t forget to tell us what you think.

SharePoint 2013 WCM Advanced Cookbook

Buy the paper bookSharePoint 2013 Server includes new and improved features for web content management that simplify how you design publishing sites, and enhances the authoring and publishing processes of organizations.

With SharePoint 2013 WCM Advanced Cookbook, you will learn about a full-fledged web content management system using Microsoft SharePoint Server 2013.

Publisher: Packt Publishing

By: John Chapman

Published Year: 2014
Pages: 436
Download PDF (7 MB)
Buy the paper book version


SharePoint 2013 Branding and User Interface Design

Buy the paper bookIf you are planning, designing, and launching your brand using SharePoint, this book and author trio will walk you through everything you need to know in an understandable and approachable way.
This visual book provides step-by-step instructions in a simple and striking format that focuses on each of the tasks you will face in your own branding project.

Publisher: Wrox
By: Randy Drisgill, John Ross, Paul Stubbs
Published Year: 2013
Pages: 432
Download PDF (54 MB)
Buy the paper book version


Pro SharePoint 2013 App Development

Buy the paper bookUsing step-by-step tutorials, author Steve Wright creates a sample SharePoint app throughout the course of the book, and you can walk with him through the entire lifecycle of a SharePoint app.

Publisher: Apress
By: Steve Wright
Published Year: 2013
Pages: 432
Download PDF (15.5 MB)
Buy the paper book version


Microsoft SharePoint 2013 App Development

Buy the paper bookLed by two SharePoint experts, you’ll learn development techniques such as building app lists, creating event handlers, and the major classes in the object model that provide access to content stored in SharePoint.

Publisher: Microsoft Press
By: Scot Hillier, Ted Pattison
Published Year: 2013
Pages: 202
Download PDF (34 MB)
Buy the paper book version


Pro SharePoint 2013 Branding and Responsive Web Development

Buy the paper bookPro SharePoint 2013 Branding and Responsive Web Development is the definitive reference on the technologies, tools, and techniques needed for building responsive websites and applications with SharePoint 2013. The book focuses on solutions that provide the best browser experience for the myriad of devices, browsers, and screen orientations and resolutions.

Publisher: Apress
By: Eric Overfield, Rita Zhang, Oscar Medina, Kanwal Khipple
Published Year: 2013
Pages: 580
Download PDF (26 MB)
Buy the paper book version


Microsoft SharePoint 2013: Designing and Architecting Solutions

Buy the paper bookDetermine the best design for your SharePoint implementation by gaining a deeper understanding of how the platform works. Written by a team of SharePoint experts, this practical guide introduces the Microsoft SharePoint 2013 architecture, and walks you through design considerations for planning and building a custom SharePoint solution. It’s ideal for IT professionals, whether or not you have experience with previous versions of SharePoint.

Publisher: Microsoft Press
By: Shannon Bray, Miguel Wood, Patrick Curran
Published Year: 2013
Pages: 488
Download PDF (55 MB)
Buy the paper book version


SharePoint 2013 User’s Guide, 4th Edition

Buy the paper bookMicrosoft SharePoint 2013 provides a collection of tools and services you can use to improve user and team productivity, make information sharing more effective, and facilitate business decision–making processes. In order to get the most out of SharePoint 2013, you need to understand how to best use the capabilities to support your information management, collaboration, and business process management needs. The SharePoint 2013 User’s Guide is designed to provide you with the information you need to effectively use these tools.

Publisher: Apress
By: Anthony Smith
Published Year: 2013
Pages: 536
Download PDF (53 MB)
Buy the paper book version


Microsoft SharePoint 2013 Inside Out

Buy the paper bookYou’re beyond the basics, so dive right into SharePoint 2013—and really put your business collaboration platform to work! This supremely organized reference packs hundreds of timesaving solutions, troubleshooting techniques, and workarounds. It’s all muscle and no fluff. Discover how the experts facilitate information sharing across the enterprise—and challenge yourself to new levels of mastery.

Publisher: Microsoft Press
By: Darvish Shadravan, Penelope Coventry, Thomas Resing, Christina Wheeler
Published Year: 2013
Pages: 904
Download PDF (124 MB)
Buy the paper book version


Pro SharePoint 2013 Administration, 2nd Edition

Buy the paper bookPro SharePoint 2013 Administration is a practical guide to SharePoint 2013 for intermediate to advanced SharePoint administrators and power users, covering the out-of-the-box feature set and capabilities of Microsoft’s collaboration and business productivity platform.

Publisher: Apress
By: Robert Garrett
Published Year: 2013
Pages: 655
Download PDF (32 MB)
Buy the paper book version


Professional SharePoint 2013 Administration

Buy the paper bookThe new iteration of SharePoint boasts exciting new features. However, any new version also comes with its fair share of challenges and that’s where this book comes in. The team of SharePoint admin gurus returns to presents a fully updated resource that prepares you for making all the new SharePoint 2013 features work right. They cover all of the administration components of SharePoint 2013 in detail, and present a clear understanding of how they affect the role of the administrator.

Publisher: Wrox
By: Shane Young, Steve Caravajal, Todd Klindt
Published Year: 2013
Pages: 840
Download PDF (56 MB)
Buy the paper book version


Practical SharePoint 2010 Branding and Customization

Buy the paper bookWith Practical SharePoint 2010 Branding and Customization, SharePoint branding expert Erik Swenson cuts through the fluff and discusses accessible, easy-to-understand consulting and processes to create aesthetically pleasing, highly usable branded and customized SharePoint websites, both internally and externally. Designed to be a quick reference, how-to guide that lets you dive straight into the task at hand, you’ll find this book’s attention to detail and pragmatism make it an attractive companion during your branding experience.

Publisher: Apress
By: Erik Swenson
Published Year: 2013
Pages: 368
Download PDF (7 MB)
Buy the paper book version


Professional SharePoint 2013 Development

Buy the paper bookA team of well-known Microsoft MVPs joins forces in this fully updated resource, providing you with in-depth coverage of development tools in the latest iteration of the immensely popular SharePoint. From building solutions to building custom workflow and content management applications, this book shares field-tested best practices on all aspect of SharePoint 2013 development.

Publisher: Wrox
By: Reza Alirezaei, Brendon Schwartz, Matt Ranlett, Scot Hillier, Brian Wilson, Jeff Fried, Paul Swider
Published Year: 2013
Pages: 816
Download PDF (47 MB)
Buy the paper book version


Exploring Microsoft SharePoint 2013

Buy the paper bookYour guide to the most significant changes in SharePoint 2013. Discover what’s new and what’s changed in SharePoint 2013—and get a head start using these cutting-edge capabilities to improve organizational collaboration and effectiveness.

Led by a Microsoft MVP for SharePoint, you’ll learn how to take advantage of important new features and functionality, including app development, collaborative social enterprise tools, enhanced versioning, themes, improved search, and an extended client object model.

Publisher: Microsoft Press
By: Penelope Coventry
Published Year: 2013
Pages: 200
Download PDF (17 MB)
Buy the paper book version


SharePoint 2013 For Dummies

Buy the paper bookSharePoint Portal Server is an essential part of the enterprise infrastructure for many businesses. Building on the success of previous versions of SharePoint For Dummies, this new edition covers all the latest features of SharePoint 2013 and provides you with an easy-to-understand resource for making the most of all that this version has to offer. You’ll learn how to get a site up and running, branded, and populated with content, workflow, and management. In addition, this new edition includes essential need-to-know information for administrators, techsumers, and page admins who want to leverage the cloud-hosted features online, either as a standalone product or in conjunction with an existing SharePoint infrastructure.

Publisher: Wiley
By: Ken Withee
Published Year: 2013
Pages: 384
Download PDF (32 MB)
Buy the paper book version

If you are unable to download email me

Ref : topsharepoint

Resolving VS 2010 solution deployment issues for SharePoint 2010 projects

In my new SharePoint 2010 book, I touch base on variety of deployment approaches; in this article I wanted to focus on Visual Studio 2010 feature allowing to deploy SharePoint 2010 solutions right to the portal. However, you haven’t configured your development environment properly – you will run into issues. Here I’m talking about the following error:

Error occurred in deployment step ‘Recycle IIS Application Pool’: The local SharePoint server is not available. Check that the server is running and connected to the SharePoint .

Or this:

Error occurred in deployment step ‘Recycle IIS Application Pool’: Cannot connect to the SharePoint site: http://localhost/. Make sure that this is a valid URL the SharePoint site is running on the local computer. If you moved this project to a new computer or if the URL of the SharePoint site has changed since you created the project, update the Site URL property of the project

Visual studio uses the following process to deploy your solution: vssphost4.exe
Open your task manager and find the process in the list; take a note of the User Nameunder which this process is running, let’s say it’s myadmin_account

Now, open your SQL Management Studio and ensure this Username is added as a DBOWNER to the following databases:

SharePoint_Config
SharePoint_AdminContent_[guid]
SharePoint Site Content DB

sql-permissions

Close and Open your Visual Studio again, this will ensure the service is recycled; this should fix above deployment error. If you’re still having same issue, End the process in taskmanager and then VS 2010.

Good luck!

Ref : Sharemuch

Jquery datepicker problem on date select in IE – ‘length’ is null or not an object

I am posting a wonderful post on Jquery datepicker.
Because I am using Jquery in ASP.NET application, I added a regular expression for date to validate whether user entered date is valid or not. Because of adding the validation on the text box, whenever I select a date from datepicker, the datepicker events are firing like onselect, change etc.. So, generally what validation framework is doing, whenever some event fires on the page, validations will execute. The same thing happening here. Whenever I change or select date from the date picker, it will fire some events and at the same time validation framework trying to validate the validations. But, it is not the right event to do validations. So, always we will get the exception at “vals.length” in a for loop of the built-in code. vals is the object of all the validators on the page. It always fails to load in Jquery date picker event trigger, because it is not the right event for validation. And the result is vals is undefined, you always get exception at vals.length as “length is null or not an object”. I think now you got very clear idea of why it is happening. Now, move to the next step i.e. solution for it.

Solution is very simple, I read all the documentation of Jquery datepicker and found an event named onSelect. So, whenever I select date this is the event firing. So, there I got a clue and started thinking towards it. And below is the result.

$(“.datepicker”).datepicker({ onSelect:function(){}});

In your datepicker initialization statement add onSelect event which don’t do anything means empty function as shown above. There problem solved. Isn’t a good find? Please let me know your thoughts on this.

Ref : praveenbattula

Session TimeOut manually in web.config

if you would like to set Session TimeOut manually in web.config as 24 hours.

Solution : 

Use timeout in web.config, can also use timespan–20 minutes is default, also The timeout attribute cannot be set to a value that is greater than 525,601 minutes (1 year) for the in-process and state-server modes.

<sessionState
mode=”[Off|InProc|StateServer|SQLServer|Custom]”
 timeout=”number of minutes”…………

……/>

If you are using ASP.NET 2.0, use have to check in the IIS.

Open the IIS, click on the Application Pools, Select the Application pool for your application.

Right Click on that, Select Properties.

In the Performance tab, Set the idle timeout as your desired minutes for “shutdown worker processes after being idle for ….. minutes”.

Hope this works.

Using jQuery validation in a sharepoint web part

As we all know, a SharePoint page can only have one <form > tag in it. As anyone who wanted to use jQuery validation knows, the validation script needs to run on a form tag.
So how do I use the validation code in a sharepoint web part?

The answer is to run the script against the form that already exists in the page. For example, I had to write a web part with an email address field, and wanted to help the users by validating the text they entered is a valid email address on the client side (I also validate on the server side – just in case someone is running a browser with no script). This is the “Render” override code that I used:

txtEmailAddress1.CssClass = “required email”;

       base.Render(writer);
       if (SPContext.Current.FormContext.FormMode != Microsoft.SharePoint.WebControls.SPControlMode.Edit)
       {
              writer.Write(@"<script>
$().ready(function() {
    $(""#" + this.Page.Form.ClientID + @""").validate();
});
</script>
");
       }

As you can see, I am adding a css class of type “required email” for the text box, and then telling the form on the page to validate using the jquery validation plug in. This of course assumes you added the references to the jquery scripts to the page…which you may want to do as part of the web part (override oninit, and registerclientscriptblock) or as part of the master page (if you expect a lot of web parts to use it).

As for the “if (SPContext.Current.FormContext.FormMode != Microsoft.SharePoint.WebControls.SPControlMode.Edit)” line – you have to be careful that your validation does not prevent you from editing the page. For example, if you remove that “if”, you will not be able to change the properties of any web part on the page without first entering a valid email address in the textbox!

Ref : Sharepoint Tips And Tricks