Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

August 07, 2014

How to Covert string to valid file name format, get valid file name, file name validation

This is general question that How to Covert string to a file name to save on drive or some location. our Keyboard have so many special characters and looking for more symbols in our keyboard,
That's good for users but for developers its headache coz out of those characters few are allowed in file name,
That makes issue sometime while reading/writing or creating file.

if user entered some incorrect word so instead of giving error to end user we can replace all those special characters by any specific character like I have done with char '_' underscore,
The file name is very important in terms of search or crawl files/file name.


So to make it simple, easy and working I have would prefer to use below way to do so.....


C# Code:
private string ConverToStandardFileName(string accountName)
        {
            foreach (char c in System.IO.Path.GetInvalidFileNameChars())
            {
                accountName = accountName.Replace(c, '_');
            }
            return accountName;
        }


That can be used in any aspx or C#/Windows appliaction. Other ways are also suggested over internet like .Replace("%","").Replace("&",""),Replace("*","") etc....


Other ways/suggestion are welcome, also shared you findings on this.


--

Regards,
Praveen Pandit
Keep Sharing Knowledge!!

May 04, 2014

SharePoint 2013 auto fill people picker, auto fill people editor in application page (aspx) C#

Microsoft always comes with some new and more user friendly features in every new version. Well this client people picker (which is auto fill by user name, email or login id) new and simple control introduced in SharePoint 2013, that will save lot of time of ours.

instead of using below people picker of sharepoint 2010

<SharePoint:PeopleEditor ID="spPeoplePicker" runat="server" Width="350" SelectionSet="User" />

and setting javascript we can use  PeopleEditor to make it easy and faster for end user we can use below control in SP2013

aspx syntax :
<SharePoint:ClientPeoplePicker ValidationEnabled="true" ID="pplDemo" runat="server" VisibleSuggestions="5" AutoFillEnabled="True" AllowEmailAddresses="true" Rows="1" AllowMultipleEntities="false" CssClass="ms-long ms-spellcheck-true" Height="85px"  />



C# Code to get SPUser:
if( pplDemo.ResolvedEntities.Count > 0)
{
SPUser oUser = oWeb.SiteUsers[((PickerEntity)pplDemo.ResolvedEntities[0]).Key];

                         if (oUser != null)
                         {
                              // do your stuff.
                         }
}

C# Code to Set User to Client People Picker control:
 
 pplDemo.InitialUserAccounts = "UserEmail1";
 



Thanks,
remaining getting and saving values in SharePoint is same as earlier.

You can Share your findings or issue here.


--
Thanks,
Praveen Pandit

April 24, 2014

SharePoint how to check user, CurrentUser is in perticuler site group

You wants to check if CurrentUser or particular User / SPUser is present in specific site's permission group or not,
Usually site have three groups Visitors, Members and Owners. If you have create another group and wants to check if particular user is present is that group for some validation so you can refer below code sample,

* Assuming you have basic knowledge of SharePoint coding.



Code:
private bool UserPresentInGroup(string groupName)
        {
            bool isAdmin = false;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                { // User may not have permission to see site group or Group members....
                    using (SPSite oSite = new SPSite(strWebUrl))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            SPGroup oUserGroup = oWeb.Groups[groupName];
                            foreach (SPUser item in oUserGroup.Users)
                            {
                                if (item.LoginName == currentUser.LoginName)
                                {
                                    isAdmin = true;
                                }
                            }
                        }
                    }
                });
            }
            catch (Exception exp)
            {}// Catch exception

If you wants to check user from Sites default Visitor, Member or Owner Group you can directly get group by below property
  • SPWeb.AssociatedVisitorGroup
  • SPWeb.AssociatedMemberGroup
  • SPWeb.AssociatedOwnerGroup
instead of  oUserGroup.


--
Thanks,
Praveen Pandit

March 16, 2014

SharePoint read csv or xml file from wsp / solution of _layouts file.





SharePoint how to read any csv or xml file in webpart using C# code.

Usually we doesn’t required this scenario, but in some cases you want to keep any config data or aby xml data apart from typical SPList you have to create a Config or default setting file that cabn be access by your C# code,



Finally you want to get file that you have mapped in _layouts so using StreamReader / Stream or File.Open(); it needs file’s absolute path and if you are in SharePoint wsp so that makes you to follow approach like below,

In file path string pass below way


SharePoint – C# get xml file from _layouts
Server.MapPath(“/_layouts/mySolutionFolder/myXml.xml”);
Read external file in SharePoint C#







Thanks,

Praveen Pandit




February 20, 2014

SharePoint How to get SPUser from list item C#



How to get SPUser from list item, SharePoint list item get user, how to get created, modified, Author or Editor from sharepoint list, how to get LoginName or Email of User from list,

Well there is another way to get Web. EnsureUser(“User”); it returns SPUser object as well it adds user in site directly if do not already that web user, another way to get it write a function that return SPUser object,   

*Assuming that you are aware how to get SPWeb and List then List item,

SPUser oUserSubmittedBy = GetSPUser(oItem, “fieldDisplay Name”);

Here is the function body.



Code:
protected SPUser GetSPUser(SPListItem item, string user)

        {

            SPUser oUser = null;

            SPFieldUserValue userValue = new SPFieldUserValue(item.Web, Convert.ToString(item[user]));

            if (userValue != null)

            {

                oUser = userValue.User;

            }

            return oUser;

        }


And once you get object you can get Name, email and login name

oUserSubmittedBy.LoginName
oUserSubmittedBy.Name
oUserSubmittedBy.Email…. etc..



--
Regards,
Praveen Pandit

January 09, 2014

Best way to get Query string from url in SharePoint / Asp .Net / webApps



The easiest and well know way is to Request.QueryString[“name”]; but many times to get null exception we should check query string and return in appropriate format. Below I have created a private int variable and protected property of it. You can have a look on below code.


protected int ItemID
        {
            get
            {
                if (Request.QueryString["itemId"] != null && Request.QueryString["itemId"].Length > 0)
                {
                    return Convert.ToInt32(Request.QueryString["itemId"]);
                }
                else return 0;
            }
        }



You can Share your findings or issue or Discussion below.

--
Regards,
Praveen Pandit