Sunday, December 11, 2016

A lightweight shopping cart web application in ASP.NET MVC 5

http://bacaj.azurewebsites.net/a-lightweight-shopping-cart-web-application-in-asp-net-mvc-5/

git code: https://github.com/lbacaj/OpenOrderFramework

Thursday, December 4, 2014

C# When to use if else and when to use ternary operator



If you have any control flow, then use if else

int a = 1;
int b = 3;

// Use negated expression.
if (!(a == 1 && b == 2))
{
//Do some thing..
   Console.WriteLine(true);
}

// Use binary or version.
if (a != 1 || b != 2)
{//Do some thing..
   Console.WriteLine(true);
}


If you have any condition, based on condition if you want to assign any value then use ternary operator

Ex:
int input = Convert.ToInt32(Console.ReadLine());
string classify;
classify = (input < 0) ? "negative" : "positive";

Advantages of using ADO.NET

• All data in ADO.NET is transported in XML format
• ADO.NET can improve overall development time
• ADO.NET supports a variety of development needs
• ADO.NET can be used from all programming languages that target the .NET Framework

Tuesday, December 2, 2014

Error in Web parts after SharePoint platform upgrade



Using MOSS 2007 web part code, i have re build the VS 2010 SharePoint project. After deploying the webpart, i was getting error.

Solution:
I have added below tag in web.config

SafeControl Assembly="MyCustomWebpart, Version=12.0.0.0, Culture=neutral, PublicKeyToken=bdb4a6220fe9433c” Namespace="MyProject.UI.WebParts” TypeName="ListItemReport" Safe="True" SafeAgainstScript="True"

SharePoint remove and repair the broken Web Part



Some times, you will see some webparts shows error, but will not able to delete that web parts.
Using below url, you will able to delete the webparts.

http://SPO/default.aspx?contents=1

You will see all error-ed webparts, select webpart and delete.

Error occurred in deployment step 'Activate Features': Cannot start service SPUserCodeV4 on computer


Root Cause: Microsoft SharePoint Foundation Sandboxed Code Service is stopped.
Solution:
Open Central Administration site
go to System Settings
lick on Manage Service on server
Check to see if Microsoft SharePoint Foundation Sandboxed Code Service  is running, it should be stopped
Start the service and try deploying the Sandboxed solution

Monday, December 1, 2014

Migrate MOSS 2007 Custom webpart to SharePoint 2010


First Get MOSS 2007 code.

Open VS 2010
Create new Empty SharePoint Project.
Add New webpart.
Now delete .cs from solution.
Right click on Web part folder Add existing item.
Select .cs file from old MOSS 2007 code folder.
Save.
Build.
Resolve all references and errors.
Deploy...


Unable to display this web part. To troubleshoot the problem, open this web page in a Microsoft SharePoint Foundation-Compatible HTML editor such as Microsoft SharePoint Designer

Error: Unable to display this web part. To troubleshoot the problem, open this web page in a Microsoft SharePoint Foundation-Compatible HTML editor such as Microsoft SharePoint Designer. If the problem persists, contact your Web Server Administrator. Correlation ID.
Solution
This error occurs when the “AllowPersonalization” property of the Web Part Zone is set to false, and a user with less privilege tries to access the zone. This leads to the WebPartPageUsageException. This could be overcome by just setting the AllowPersonalization property to true.

Error parameter name ncolindex


parameter name ncolindex
This is a bug with SQL management studio and I need to use TSQL to attach the database
USE [master]
GO
CREATE DATABASE [WSS_Content_Databasename] ON
( FILENAME = N’E:\MSSQL\MSSQLSERVER.DB\Data01\WSS_Content_databasename.mdf’ ),
( FILENAME = N’E:\MSSQL\MSSQLSERVER.DB\Data01\WSS_Content_databasename_log.LDF’ )
FOR ATTACH
GO
if exists (select name from master.sys.databases sd where name = N’WSS_Content_databasename’ and SUSER_SNAME(sd.owner_sid) = SUSER_SNAME() ) EXEC [WSS_Content_databasename].dbo.sp_changedbowner @loginame=N’sa’, @map=false
GO

DATABASE Tuning

1) Return Multiple Resultsets

2) Connection Pooling and Object Pooling

3) Use SqlDataReader Instead of Dataset wherever it is possible

4) Keep Your Datasets Lean

5) Avoid Inefficient queries

6) Unnecessary round trips

7) Too many open connections

8) Avoid Transaction misuse

9) Avoid Over Normalized tables

10) Reduce Serialization

11) Do Not Use CommandBuilder at Run Time

12) Use Stored Procedures Whenever Possible

13) Avoid Auto-Generated Commands

14) Use Sequential Access as Often as Possible

How to set, Person or Group field to Empty or Null in SharePoint using JSOM


Today i was trying to set null value to Person or Group field.
It was not straight way..

Solution:

var objUser = new Array();
Assign empty array to column of type "Person or Group"
ojLstItem.set_item('MyPersonColumnName', objUser)

Monday, November 24, 2014

Microsoft.Online.SharePoint.Client.Tenant.dll location

I was trying to create Site Collection using client object model in SharePoint online.
I came to know Microsoft.Online.SharePoint.Client.Tenant.dll is required to create Site Collection using client object model in SharePoint online.
I was not able to find Microsoft.Online.SharePoint.Client.Tenant.dll
Solution:
Download: SharePoint Server 2013 Client Components SDK
From below url.
http://www.microsoft.com/en-au/download/details.aspx?id=35585
Now go to below path, you will find Microsoft.Online.SharePoint.Client.Tenant.dll
C:\Program Files\SharePoint Client Components\Assemblies\

Thursday, September 10, 2009

.Net-Insert Excel Data into Database

// Connection String to Excel Workbook
string excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Empinfo.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select * FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (OleDbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=SCSHYD-067\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "INA_EIS_EMOF_EMEM_OFFL";
bulkCopy.WriteToServer(dr);
}
}
}

SQl-Insert Excel Data into Database

/****** Object: StoredProcedure [dbo].[fs_prog_rt_InsertTransaction] Script Date: 09/10/2009 19:47:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:
-- Create date:
-- Description:
-- =============================================
CREATE PROCEDURE [dbo].[fs_prog_rt_InsertTransaction]
@xmlData XML,
@ErrorMessage varchar(500) OUTPUT
AS
BEGIN
BEGIN TRY
SET NOCOUNT ON;

DECLARE @SubId VARCHAR(20)
DECLARE @EntryType VARCHAR(50)
DECLARE @ContainerCode VARCHAR(20)
DECLARE @EquipmentId VARCHAR(20)
DECLARE @ProcessCode VARCHAR(20)
DECLARE @TestTypeCode VARCHAR(20)
DECLARE @CreatedByUserId VARCHAR(50)
DECLARE @CreatedTime VARCHAR(50)
DECLARE @idoc INT
DECLARE @LogId INT
DECLARE @return_Value INT
DECLARE @ValidationErrorMessage VARCHAR(500)

EXEC sp_xml_preparedocument @idoc OUTPUT, @xmlData

SELECT * into #temp_table FROM OPENXML (@idoc,'/NewDataSet/RT_Transaction',0)
WITH (LogId int 'LogId',
SubId varchar(50) 'SubId',
EntryType Varchar(50) 'EntryType',
ContainerCode varchar(50) 'ContainerCode',
CreatedByUserId varchar(10) 'CreatedByUserId',
ProcessCode varchar(100) 'ProcessCode',
EquipmentId varchar(50) 'EquipmentId',
TestTypeCode varchar(50) 'TestTypeCode',
CreatedTime varchar(100) 'CreatedTime')

EXEC sp_xml_removedocument @idoc

CREATE TABLE #temp_Errortable (
LogId int,
SubId varchar(50),EntryType Varchar(50),ContainerCode varchar(50),CreatedByUserId varchar(10),ProcessCode varchar(100),EquipmentId varchar(50),TestTypeCode varchar(50),CreatedTime varchar(100),ErrorMessage Varchar(250))




SELECT TOP 1 @LogId = [LOGID] FROM #temp_table

WHILE (ISNULL(@LogId,0) <> 0)
BEGIN
SELECT
@SubId = SubID,
@EntryType = EntryType,
@ContainerCode = ContainerCode,
@EquipmentId = EquipmentId,
@ProcessCode = ProcessCode,
@TestTypeCode = TestTypeCode,
@CreatedByUserId = CreatedByUserId,
@CreatedTime = CreatedTime
FROM #temp_table WHERE [LOGID] = @LogId

IF (@EntryType = 'Cart/Box')
BEGIN
EXEC @return_Value = dbo.RT_ValidateAndInsertCart @SubId,@EntryType,@ContainerCode,@CreatedByUserId,@ValidationErrorMessage OUTPUT,@ErrorMessage OUTPUT
END
ELSE
BEGIN
EXEC @return_Value = dbo.RT_ValidateAndInsertEquipment @SubId,@EntryType,@EquipmentId,@TestTypeCode,@ProcessCode,@CreatedByUserId,@ValidationErrorMessage OUTPUT,@ErrorMessage OUTPUT
END
IF (@ValidationErrorMessage <> '')
BEGIN
-- INSERT INTO #temp_Errortable SELECT LogId,SubId,EntryType,ContainerCode,CreatedByUserId,ProcessCode,EquipmentId,TestTypeCode,CreatedTime,@ValidationErrorMessage AS ErrorMessage FROM #temp_table Where LogId=@LogId
INSERT INTO #temp_Errortable Values(@LogId,@SubId,@EntryType,@ContainerCode,@CreatedByUserId,@ProcessCode,@EquipmentId,@TestTypeCode,@CreatedTime,@ValidationErrorMessage)
END

DELETE #temp_table WHERE [LOGID] = @LogId
set @LogId = 0
SELECT TOP 1 @LogId=[LOGID] FROM #temp_table
END

DROP TABLE #temp_table

Select * From #temp_Errortable
DROP TABLE #temp_Errortable
SET NOCOUNT OFF
END TRY
BEGIN CATCH
BEGIN
SELECT @ErrorMessage=ERROR_MESSAGE()
END
END CATCH
END

Monday, September 7, 2009

String Array

strEmployeeName="Tester(Test)";
///
/// It will return Full name and FQN
///

///
///
public string[] SplitEmployeeNameFQN(string strEmployeeName)
{
string[] strInputValue = strEmployeeName.Split(';');
string[] arrReturn = new string[2];
//string employeeName = string.Empty;
string strFQN = string.Empty;
for (int i = 0; i < strInputValue.Length; i++)
{
if (!(strInputValue[i] == ""))
{
int startIndex = strInputValue[i].IndexOf("(");
strFQN = strInputValue[i].Substring(startIndex + 1);
strFQN = strFQN.Replace(")", "");
arrReturn[0] += strFQN.Trim() + ";";
arrReturn[1] += strInputValue[i].Remove(startIndex).Trim() + ";";
}
}

return arrReturn;
}

Monday, August 24, 2009

SQL Search

CREATE PROCEDURE [dbo].[GetSparePartsECRETS]
(
@pnEcretsNum INT = NULL
,@pnvcEcretsTitle NVARCHAR(100) = NULL
,@pnvcOriginatorID NVARCHAR(50) = NULL
)
AS

BEGIN

/*SET NOCOUNT TO ON AND NO LONGER DISPLAY THE COUNT MESSAGE*/
SET NOCOUNT ON

/*START THE TRY BLOCK*/
BEGIN TRY
IF @pnEcretsNum = '' SET @pnEcretsNum = NULL
IF @pnvcEcretsTitle = '' SET @pnvcEcretsTitle = NULL
IF @pnvcOriginatorID = '' SET @pnvcOriginatorID = NULL

SELECT
TBLE.ECRETSID,
TBLE.[Title],
[TBEI].[FirstName] +' '+COALESCE([TBEI].[LastName],'') AS Originator
FROM dbo.tblECRETS TBLE,
dbo.TblEmployeeInfo TBEI
WHERE (TBLE.ECRETSID = @pnEcretsNum OR @pnEcretsNum IS NULL)
AND (TBLE.Title = @pnvcEcretsTitle OR @pnvcEcretsTitle IS NULL)
AND (TBLE.OriginatorID = @pnvcOriginatorID OR @pnvcOriginatorID IS NULL)
AND TBLE.OriginatorID = TBEI.FQN

END TRY
BEGIN CATCH
IF @@ERROR != 0
BEGIN
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_MESSAGE() AS ErrorMessage
END
END CATCH

/*Reset SET NOCOUNT to OFF*/
SET NOCOUNT OFF
END

Thursday, July 23, 2009

Web Services

1. Which attribute is used in order that the method can be used as WebService ?
WebMethod attribute has to be specified in order that the method and property can be treated as WebService.
2. Do webservice have state ?
Twist :- How can we maintain State in Webservices ?
Webservices as such do not have any mechanism by which they can maintain state.
3. How to Authentication for Web Services
using SOAP headers
4. HOW TO: Pass Current Credentials to an ASP.NET Web Service
myProxy.Credentials = System.Net.CredentialCache.DefaultCredentials
OR
localhost.MyWebService myService = new localhost.MyWebService();
System.Net.CredentialCache myCredentials = new System.Net.CredentialCache();
NetworkCredential netCred = new NetworkCredential("UserName", "Password");
myCredentials.Add(new Uri(myService.Url), "Basic", netCred);
myService.Credentials = myCredentials;
---------
DataSet dsPartDetails = new DataSet();
Item[] arrPartDetails = null;
arrPartDetails = objSrchPartsCommonMethods.GetPartService(vendorPartNum, manPartNum);
dsPartDetails = objSrchPartsCommonMethods.ConvertArrayToDataSet(arrPartDetails);
----------------------------------


public FirstSolarMasterDataServices.Item[] GetPartService(string partNumber, string manPartNum)
{
try
{
FirstSolarMasterDataServices.MasterData objFirstSolarERPWebService = new FirstSolarMasterDataServices.MasterData();
FirstSolarMasterDataServices.Item[] arrParts;

objFirstSolarERPWebService = ImpersonateDevUser();

//Calling Web services menthods
arrParts = objFirstSolarERPWebService.GetItems(ConfigurationManager.AppSettings["CompanyId"].ToString(), "", partNumber, "","",manPartNum);
return arrParts;
}
catch
{
throw;
}
//code used at Onsite
//comment this code at ODC

//finally
//{
// if (m_Ctx != null)
// {
// m_Ctx.Undo();
// }
//}
}

private FirstSolarMasterDataServices.MasterData ImpersonateDevUser()
{
FirstSolarMasterDataServices.MasterData objFirstSolarErpModifyWebService = new FirstSolarMasterDataServices.MasterData();

try
{
//code used at ODC
//comment this code at Onsite
//*************************************

NetworkCredential nwCredentials = new NetworkCredential();

nwCredentials.UserName = ConfigurationManager.AppSettings["NWUserName"].ToString();
nwCredentials.Password = ConfigurationManager.AppSettings["NWPassword"].ToString();
nwCredentials.Domain = ConfigurationManager.AppSettings["NWDomain"].ToString();

//Assignign credentials to web services
objFirstSolarErpModifyWebService.Credentials = new NetworkCredential(nwCredentials.UserName, nwCredentials.Password, nwCredentials.Domain);

//*************************************


//code used at Onsite
//comment this code at ODC
//*************************************

//m_Ctx = WindowsIdentity.GetCurrent().Impersonate();
//RevertToSelf();

//objFirstSolarERPModifyWebService.Url = ModifyWebService;

// //We have to authenticate ourselves with the web service.
//objFirstSolarERPModifyWebService.PreAuthenticate = true;
//objFirstSolarERPModifyWebService.Credentials = System.Net.CredentialCache.DefaultCredentials;

//*************************************
}
catch
{
throw;
}

return objFirstSolarErpModifyWebService;
}
------------------
Covert Arrat to Dataset
---
public DataSet ConvertArrayToDataSet(Object[] objArray)
{
XmlTextReader reader;
DataSet arrayDataSet = new DataSet();
MemoryStream memStream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(memStream, System.Text.Encoding.UTF8);
XmlSerializer serializer = new XmlSerializer(objArray.GetType());
try
{
serializer.Serialize(writer, objArray);
memStream.Position = 0;
reader = new XmlTextReader(memStream);
arrayDataSet.ReadXml(reader);

return arrayDataSet;
}
catch (Exception ex)
{
throw;
}
}

Tuesday, July 21, 2009

Use Data View

protected void BindEmployee()
{
ConnectDB objConnectDB = null;
SqlConnection objSqlConnection = null;
SqlCommand objSqlCommand = null;
SqlDataAdapter objSqlDataAdapter = null;
DataSet objDataSet = null;
try
{
objConnectDB = new ConnectDB();
objSqlConnection = objConnectDB.getConnection();
objDataSet = new DataSet();
//string strSQL = "SELECT GUID,FirstName+' '+coalesce(LastName,'') as FullName from TblEmployeeInfo where active=1 order by FirstName+' '+coalesce(LastName,'')";
string strSQL = "SELECT GUID, FirstName+' '+coalesce(LastName,'') as FullName, REPLACE(FirstName+' '+coalesce(LastName,''),'''','\\''') as FullNameRead from TblEmployeeInfo where active=1 order by FirstName+' '+coalesce(LastName,'')";

objSqlCommand = new SqlCommand(strSQL, objSqlConnection);
objSqlDataAdapter = new SqlDataAdapter(objSqlCommand);

objSqlDataAdapter.Fill(objDataSet);

if (txtFilter.Text == "")
{
grdvwEmployee.DataSource = objDataSet.Tables[0];
}
else
{
//DataView dv = new DataView(objDataSet.Tables[0], "FullName like '%" + txtFilter.Text.Trim() + "%'", "", DataViewRowState.CurrentRows);
DataView dv = new DataView(objDataSet.Tables[0], "FullName like '%" + txtFilter.Text.Trim().Replace("'", "") + "%'", "", DataViewRowState.CurrentRows);
grdvwEmployee.DataSource = dv;
}


grdvwEmployee.DataBind();


}
catch (Exception ex)
{
lblMsg.Text = "Error: " + ex.Message;
}
finally
{
objSqlCommand.Dispose();
objSqlDataAdapter.Dispose();
objDataSet.Dispose();
}
}

Monday, July 20, 2009

Get Selected result with Comma separate

CREATE TABLE dbo.tblItems
(
ItemID int NOT NULL IDENTITY (1, 1),
ItemName nvarchar(50) NOT NULL
) ON [PRIMARY]
GO
ALTER TABLE dbo.tblItems ADD CONSTRAINT
PK_Table_1 PRIMARY KEY CLUSTERED
( ItemID )
GO



Insert into dbo.tblItems (ItemName) Values ('Item1')
Insert into dbo.tblItems (ItemName) Values ('Item2')
Insert into dbo.tblItems (ItemName) Values ('Item3')
Insert into dbo.tblItems (ItemName) Values ('Item4')
Go


Declare @m_ItemsList nvarchar(2000)
Select @m_ItemsList=''
Select @m_ItemsList=@m_ItemsList+ItemName+',' from tblItems
Select Left(@m_ItemsList,Len(@m_ItemsList)-1)