Thursday, 23 August 2018

ngif to check null, undefined and empty + angular 5

<ng-template pTemplate="body" let-rowData let-columns="columns">
                <tr style="height:110px">
                    <td *ngFor="let col of columns" [style.width]="col.width" >
                        <div *ngIf = "rowData[col?.field] != ''">
                                {{rowData[col?.field] || rowData.Control[col?.field] || rowData.Turbo[col?.field]}}
                        </div>
                    </td>
                </tr>
            </ng-template>

Friday, 1 June 2018

Restore content databases in SharePoint Server

Refer : https://docs.microsoft.com/en-us/sharepoint/administration/restore-a-content-database


From SQL Server:

1) Right click on databases--> restore database-->Under General--->give name of database(which name you want to prefer)--> select back file from local machine-----> two files will be added
2)Options--->if you want to override you can ,orelse we can create new one-->ok


Thursday, 15 March 2018

Update HyperLinks in MS Word,MS Excel,MS Powerpoint using c#

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
using PPT = Microsoft.Office.Interop.PowerPoint;
using System.Text.RegularExpressions;

namespace UpdateUrls
{
    public partial class updatelinks : System.Web.UI.Page
    {
        string Insightdocuments = @"D:\Sireesha\POC\oldDocuments";
        string Archivedocuments = @"D:\Sireesha\POC\newDocuments";

        string srcText = "google";
        string replaceText = "youtube";


        object missing = Type.Missing;


        protected void Page_Load(object sender, EventArgs e)
        {
            DirectoryInfo di = new DirectoryInfo(Insightdocuments);
            FileInfo[] files = di.GetFiles().Where(f => !f.Attributes.HasFlag(FileAttributes.Hidden)).ToArray();
            for (int i = 0; i < files.Length; i++)
            {
                if (files[i].ToString().Contains(".docx") || files[i].ToString().Contains(".doc"))
                {
                    UpdateLinksInWord(files[i]);
                }
                else if (files[i].ToString().Contains(".xlsx") || files[i].ToString().Contains(".xls"))
                {
                    UpdateLinksInExcel(files[i]);
                }
                else
                {
                   UpdateLinksInPPT(files[i])
                }
            }

            Response.Write("Links has been updated from insight to archival system");

        }


url update in word

        private void UpdateLinksInWord(FileInfo file)
        {
            word.Application applicationObject = new word.Application();
            try
            {
                object fileurl = file.FullName;

                applicationObject.DisplayAlerts = word.WdAlertLevel.wdAlertsNone;
                word.Document documentObject = applicationObject.Documents.Open(fileurl);
                word.Hyperlinks links = documentObject.Hyperlinks;

                string currLinkAddress = string.Empty;
                string currLinkText = string.Empty;


                foreach (word.Hyperlink link in links)
                {
                    currLinkAddress = link.Address;
                    currLinkText = link.TextToDisplay;

                    if (Regex.IsMatch(currLinkAddress, srcText, RegexOptions.IgnoreCase))
                    {
                        link.Address = Regex.Replace(currLinkAddress, srcText, replaceText, RegexOptions.IgnoreCase);
                    }

                    if (Regex.IsMatch(currLinkText, srcText, RegexOptions.IgnoreCase))
                    {
                        link.TextToDisplay = Regex.Replace(currLinkText, srcText, replaceText, RegexOptions.IgnoreCase);

                    }
                }

                object archivaldoc = file.FullName.Replace(Insightdocuments, Archivedocuments);
                documentObject.SaveAs2(ref archivaldoc);

                documentObject.Close(true);
                applicationObject.Quit();
            }

            catch (Exception ex)
            {
                Response.Write("Exception in UpdateLinksInWord" + ex.Message);
            }
        }

url update in excel

        private void UpdateLinksInExcel(FileInfo file)
        {
            Excel.Application oExcel = new Excel.Application();
            try
            {
                //specify the file name where its actually exist
                string filepath = file.FullName;

                //pass that to workbook object
                Excel.Workbook WB = oExcel.Workbooks.Open(filepath);

                // statement get the workbookname
                string ExcelWorkbookname = WB.Name;

                // statement get the worksheet count
                int worksheetcount = WB.Worksheets.Count;

                for (int ws = 1; ws <= worksheetcount; ws++)
                {
                    Excel.Worksheet wks = (Excel.Worksheet)WB.Worksheets[ws];

                    // statement get the firstworksheetname
                    Excel.Hyperlinks excelinks = wks.UsedRange.Cells.Hyperlinks;

                    string currLink = string.Empty;
                    string TTD = string.Empty;

                    foreach (Excel.Hyperlink excellink in excelinks)
                    {
                        currLink = excellink.Address;

                        TTD = excellink.TextToDisplay;

                        if (Regex.IsMatch(currLink, srcText, RegexOptions.IgnoreCase))
                        {
                            excellink.Address = Regex.Replace(currLink, srcText, replaceText, RegexOptions.IgnoreCase);
                        }

                        if (Regex.IsMatch(TTD, srcText, RegexOptions.IgnoreCase))
                        {
                            excellink.TextToDisplay = Regex.Replace(TTD, srcText, replaceText, RegexOptions.IgnoreCase);
                        }
                    }
                }

                // Saves the modified file into Archive folder

                object UpdatedFile = file.FullName.Replace(Insightdocuments, Archivedocuments);

                WB.SaveAs(UpdatedFile, missing,
                    missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange);

                WB.Close(true);

                oExcel.Quit();
            }
            catch (Exception ex)
            {
                Response.Write("Exception in UpdateLinksInExcel" + ex.Message);
            }
        }

url update in ppt

private void UpdateLinksInPPT(FileInfo file)
        {
powerpoint.Application pptapp = new powerpoint.Application();
            powerpoint.Presentation presntn = pptapp.Presentations.Open(olddocuments ,MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
            foreach (powerpoint.Slide mSlide in presntn.Slides)
            {
                powerpoint.Hyperlinks links = mSlide.Hyperlinks;
                for (int i = 1; i <= links.Count; i++)
                {
                    powerpoint.Hyperlink mLink = links[i];
                    string currLinkAddress = mLink.Address;
                    string currLinkText = mLink.TextToDisplay;

                    if (Regex.IsMatch(currLinkAddress, srcText, RegexOptions.IgnoreCase))
                    {
                        mLink.Address = Regex.Replace(currLinkAddress, srcText, replaceText, RegexOptions.IgnoreCase);
                    }

                    if (Regex.IsMatch(currLinkText, srcText, RegexOptions.IgnoreCase))
                    {
                        mLink.TextToDisplay = Regex.Replace(currLinkText, srcText, replaceText, RegexOptions.IgnoreCase);
                    }
                }
            }
            presntn.SaveAs(newdocuments , powerpoint.PpSaveAsFileType.ppSaveAsDefault,MsoTriState.msoTrue);
            presntn.Close();
            pptapp.Quit();
}
    }
}

Wednesday, 7 March 2018

Convert an ASP.Net MVC Webpage HTML to PDF

1) Install  Install-Package Select.HtmlToPdf

We can directly install rotativa using package manager console (i.e View-> Package Manager Console) and then type  ---in console ---Install-Package Select.HtmlToPdf
Or
We can do by searching it from Nuget package manager (i.e Project-> Manage Nuget Packages-> search nuget-> Install).

In Installed just update that installed Select.HtmlToPdf.


Create below actions. Index action is default action provided by Visual Studio. GetPdfaction is used to generate the PDF of Index action using SelectPDF API.
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
        return View();
    }

    public ActionResult GetPdf()
    {
        var converter = new HtmlToPdf();
        var doc = converter.ConvertUrl("http://localhost:50265/Home/Index");
        doc.Save(System.Web.HttpContext.Current.Response, true, "test.pdf");
        doc.Close();

        return null;
    }
}
As shown in above code, we create an instance of HtmlToPdf() and then call its ConvertUrl(string url) to do the conversion. We write PdfDocument (output of ConvertUrlmethod) to HttpResponse stream. Finally close the document to release all the resources.
Run the application and navigate to /Home/GetPdf. We should get the PDF document as shown below.

Now lets make small changes in Index action to support Session usa

Thursday, 15 February 2018

Tuesday, 13 February 2018

How to get States,country,cities using ZipCode+javascript


1)you can use this api--https://api.zippopotam.us/us/


you can write the below code in any fucntion

function test()
{
var zip=90210;
  $.getJSON({
    url  : 'https://api.zippopotam.us/us/'+zip+'',  
    data : {
        sensor  : false
    },
    success : function( data, textStatus ) {
    debugger;
city =data.places[0].state
state =data.places["0"]["place name"]
country =data.country

    //pre-fill the city and state
    $('input[title="City"]').val(city);---//city textbox ID
    $('input[title="State Required Field"]').val(state);----//state textbox ID
    $('input[title="Country Required Field"]').val(country);----////country textbox ID
    }
});
});
}


Monday, 12 February 2018

Client Object Model Document Library to update metadata and file at a time

1)HTML for upload document

<head>
    <script src="jquery.min.js" type="text\javascript"></script>
</head>
<body>
<div>
<label>DocName:</label>
<input type="text" id="DocName" />
</div>
<div>
<label>User:</label>
<input type="text" id="Popuser" />
</div>
<div>
<input type="file" id="uploadFile" />
</div>
<div style="margin-top:20px;">
<button type="button" onclick="readFile()">Submit</button>
</div>
<script>

2)Get file from input tag

var fileInput;
$(document)
    .ready(function () {
    debugger;
        fileInput = $("#getFile");
        SP.SOD.executeFunc('sp.js', 'SP.ClientContext');
    });

var arrayBuffer;

function readFile() {
    debugger;
    //Get File Input Control and read th file name  
    //var element = $("#fileBtn").files[0];
    var element = document.getElementById("uploadFile");
    var file = element.files[0];
    var parts = element.value.split("\\");
    var fileName = parts[parts.length - 1];
 
    //Read File contents using file reader 
    var reader = new FileReader();
    reader.onload = function (e) {
        uploadFile(e.target.result, fileName);
    }
    reader.onerror = function (e) {
        alert(e.target.error);
    }
    reader.readAsArrayBuffer(file);
}
var attachmentFiles;

function uploadFile(arrayBuffer, fileName) {
    //Get Client Context,Web and List object.  
    var clientContext = new SP.ClientContext();
    var oWeb = clientContext.get_web();
    var oList = oWeb.get_lists().getByTitle('DocUpload');
 
    //Convert the file contents into base64 data  
 var bytes = new Uint8Array(arrayBuffer);
    var i, length, out = '';
    for (i = 0, length = bytes.length; i < length; i += 1) {
        out += String.fromCharCode(bytes[i]);
    }
    var base64 = btoa(out);
    //Create FileCreationInformation object using the read file data
    var createInfo = new SP.FileCreationInformation();
   
    createInfo.set_content(base64);
    createInfo.set_url(fileName);
 
    //Add the file to the library
    this.uploadedDocument = oList.get_rootFolder().get_files().add(createInfo)  
    //Load client context and execcute the batch
    listItem = uploadedDocument.get_listItemAllFields();
    listItem.set_item('docName', fileName);
    listItem.update();
    clientContext.load(uploadedDocument,'ListItemAllFields');  //here at a time we are loading uploading funtionality and get items AND update items
    clientContext.executeQueryAsync(Function.createDelegate(this, this.QuerySuccess), Function.createDelegate(this, this.QueryFailure));
}

function QuerySuccess() {
// if we want get curent upload item id ,we can use below line of code 
var id = uploadedDocument.get_listItemAllFields();
    console.log('File Uploaded Successfully.');
    alert("File Uploaded Successfully.");
}

function QueryFailure(sender, args) {
    console.log('Request failed with error message - ' + args.get_message() + ' . Stack Trace - ' + args.get_stackTrace());
alert("Request failed with error message - " + args.get_message() + " . Stack Trace - " + args.get_stackTrace());
}


</script>
</body>

Thursday, 8 February 2018

How to create a workflow for particular task and untill complete that task(Approved)

1)create a task(item) in TASKLIST then send email using send mail action

2)once submit the form we create task workflow  send mail to a person

2)click on open this task see the above image it will be redirected to tasklist for approving task

3) untill task complete it wont go for other line in workflow(in 4th line workflow).
4) once approve/reject the outcome column in task list will change as approved/rejected
5) based on that status we need to follow what ever action we need to do,we can.



Turn on support for multiple content types in a list or library AND In side contenttype Column order disable/enable


Turn on multiple content types in a library

  1. Open the library for which you want to enable multiple content types.
    Note:  You cannot enable multiple content types in the Wiki Library
  2. On the ribbon, underLibrary Tools, click the Library tab
  3. In theSettings group, click Library settings.
  4. In the General Settings section, select Advanced Settings.
  5. In the Content Types section, click Yes under Allow management of content types?
  6. Change any other settings that you want, and then click OK.
 In side content type Column order disable/enable

1) list setting-->  click on any specific content type-->Advanced Settings.--> Content type be read only Make it as yes

 see below image



Monday, 5 February 2018

difference-between-build-solution-rebuild-solution-and-clean-solution-in-visua

1)
  • Build solution will perform an incremental build: if it doesn't think it needs to rebuild a project, it won't. It may also use partially-built bits of the project if they haven't changed (I don't know how far it takes this)
  • Rebuild solution will clean and then build the solution from scratch, ignoring anything it's done before.
  • Clean solution will remove the build artifacts from the previous build. If there are any other files in the build target directories (bin and obj) they may not be removed, but actual build artifacts are. I've seen behaviour for this vary - sometimes deleting fairly thoroughly and sometimes not - but I'll give VS the benefit of the doubt for the moment :)

2)
Build solution: Compiles code files (DLL and EXE) which are changed.
Rebuild: Deletes all compiled files and compiles them again irrespective if the code has changed or not.
Clean solution: Deletes all compiled files (DLL and EXE file).
You can see this YouTube video (Visual Studio Build vs. Rebuild vs. Clean (C# interview questions with answers)) where I have demonstrated the differences and below are visual representations which will help you to analyze the same in more detail.

Build vs Rebuild


Rebuild Vs Clean

Thursday, 1 February 2018

Set login or any name to people picker column

<script src="https://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            ExecuteOrDelayUntilScriptLoaded(setLoginName, "clientpeoplepicker.js");
        });
    
        function setLoginName() {
            var loginName = _spPageContextInfo.userLoginName;
            var peoplePickerDiv = $("[id$='ClientPeoplePicker'][title='Name']");
            var peoplePickerEditor = peoplePickerDiv.find("[title='Name']");
            var spPeoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerDiv[0].id];
            peoplePickerEditor.val(loginName);
            spPeoplePicker.AddUnresolvedUserFromEditor(true);
        }
     </script>

Tuesday, 30 January 2018

how to put DLL in GAC(Global Assembly Cache)

how to put DLL in GAC(Global Assembly Cache)

If we put DLL in Gac means no need to deploy whole solution,we can proceed ....

C:\Windows\system32>

need to add DLL in GAC using this command

gacutil /i 

C:\Windows\system32> gacutil /i  "E:\BackUp\test\c\test\bin\Release\nameofDLL.dll"


DEBUGGING PROCESS

1)Build the solution
2) put dll in to GAC (or) deploy solution
3)reset IIS
4)Attach the process(in debug from ribbon)

Switch back to New Experience UI in Sharepoint

Switch back to New Experience UI



  • In your document library, choose Settings icon and then Library settings.
enter image description here


  • Click Advanced settings and then scroll down to List experience.
  • Choose New experience.
enter image description here

Create A Microsoft Flow That Saves Outlook Attachments To a SharePoint Library

Monday, 29 January 2018

Get list items from sharepoint site and assigning that values to one variable(IN SERVER SIDE)

Get list items from sharepoint site and assigning that values to one splistitemcollection(IN SERVER SIDE)

// Function to get selected PPElistitems
                                                    
    SPListItemCollection ProjectPPEsCol = GetSelectedPPEListItems("ProjectPPEs");


private SPListItemCollection GetSelectedPPEListItems(string listName)
        {
            SPListItemCollection spListItems = null;

            SPSecurity.RunWithElevatedPrivileges(delegate ()
            { 
                using (SPSite pSitecol = SPContext.Current.Site)
                {
                    using (SPWeb oWeb = pSitecol.OpenWeb())
                    {

                   SPList list = oWeb.Lists[listName];
// listname="ProjectPPEs";
                        SPQuery spQuery = new SPQuery();

                        // query.Query = "<Query><Where><And><Eq><FieldRef Name=;ProjectNumber;/><Value Type='Number'>" + Pid1
                        //+ "</Value></Eq><And><Eq><FieldRef Name = 'PNum3Digit'/><Value Type = 'Number' >" + Pid2
                        //+ "</ Value ></ Eq >< And >< Eq >< FieldRef Name = 'TaskNumber' />< Value Type = 'Number' >" + taskId
                        //+ "</ Value ></ Eq >< IsNotNull >< FieldRef Name = 'PPEIDs' /></ IsNotNull ></ And ></ And ></ And ></ Where ></ Query >";

                        spListItems = list.GetItems(spQuery);
                    }
                }
            });

            return spListItems;
        }

Get list items from sharepoint site and assigning that values to one string array(IN SERVER SIDE)

// Get selected PPE Text values

  string[] selectedPPEArrValues = GetSelectedPPETextArrayValue(ProjectPPEsCol,ProjNoPart1,ProjNo3DigPart2, TaskNo);

//Created separate function
private string[] GetSelectedPPETextArrayValue(SPListItemCollection selectedPPEListItemCol,string ProjNoPart1, string ProjNo3DigPart2, string taskNo)
        {
            string[] ppeTextArrValue = null;

            if (selectedPPEListItemCol != null)
            {
                string ppeTextValues = string.Empty;
                foreach (SPListItem listItem in selectedPPEListItemCol)
                {
                    if (listItem["PPEText"] != null && listItem["ProjectNumber"] != null && listItem["PNum3Digit"] != null && listItem["TaskNumber"] != null)

                    {
                        if (listItem["ProjectNumber"].ToString() == ProjNoPart1 && listItem["PNum3Digit"].ToString() == ProjNo3DigPart2 && listItem["TaskNumber"].ToString() == taskNo)
                        {

                            if (string.IsNullOrEmpty(ppeTextValues))
                            {

                                ppeTextValues = listItem["PPEText"].ToString();
                                if (ppeTextValues.StartsWith("|"))
                                {
                                    //ppeTextValues.Remove(0, 1);
                                    ppeTextValues.Substring(1);
                                }
                            }
                            else
                                ppeTextValues += "|" + listItem["PPEText"].ToString();

                        }
                    }
return ppeTextValues ;
                }

How to get the value from web.config(if any value assign as static Key)

Web.Config File:   <appSettings>     <add key="DomainName" value="PW" />     </appSettings> Cl...