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

Sunday, 28 February 2021

How to get the strong name of your assembly by adding an External Tool?

Introduction

Solution

This tip will make it easy for you to get that assembly name right within Visual Studio.

  • In Visual Studio, Go to Tools –>  External Tools.


  • Click on “Add” to add a tool, and put in the following values:
    • Title: Strong Name
    • Command: Powershell.exe
    • Arguments: -command "[System.Reflection.AssemblyName]::GetAssemblyName(\"$(TargetPath)\").FullName"
    • Check “Use Output Window”
    • Uncheck everything else – here’s how it should look -

  


  • Right Click on your solution and Clean Your Project solution.

 


  • Now, Right Click on your solution and build Your Project solution.

 


  • That’s it, now in your project, Visit Tools –> Strong Name, and in the output window, it will give you the assembly name like this –>

 ProjectName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e3d610b32dbba675  

 




Please let me know if you face any issues.

Thursday, 21 June 2018

SharePoint List useful details

Recently get change to go back to development and done some basic level of errors. So here is my knowledge for list level that I want to share:

I have a library with internal name "LiteracyResources" and the display name was updated to "Literacy Resources" (a space between two words). I need to bind documents to a grid and click on name I need to download it. Simple requirement.

The issue I face was when I try to get list I need to use name with space. And If I want to get any file url for download, I need to create it and that should use internal name of the list. Otherwise your download url won't work.

So to get internal name of list, I use "list.RootFolder.Name".

below is the code that I use for this:

Code:

SPList resourcelist = null;

 using (SPSite siteCol = new SPSite(SPContext.Current.Site.Url))
                {
                    SPWeb web = siteCol.RootWeb;
                    {
                        SPList list = web.Lists.TryGetList(Constants.LibNameLiteracy); // Here we need to //use library name with space 
                     
                        SPListItemCollection items = list.GetItems();
                        if (items.Count > 0)
                        {
                            dt = items.GetDataTable();
                            dt.Columns.Add(Constants.ColNameDocURL, typeof(string));
                            for (int itemcount = 0; itemcount < dt.Rows.Count; itemcount++)
                            {
                                if (web.Url.EndsWith("/"))
{ // here we use internal name 
                                    dt.Rows[itemcount][Constants.ColNameDocURL] = web.Url + list.RootFolder.Name + "/" + Convert.ToString(dt.Rows[itemcount][Constants.ColNameFileLeafRef]);
{
                                else {
                                    dt.Rows[itemcount][Constants.ColNameDocURL] = web.Url + "/" + list.RootFolder.Name + "/" + Convert.ToString(dt.Rows[itemcount][Constants.ColNameFileLeafRef]);
}
                                dt.AcceptChanges();
                            }
                        }
                    }
                }

                allYearsGrid.DataSource = dt;
                allYearsGrid.DataBind(); 

Tuesday, 3 October 2017

QueryString-error-The name request does not exist in the current context

After a long time, I was working on .net project. Basically I forget all basic things and on of them was how to use Query String. So here is blog for those who face issue same as me when user querystring and get error :

The name request does not exist in the current context

Below was code I was using:

if (!String.IsNullOrWhiteSpace(Convert.ToString(Request.QueryString["Source"])))
                {
                    Context.Response.Redirect(Convert.ToString(Request.QueryString["Source"]));
                }


Solution:

Solution is very easy. First, you need to add below reference in your code:

using System.Web;

This will allow you to use "HttpContext.Current" in your code. So your final solution should look like below:

if (HttpContext.Current != null && !String.IsNullOrWhiteSpace(Convert.ToString(HttpContext.Current.Request.QueryString["Source"])))
                {
                    Context.Response.Redirect(Convert.ToString(HttpContext.Current.Request.QueryString["Source"]));
                }

Thursday, 4 February 2016

How to add separator to string at every N characters?

I was having a strange requirements last days and one of them is this one:

we have a string and we want to add a separator after 8 digit.

Here is the post which help me to achieve the my solution:
http://stackoverflow.com/questions/9932096/add-separator-to-string-at-every-n-characters

Solution:

here is the solution that worked for me:

string x = "111111110000000011111111000000001111111100000000";
output should be :
"11111111,00000000,11111111,00000000,11111111,00000000,"

C# : Regex.Replace(myString, ".{8}", "$0,");

Javascript:

"111111110000000011111111000000001111111100000000".replace(/(.{8})/g,"$1,")


Error Occurred in Deployment step 'Recycle IIS Application Pool'

Currently we have moved our development environment and one common error I faced after moving them was :
Error occurred in deployment step 'Recycle IIS Application Pool':
<nativehr>0x80070005</nativehr><nativestack></nativestack>Access denied

Solution:

Original Post: http://stackoverflow.com/questions/21278281/error-occurred-in-deployment-step-recycle-iis-application-pool

Here are the steps that worked for me:

  1. Go to Central Administration site
  2. Navigate to the Manage Web Applications page
  3. Click on the web application that hosts the site you are trying to deploy to
  4. Click the User Policy ribbon item.
  5. Add your windows account to the list of users with the Full Control permission.

Monday, 9 November 2015

check which control fired post back at pageload

If you want to know which controlled fired post back at page load, here is some sample code.

1) for link button:

string ctrlname = Page.Request.Params["__EVENTTARGET"];
                        if ((!string.IsNullOrWhiteSpace(ctrlname)) && ctrlname.EndsWith("lnkSelect"))
                        {
                            LinkButton lnk1 = Page.FindControl(ctrlname) as LinkButton;
                         }

2) for Image button and Button:

protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
            Response.Write(getPostBackControlName());
    }

   
    private string getPostBackControlName()
    {
        Control control = null;
        //first we will check the "__EVENTTARGET" because if post back made by       the controls
        //which used "_doPostBack" function also available in Request.Form collection.
        string ctrlname = Page.Request.Params["__EVENTTARGET"];
        if (ctrlname != null && ctrlname != String.Empty)
        {
            control = Page.FindControl(ctrlname);
        }
        // if __EVENTTARGET is null, the control is a button type and we need to
        // iterate over the form collection to find it
        else
        {
            string ctrlStr = String.Empty;
            Control c = null;
            foreach (string ctl in Page.Request.Form)
            {
                //handle ImageButton they having an additional "quasi-property" in their Id which identifies
                //mouse x and y coordinates
                if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
                {
                    ctrlStr = ctl.Substring(0, ctl.Length - 2);
                    c = Page.FindControl(ctrlStr);
                }
                else
                {
                    c = Page.FindControl(ctl);
                }
                if (c is System.Web.UI.WebControls.Button ||
                         c is System.Web.UI.WebControls.ImageButton)
                {
                    control = c;
                    break;
                }
            }
        }
        return control.ID;

    }
}

Tuesday, 3 November 2015

General Code Review

Code Review :- General 
1. Remove the  commented code
2. Variable name should not be contain "_".
3. Query should be in separate class.
4. Use Common log error when handle the exception
5. Use String.isNullorWhiteSpace instead of String.isNullorEmpty
6. Use Using Statement for variable scope should be limited.
7.  Remove unnecessary if ... else ...

e.g.   if (dtTasksAll != null && dtTasksAll.Rows.Count > 0)
{
            gv.DataSource = dtTasksAll;
            gv.DataBind();
        }
        else
        {
gv.EmptyDataText = "No New Tasks found";
lblviewimg.Visible=false;
gv.DataSource = dtTasksAll;
gv.DataBind();
}

Optimized code :-
if(dtTasksAll == null)
{
gv.EmptyDataText = "No New Tasks found";
lblviewimg.Visible=false;
}
gv.DataSource = dtTasksAll;
gv.DataBind();

8. Terminate loop as soon as possible

e.g.
foreach (SPUser user in group.Users)
{
if (!string.IsNullOrEmpty(user.Email))
{
MailTo += MailTo == string.Empty ? user.Email : "," + user.Email;
}
}

Optimized code :-
foreach (SPUser user in group.Users)
{
if (string.IsNullOrWhiteSpace(user.Email)) Continue;
MailTo += MailTo == string.Empty ? user.Email : "," + user.Email;
}

Friday, 23 October 2015

Pass function Parameter & string value in string builder function.

Recently I was working with dynamic controls where I got in to a small issue where I need to provide parameters in JavaScript function. I tried lots of things , But here is the approach which solved my issue:

Example:

sb.AppendLine(@"<li><a href='#' onclick='FunctionTest(" + "\"" + string1 + "\" ,\"" + string2+ "\"," + int1 + ")'>" + string4 + "</a></li>");

Explanation:

We can divide above code in following parts:

1) sb.AppendLine(@"<li><a href='#' onclick='FunctionTest(" completes first string
2) + "\"" + string1 + "\" Adds " string1 " (string parameter) to function
3) " + int1 + " Adds int1 (integer parameter) to function
4) )'>" + string4 + "</a></li>"); Complete remaining string

Monday, 25 May 2015

Service error - "Memory gates checking failed because the free memory (xxxxx bytes) is less than 5% of total memory."

I was testing few service scripts when I encounter with this error -

"Memory gates checking failed because the free memory (xxxxxxxxx bytes) is less than 5% of total memory."

Resolution:

Adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element or your project config file.

The easiest way just add this into your web.config

<system.serviceModel>
<serviceHostingEnvironment minFreeMemoryPercentageToActivateService="0" />

</system.serviceModel>

Reference:
1) http://support.ge-ip.com/support/index?page=kbchannel&id=23301025e79bf210148caf0ad63007ec5
2) http://stevemannspath.blogspot.in/2012/07/sharepoint-2013-opening-memory-gates.html

Monday, 16 February 2015

Filter Data Table in C#.

In general code data binding , most times we need to bind data through data table. In some case we might require to filter data. There are Three different ways you can filter data in data table.

  1. Using For loop. 
  2. Using Data view.
  3. Using Linq query.

Here we will see the demo for last two options.

A. Using data view.

Code Example:

DataTable  dt = GetDataTable(); //Get data in datatable
DataView dv = dt.DefaultView;
dv.RowFilter ="id=10"; // Filter column = filter value
dv.Sort =  "id"; //sort column (Desc for descending order)


repeater1.datasource = dv;
repeater1.databind();

The problem with data view is if the filter column does not match, it will return you the full table instead of null.

Helpful Blog :

B. Using Linq query

Code Example: 


DataTable dtdata = GetDataTable(); //Get data in datatable
                 
                        var data = (from dt in dtdata.AsEnumerable()
                                    where Convert.ToString(dt["id"]) == "10" 
                                    select dt
                                   ).ToList();
                        if (data.Count > 0)
                        {
                            DataTable dtlevel3 = new DataTable();
                            dtlevel3 = data.CopyToDataTable();
                            repeater1.datasource = dv;
                            repeater1.databind();
                        }

For c# code you will require to add namespace : using  System.Linq; 
For Sharepoint you need to add namespace : using Microsoft.SharePoint.Linq;

Wednesday, 7 January 2015

different ways of extracting different parts of URL

Here is the sample how you can have different ways of extracting different parts of URL

EXAMPLE (Sample URL)

http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QuerrString2=2

CODE

Response.Write("<br/> " + HttpContext.Current.Request.Url.Host);
Response.Write("<br/> " + HttpContext.Current.Request.Url.Authority);
Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsolutePath);
Response.Write("<br/> " + HttpContext.Current.Request.ApplicationPath);
Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsoluteUri);
Response.Write("<br/> " + HttpContext.Current.Request.Url.PathAndQuery);
OUTPUT

localhost
localhost:60527
/WebSite1test/Default2.aspx
/WebSite1test
http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QuerrString2=2
/WebSite1test/Default2.aspx?QueryString1=1&QuerrString2=2


If you have something like this:

"http://localhost:1234/Default.aspx?un=asdf&somethingelse=fdsa"
or like this:

"https://www.something.com/index.html?a=123&b=4567"
and you only want the part that a user would type in then this will work:

String strPathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
String strUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(strPathAndQuery, "/");
which would result in these:

"http://localhost:1234/"
"https://www.something.com/"

Thursday, 20 November 2014

Linq query to datatable conversion

Recently I have encounter with Linq after a long time and I was required to convert linq result in to datatable. It take a while but I found the method i used in past. I hope it will help you too.

 1. use AsEnumerable() in your query.and you will be good to get a function CopyToDataTable() to get datatable.
  Example:
var query =
    from order in orders.AsEnumerable()
    join detail in details.AsEnumerable()
    on order.Field<int>("SalesOrderID") equals
        detail.Field<int>("SalesOrderID")
    where order.Field<bool>("OnlineOrderFlag") == true
    && order.Field<DateTime>("OrderDate").Month == 8
    select new
    {
        SalesOrderID =
            order.Field<int>("SalesOrderID"),
        SalesOrderDetailID =
            detail.Field<int>("SalesOrderDetailID"),
        OrderDate =
            order.Field<DateTime>("OrderDate"),
        ProductID =
            detail.Field<int>("ProductID")
    };

DataTable orderTable = query.CopyToDataTable(); 
 
Original Source : http://msdn.microsoft.com/en-us/library/bb386921%28v=vs.110%29.aspx

2. use this coustom method to get datatable

 Example:
public DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query)
{
     if (query == null)
     {
          throw new ArgumentNullException("query");
     }
    
     IDbCommand cmd = ctx.GetCommand(query as IQueryable);
     SqlDataAdapter adapter = new SqlDataAdapter();
     adapter.SelectCommand = (SqlCommand)cmd;
     DataTable dt = new DataTable("sd");

     try
     {
          cmd.Connection.Open();
          adapter.FillSchema(dt, SchemaType.Source);
          adapter.Fill(dt);
     }
     finally
     {
          cmd.Connection.Close();
     }
     return dt;
}

For getting datatable

var vr = from country in objDataContext.CountryMaster
                        select new {country.CID,country.CName};

DataTable dt = ToDataTable(objDataContext,vr);

Original source : http://www.c-sharpcorner.com/uploadfile/VIMAL.LAKHERA/convert-a-linq-query-resultset-to-a-datatable/